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(external-chat): create a task from a WhatsApp message (#9595)
Wolf Mermelstein6bea0010a870
diff --git a/apps/web/src/features/external-chat/AGENTS.md b/apps/web/src/features/external-chat/AGENTS.mdindex 8f6068fd8b..e8fe6f4a28 100644--- a/apps/web/src/features/external-chat/AGENTS.md+++ b/apps/web/src/features/external-chat/AGENTS.md@@ -28,7 +28,8 @@ belong to `features/external-view`. Architecture:- `context/`: source and action contracts; no production imports.- `primitives/conversation.ts`: optimistic sends, idempotency keys, quietretries, reply/edit targets, uploads and read state.-- `components/`: supplied values and callbacks only.+- `components/`: supplied values and callbacks only; `message-media.tsx`+ holds a row's inline media.- `views/`: conversation composition, scroll and read lifecycle.- `queries/`: generated wire decoding, write-failure classification andproduction source construction (spans live here).@@ -65,6 +66,9 @@ belong to `features/external-view`. Architecture:- Refusals (`{code,message}` from DSS) remove the pending row, toast thereason and restore the draft only if the composer is empty.- Row actions are getters: `ChannelMessage` reads them once per row.+ Create task (`core/task.ts`) needs only view access; it sets no Source,+ because property entity references have no `external_chat` type, and its+ content mentions the chat (no message-level link exists).- Reads do not poll; DSS pushes `external_chat_changed`, with one fallbackre-fetch 3 s after opening. Only in-flight sends poll their progress.- History imported after adding (`backfill` on the detail) lands older thandiff --git a/apps/web/src/features/external-chat/components/message-media.tsx b/apps/web/src/features/external-chat/components/message-media.tsxnew file mode 100644index 0000000000..59d7f51efc--- /dev/null+++ b/apps/web/src/features/external-chat/components/message-media.tsx@@ -0,0 +1,71 @@+import { createMemo, mapArray, Show } from 'solid-js';+import { useExternalChat } from '../context/external-chat-context';+import { type InboundAttachment, inlineMediaKind } from '../core/attachments';+import { InboundMedia, type InboundMediaFile } from './inbound-media';++function sameMediaFile(+ a: InboundMediaFile | undefined,+ b: InboundMediaFile | undefined+): boolean {+ if (!a || !b) return a === b;+ return (Object.keys(a) as (keyof InboundMediaFile)[]).every(+ (key) => a[key] === b[key]+ );+}++/**+ * A message's images, video and voice notes, played inline. `sent` is what+ * this page showed for a file it sent: its local preview and size stand in+ * until the stored file loads.+ */+export function MessageMedia(props: {+ attachments: InboundAttachment[];+ sent?: InboundAttachment[];+}) {+ const source = useExternalChat();+ const media = createMemo(() =>+ props.attachments.flatMap((attachment, index) => {+ const local = props.sent?.[index];+ const file: InboundAttachment = local+ ? {+ ...attachment,+ previewUrl: attachment.previewUrl ?? local.previewUrl,+ width: attachment.width ?? local.width,+ height: attachment.height ?? local.height,+ }+ : attachment;+ const kind = inlineMediaKind(file);+ return kind ? [{ attachment: file, kind }] : [];+ })+ );+ const files = mapArray(+ () => media().map((file) => file.attachment.fileId ?? ''),+ (fileId, index) =>+ // One object per change, so Chat's media rows don't remount.+ createMemo(+ (): InboundMediaFile | undefined => {+ const file = media()[index()];+ if (!file) return undefined;+ return {+ id: fileId || `${file.attachment.ordinal}`,+ kind: file.kind,+ fileName: file.attachment.fileName,+ url: fileId ? source.fileUrl(fileId) : file.attachment.previewUrl,+ previewUrl: file.attachment.previewUrl,+ width: file.attachment.width,+ height: file.attachment.height,+ durationSeconds: file.attachment.durationSeconds,+ presentation: file.attachment.presentation,+ };+ },+ undefined,+ { equals: sameMediaFile }+ )+ );+ const shown = () => files().flatMap((file) => file() ?? []);+ return (+ <Show when={shown().length > 0}>+ <InboundMedia files={shown()} />+ </Show>+ );+}diff --git a/apps/web/src/features/external-chat/core/mentions.ts b/apps/web/src/features/external-chat/core/mentions.tsindex 50a13d2ba0..030e26dbb9 100644--- a/apps/web/src/features/external-chat/core/mentions.ts+++ b/apps/web/src/features/external-chat/core/mentions.ts@@ -1,3 +1,5 @@+import type { Mention } from './rich';+const USER_MENTION = /<m-user-mention>(.*?)<\/m-user-mention>/g;/** The digits WhatsApp shows after `@` for a participant id. */@@ -5,6 +7,15 @@ export function mentionToken(jid: string): string {return jid.split('@')[0]?.split(':')[0] ?? jid;}+/** `@<token>` for one of `mentions`, not inside a longer word or number. */+export function mentionPattern(mentions: Mention[]): RegExp | undefined {+ if (mentions.length === 0) return undefined;+ const tokens = [...new Set(mentions.map((mention) => mention.token))]+ .sort((a, b) => b.length - a.length)+ .map((token) => token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));+ return new RegExp(`@(${tokens.join('|')})(?![\\p{L}\\p{N}])`, 'gu');+}+/*** The composer's mention chips for group participants, turned into the* `@<digits>` text WhatsApp shows and the participant ids it notifies.diff --git a/apps/web/src/features/external-chat/core/task.test.ts b/apps/web/src/features/external-chat/core/task.test.tsnew file mode 100644index 0000000000..9fc4a16345--- /dev/null+++ b/apps/web/src/features/external-chat/core/task.test.ts@@ -0,0 +1,50 @@+import { expect, it } from 'vitest';+import { chat, messages } from '../tests/fake-capabilities';+import { messageTask } from './task';++it('titles a task from the message text and assigns the Macro users it mentions', () => {+ expect(+ messageTask(+ {+ ...messages[0],+ mentions: [+ {+ token: '14155550100',+ name: 'Ana Ruiz',+ userId: 'macro|[email protected]',+ },+ { token: '14155550111', name: 'Bo Chen' },+ ],+ body: '@14155550100 please send @14155550111 the *updated* designs before the review on Friday morning',+ },+ chat+ )+ ).toEqual({+ title:+ 'please send @Bo Chen the *updated* designs before the review on Friday...',+ content:+ '<m-document-mention>{"documentId":"019a061e-0000-7000-8000-000000000001","documentName":"Design Crit","blockName":"external_chat"}</m-document-mention>',+ assigneeIds: ['macro|[email protected]'],+ });+});++it('makes no task from pending, deleted or system rows', () => {+ expect(messageTask({ ...messages[0], pending: true }, chat)).toBeUndefined();+ expect(messageTask({ ...messages[0], deleted: true }, chat)).toBeUndefined();+ expect(+ messageTask(+ {+ ...messages[0],+ kind: 'system',+ body: '',+ rich: {+ type: 'system',+ action: 'call',+ participants: [],+ call: { video: true, outcome: 'missed' },+ },+ },+ chat+ )+ ).toBeUndefined();+});diff --git a/apps/web/src/features/external-chat/core/task.ts b/apps/web/src/features/external-chat/core/task.tsnew file mode 100644index 0000000000..10828df29a--- /dev/null+++ b/apps/web/src/features/external-chat/core/task.ts@@ -0,0 +1,73 @@+import { buildMentionMarkdownString } from '@macro-inc/lexical-core';+import type { ChatDetail, ChatMessage } from './chat';+import { mentionPattern } from './mentions';+import type { Mention } from './rich';++const TITLE_LENGTH = 70;++/** A message as a new task, the way Chat creates one from a message. */+export type MessageTask = {+ title: string;+ /** A mention that opens the chat. */+ content: string;+ /** Macro users the message mentions. */+ assigneeIds: string[];+};++/**+ * The message's text with each mention as `@<name>`. Macro users mentioned+ * at either end are left out: they become the assignees, as in Chat.+ */+function titleText(message: ChatMessage): string {+ const pattern = mentionPattern(message.mentions);+ if (!pattern) return message.body.trim();++ const parts: (string | Mention)[] = [];+ let last = 0;+ for (const found of message.body.matchAll(pattern)) {+ const mention = message.mentions.find((each) => each.token === found[1]);+ if (!mention) continue;+ parts.push(message.body.slice(last, found.index), mention);+ last = found.index + found[0].length;+ }+ parts.push(message.body.slice(last));++ const atEdge = (part: string | Mention | undefined) =>+ typeof part === 'string' ? part.trim() === '' : !!part?.userId;+ while (parts.length > 0 && atEdge(parts[0])) parts.shift();+ while (parts.length > 0 && atEdge(parts.at(-1))) parts.pop();++ return parts+ .map((part) => (typeof part === 'string' ? part : `@${part.name}`))+ .join('')+ .trim();+}++/**+ * Anyone who can see the chat can make a task from a message; pending,+ * deleted and system rows have none.+ */+export function messageTask(+ message: ChatMessage,+ chat: Pick<ChatDetail, 'id' | 'name'>+): MessageTask | undefined {+ if (message.pending || message.deleted) return undefined;+ if (message.kind === 'system') return undefined;++ const text = titleText(message);+ const assigneeIds = message.mentions.flatMap((mention) =>+ mention.userId ? [mention.userId] : []+ );++ return {+ title:+ text.length > TITLE_LENGTH ? `${text.slice(0, TITLE_LENGTH)}...` : text,+ content: buildMentionMarkdownString({+ type: 'document',+ documentId: chat.id,+ documentName: chat.name,+ blockName: 'external_chat',+ }),+ assigneeIds: [...new Set(assigneeIds)],+ };+}diff --git a/apps/web/src/features/external-chat/providers/whatsapp/formatting.ts b/apps/web/src/features/external-chat/providers/whatsapp/formatting.tsindex ab56118d81..548d128dbb 100644--- a/apps/web/src/features/external-chat/providers/whatsapp/formatting.ts+++ b/apps/web/src/features/external-chat/providers/whatsapp/formatting.ts@@ -4,6 +4,7 @@* renderer speak Markdown. These convert at the send and display edges.*/+import { mentionPattern } from '../../core/mentions';import type { Mention } from '../../core/rich';const FENCE = /^```/;@@ -100,15 +101,6 @@ function urlLink(url: string): string {}const MARKDOWN_FOR: Record<string, string> = { '*': '**', _: '*', '~': '~~' };-/** `@<token>` for one of `mentions`, not inside a longer word or number. */-function mentionPattern(mentions: Mention[]): RegExp | undefined {- if (mentions.length === 0) return undefined;- const tokens = [...new Set(mentions.map((mention) => mention.token))]- .sort((a, b) => b.length - a.length)- .map((token) => token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));- return new RegExp(`@(${tokens.join('|')})(?![\\p{L}\\p{N}])`, 'gu');-}-/** `macro|[email protected]` → its email; the mention chip resolves the name. */function macroEmail(userId: string): string | undefined {return userId.startsWith('macro|')diff --git a/apps/web/src/features/external-chat/views/external-chat-view.test.tsx b/apps/web/src/features/external-chat/views/external-chat-view.test.tsxindex 7ef9ab1a79..643300105d 100644--- a/apps/web/src/features/external-chat/views/external-chat-view.test.tsx+++ b/apps/web/src/features/external-chat/views/external-chat-view.test.tsx@@ -21,7 +21,20 @@ const mocks = vi.hoisted(() => ({restore: vi.fn(),focus: vi.fn(),failure: vi.fn(),+ popoverSplit: vi.fn(),}));+vi.mock('@components/app/split-layout/layout', async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import('@components/app/split-layout/layout')+ >();+ return {+ useSplitLayout: () => ({+ ...actual.useSplitLayout(),+ popoverSplit: mocks.popoverSplit,+ }),+ };+});vi.mock('@core/context/user', () => ({useUserId: () => () => 'macro|[email protected]',}));@@ -190,6 +203,44 @@ it('lets a viewer without WhatsApp read and offers to connect', () => {expect(connect).toHaveBeenCalledOnce();});+it('makes a task from a message for a viewer who cannot reply', () => {+ const fake = createFakeChat({+ chat: {+ ...chat,+ accessLevel: 'view',+ canSend: false,+ sendReason: 'no_account',+ },+ });+ mount(fake);+ const row = document.querySelector('[data-message-id="message-1"]');+ if (!row) throw new Error('message row missing');+ fireEvent.pointerEnter(row);+ expect(screen.queryByRole('button', { name: 'Reply' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Task' }));+ expect(mocks.popoverSplit).toHaveBeenCalledWith({+ type: 'component',+ id: 'task-compose',+ params: {+ initialTitle: 'The *updated* designs are ready for review.',+ initialContent:+ '<m-document-mention>{"documentId":"019a061e-0000-7000-8000-000000000001","documentName":"Design Crit","blockName":"external_chat"}</m-document-mention>',+ initialAssigneeIds: undefined,+ },+ });+});++it('offers no task on a deleted message', () => {+ const fake = createFakeChat({+ messages: [{ ...messages[0], deleted: true }],+ });+ mount(fake);+ const row = document.querySelector('[data-message-id="message-1"]');+ if (!row) throw new Error('message row missing');+ fireEvent.pointerEnter(row);+ expect(screen.queryByRole('button', { name: 'Task' })).toBeNull();+});+it('offers actions on rows that rendered before the viewer could send', () => {const fake = createFakeChat({chat: { ...chat, canSend: false, sendReason: 'disconnected' },diff --git a/apps/web/src/features/external-chat/views/external-chat-view.tsx b/apps/web/src/features/external-chat/views/external-chat-view.tsxindex abe79ac562..6d07b547cc 100644--- a/apps/web/src/features/external-chat/views/external-chat-view.tsx+++ b/apps/web/src/features/external-chat/views/external-chat-view.tsx@@ -14,6 +14,7 @@ import { MaybeMessageActionDrawerManager } from '@channel/Mobile/MessageActionDrimport { HeaderActionGroup } from '@components/app/HeaderActionGroup';import { FloatRegionOrInline } from '@components/app/mobile/float-regions/FloatRegion';import { SidePanel, useSidePanel } from '@components/app/side-panel';+import { useSplitLayout } from '@components/app/split-layout/layout';import { CustomScrollbar } from '@core/component/CustomScrollbar';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { toast } from '@core/component/Toast/Toast';@@ -34,7 +35,6 @@ import {createSignal,For,type JSX,- mapArray,onCleanup,onMount,Show,@@ -43,14 +43,11 @@ import { Dynamic } from 'solid-js/web';import { match } from 'ts-pattern';import { ChatDetails } from '../components/chat-details';import { AttachmentChip } from '../components/inbound-attachment';-import {- InboundMedia,- type InboundMediaFile,-} from '../components/inbound-media';+import { MessageMedia } from '../components/message-media';import { RichCard } from '../components/rich-cards';import { ExternalChatSystemLine } from '../components/system-line';import { useExternalChat } from '../context/external-chat-context';-import { type InboundAttachment, inlineMediaKind } from '../core/attachments';+import { inlineMediaKind } from '../core/attachments';import {backfillStatus,type ChatDetail,@@ -65,6 +62,7 @@ import {import { mentionToken } from '../core/mentions';import { chatMessageData, senderKey } from '../core/message-data';import { richPreview } from '../core/rich';+import { messageTask } from '../core/task';import {type ConversationTarget,createConversation,@@ -116,73 +114,6 @@ function ForwardedTag() {);}-function sameMediaFile(- a: InboundMediaFile | undefined,- b: InboundMediaFile | undefined-): boolean {- if (!a || !b) return a === b;- return (Object.keys(a) as (keyof InboundMediaFile)[]).every(- (key) => a[key] === b[key]- );-}--/**- * A message's images, video and voice notes, played inline. `sent` is what- * this page showed for a file it sent: its local preview and size stand in- * until the stored file loads.- */-function MessageMedia(props: {- attachments: InboundAttachment[];- sent?: InboundAttachment[];-}) {- const source = useExternalChat();- const media = createMemo(() =>- props.attachments.flatMap((attachment, index) => {- const local = props.sent?.[index];- const file: InboundAttachment = local- ? {- ...attachment,- previewUrl: attachment.previewUrl ?? local.previewUrl,- width: attachment.width ?? local.width,- height: attachment.height ?? local.height,- }- : attachment;- const kind = inlineMediaKind(file);- return kind ? [{ attachment: file, kind }] : [];- })- );- const files = mapArray(- () => media().map((file) => file.attachment.fileId ?? ''),- (fileId, index) =>- // One object per change, so Chat's media rows don't remount.- createMemo(- (): InboundMediaFile | undefined => {- const file = media()[index()];- if (!file) return undefined;- return {- id: fileId || `${file.attachment.ordinal}`,- kind: file.kind,- fileName: file.attachment.fileName,- url: fileId ? source.fileUrl(fileId) : file.attachment.previewUrl,- previewUrl: file.attachment.previewUrl,- width: file.attachment.width,- height: file.attachment.height,- durationSeconds: file.attachment.durationSeconds,- presentation: file.attachment.presentation,- };- },- undefined,- { equals: sameMediaFile }- )- );- const shown = () => files().flatMap((file) => file() ?? []);- return (- <Show when={shown().length > 0}>- <InboundMedia files={shown()} />- </Show>- );-}-export function ExternalChatView(props: {userId?: string;leading?: JSX.Element;@@ -212,6 +143,7 @@ export function ExternalChatView(props: {});const [deleting, setDeleting] = createSignal<string>();const sidePanel = useSidePanel();+ const { popoverSplit } = useSplitLayout();// The floating details card covers the right of the pane; where the pane// is wide enough, the timeline and composer make room for it instead.const detailsBeside = () => !isTouchDevice() && !!sidePanel?.isOpen();@@ -470,6 +402,23 @@ export function ExternalChatView(props: {}: undefined;},+ get onCreateTask() {+ const group = source.chat.data;+ const task = group && messageTask(message, group);+ if (!task) return undefined;+ return () => {+ popoverSplit({+ type: 'component',+ id: 'task-compose',+ params: {+ initialTitle: task.title,+ initialContent: task.content,+ initialAssigneeIds:+ task.assigneeIds.length > 0 ? task.assigneeIds : undefined,+ },+ });+ };+ },};};diff --git a/apps/web/tests/functional/whatsapp-linked.spec.ts b/apps/web/tests/functional/whatsapp-linked.spec.tsindex 1ca28f152d..4341ad32e6 100644--- a/apps/web/tests/functional/whatsapp-linked.spec.ts+++ b/apps/web/tests/functional/whatsapp-linked.spec.ts@@ -1551,10 +1551,51 @@ test('a shared viewer can read without connecting WhatsApp', async ({await expect(page.getByRole('button', { name: 'Edit', exact: true })).toHaveCount(0);+ // Making a task needs only read access.+ await page.locator('[data-message-id="message-1"]').hover();+ await expect(+ page.getByRole('button', { name: 'Task', exact: true })+ ).toBeVisible();expect(state.outgoing).toEqual([]);expect(unexpected).toEqual([]);});+test.describe('phone task', () => {+ test.use({+ viewport: { width: 390, height: 844 },+ isMobile: true,+ hasTouch: true,+ });+ test('a shared viewer makes a task from the action drawer', async ({+ page,+ }) => {+ const state = server();+ state.canSend = false;+ const unexpected = await mount(page, state, `?chat=${CHAT_ID}`);+ const row = page.locator('[data-message-id="message-1"]');+ await expect(row).toBeVisible();+ const box = await row.boundingBox();+ if (!box) throw new Error('message row has no box');+ const touch = {+ identifier: 1,+ clientX: box.x + box.width / 2,+ clientY: box.y + box.height / 2,+ };+ await row.dispatchEvent('touchstart', {+ touches: [touch],+ changedTouches: [touch],+ });+ await expect(+ page.getByRole('button', { name: 'Create task', exact: true })+ ).toBeVisible();+ await row.dispatchEvent('touchend', {+ touches: [],+ changedTouches: [touch],+ });+ expect(unexpected).toEqual([]);+ });+});+for (const mobile of [false, true]) {test.describe(`${mobile ? 'mobile' : 'desktop'} group`, () => {test.use({diff --git a/docs/agent-guide/external.md b/docs/agent-guide/external.mdindex 5d481c0233..abf43f904c 100644--- a/docs/agent-guide/external.md+++ b/docs/agent-guide/external.md@@ -135,6 +135,15 @@ The detail's `limits` supplies allowed MIME types, bytes and the edit window.The owner may stop syncing (details → **Syncing**, groups and direct chats) with`DELETE /external-chats/<id>`; history remains readable.+Any viewer, including one who can't reply, can make a task from a message:+**Task** in the row's hover toolbar, or **Create task** in the touch action+drawer, opens the task composer titled with the first 70 characters of the+text (mentions as `@<name>`; Macro users mentioned at either end are left out+and preselected as assignees) and a mention of the chat as its content. The+mention opens the chat, not the message. The task has no **Source**: the+properties service's entity references don't include external chats. Pending,+deleted and system rows have no task action.+After adding, earlier messages (up to 500 messages or 90 days) come from theowner's phone only when they press Import. While a chat is`waiting_for_phone`, its owner sees a bar under the chat header ("Open