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(channels): create DMs on the first message, not when opening a person (#9341)

teo25666e8ea80a
diff --git a/apps/web/src/features/block-call/component/CallRecording/CallRecordingParticipants.tsx b/apps/web/src/features/block-call/component/CallRecording/CallRecordingParticipants.tsx
index d777709c3c..a02d1453c6 100644
--- a/apps/web/src/features/block-call/component/CallRecording/CallRecordingParticipants.tsx
+++ b/apps/web/src/features/block-call/component/CallRecording/CallRecordingParticipants.tsx
@@ -1,8 +1,7 @@
-import { useSplitLayout } from '@components/app/split-layout/layout';
import { UserIcon } from '@core/component/UserIcon';
import { idToEmail } from '@core/user';
-
-import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { useOpenDirectMessage } from '@core/util/open-direct-message';
import type { CallRecord } from '@service-call/client';
import { createMemo, For } from 'solid-js';
import { dedupeCallRecordingParticipants } from './call-recording-utils';
@@ -10,8 +9,7 @@ import { dedupeCallRecordingParticipants } from './call-recording-utils';
export function CallRecordingParticipantsSection(props: {
record: CallRecord;
}) {
- const { openWithSplit } = useSplitLayout();
- const getOrCreateDmMutation = useGetOrCreateDirectMessageMutation();
+ const openDm = useOpenDirectMessage();
const participants = createMemo(() =>
dedupeCallRecordingParticipants(
props.record.participants,
@@ -21,16 +19,9 @@ export function CallRecordingParticipantsSection(props: {
const guests = () => props.record.guests;
const openDirectMessage = (participantId: string, event: MouseEvent) => {
- getOrCreateDmMutation.mutate(
- { recipient_id: participantId },
- {
- onSuccess: ({ channel_id }) => {
- openWithSplit(
- { type: 'channel', id: channel_id },
- { activate: true, preferNewSplit: event.shiftKey }
- );
- },
- }
+ fireAndForget(
+ openDm(participantId, { activate: true, preferNewSplit: event.shiftKey }),
+ 'call-recording-participants'
);
};
diff --git a/apps/web/src/features/block-channel/component/Compose.tsx b/apps/web/src/features/block-channel/component/Compose.tsx
index 0c8d727cb4..56f33d1e50 100644
--- a/apps/web/src/features/block-channel/component/Compose.tsx
+++ b/apps/web/src/features/block-channel/component/Compose.tsx
@@ -1,32 +1,15 @@
import { useAgentDmRecipients } from '@app/features/agent-dms/agent-dm-recipients';
import { selectConversationRecipients } from '@app/features/agent-dms/core/personas';
-import {
- applyInlineFormat,
- applyNodeFormat,
- buildPostMessageRequest,
- createConfiguredChannelMarkdownEditor,
- createInputAttachmentTracker,
- createInputState,
- createMentionsTracker,
- FormatButtons,
- Input,
- type InputSnapshot,
- uploadInputAttachments,
-} from '@channel/Input';
-import { ChannelInputContainer } from '@channel/Input/ChannelInputContainer';
-import { FloatRegionOrInline } from '@components/app/mobile/float-regions/FloatRegion';
+import { buildPostMessageRequest, type InputSnapshot } from '@channel/Input';
+import { DraftComposer } from '@channel/Input/DraftComposer';
import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';
import {
SplitHeaderBadge,
StaticSplitLabel,
} from '@components/app/split-layout/components/SplitLabel';
import { SplitToolbarLeft } from '@components/app/split-layout/components/SplitToolbar';
-import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-router/mention-links';
-import { ComposerEditor } from '@core/component/LexicalMarkdown/component/ComposerEditor';
-import { createComposerLayout } from '@core/component/LexicalMarkdown/utils/create-composer-layout';
import { RecipientSelector } from '@core/component/RecipientSelector';
import { ENABLE_AGENT_DMS } from '@core/constant/featureFlags';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';
import {
getDisplayName,
@@ -35,22 +18,12 @@ import {
} from '@core/user';
import { useSendMessageToPeople } from '@core/util/channels';
import { getDestinationFromOptions } from '@core/util/destination';
-import { fireAndForget } from '@core/util/fireAndForget';
-import { isPlatform } from '@core/util/platform';
-import {
- chatRuleset,
- handleFileFolderDrop,
- uploadFile,
-} from '@core/util/upload';
import InfoIcon from '@icon/system/regular/info.svg';
-import { Telemetry } from '@macro-inc/observability';
import { useCreateChannelMutation } from '@queries/channel/channels';
import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';
-import { ComposerSurface } from '@ui';
-import { createEffect, createMemo, createSignal, on, Show } from 'solid-js';
+import { createEffect, createMemo, createSignal, on } from 'solid-js';
export function ChannelCompose() {
- const [layout, setLayout] = createSignal<HTMLDivElement>();
const [channelName, setChannelName] = createSignal<string>('');
const { users: humanOptions } = useCombinedRecipients();
@@ -121,18 +94,14 @@ export function ChannelCompose() {
}
});
- const [error, setError] = createSignal<string>();
-
const { sendToUsers, sendToChannel } = useSendMessageToPeople();
const createChannelMutation = useCreateChannelMutation();
const createDm = useGetOrCreateDirectMessageMutation();
async function handleSend(snapshot: InputSnapshot) {
- setError(undefined);
const recipients = selectedRecipients();
if (recipients.length === 0) {
- setError('Please select at least one recipient');
throw new Error('Please select at least one recipient');
}
@@ -141,128 +110,51 @@ export function ChannelCompose() {
snapshot,
});
- try {
- const persona = recipients.find(
- (recipient) => recipient.kind === 'agent'
- );
- if (persona) {
- const dm = await createDm.mutateAsync({
- recipient_id: `bot|${persona.data.id}`,
- });
- const sent = await sendToChannel({
- channelId: dm.channel_id,
- content,
- mentions,
- attachments,
- navigate: { navigate: true, mergeHistory: true },
- });
- if (!sent)
- throw new Error(
- 'Could not send your message. Your draft has been kept.'
- );
- return;
- }
- if (
- destination.type === 'users' &&
- channelName() &&
- destination.users.length > 1
- ) {
- const { id } = await createChannelMutation.mutateAsync({
- channel_type: 'private',
- name: channelName() ?? null,
- participants: destination.users,
- });
- await sendToChannel({
- channelId: id,
- content,
- mentions,
- attachments,
- navigate: { navigate: true, mergeHistory: true },
- });
- } else {
- await sendToUsers({
- users: destination.users,
- content,
- mentions,
- attachments,
- navigate: { navigate: true, mergeHistory: true },
- });
- }
- } catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to send message');
- throw e;
- }
- }
-
- const mentionsTracker = createMentionsTracker();
- const attachmentTracker = createInputAttachmentTracker();
- let clearComposer = () => {};
-
- const inputState = createInputState({
- initialInput: { mode: 'channel' as const },
- mentions: mentionsTracker.mentions,
- attachmentTracker,
- clearComposer: () => clearComposer(),
- attachFiles: async (files) => {
- await uploadInputAttachments({
- files,
- tracker: attachmentTracker,
- uploadFile: async (file) =>
- uploadFile(file, chatRuleset, { hideProgressIndicator: true }),
+ const persona = recipients.find((recipient) => recipient.kind === 'agent');
+ if (persona) {
+ const dm = await createDm.mutateAsync({
+ recipient_id: `bot|${persona.data.id}`,
});
- },
- clearInput: () => markdownEditor.controls.clear(),
- callbacks: { onSend: handleSend },
- });
-
- const send = async () => {
- try {
- await inputState.commands.send();
- } catch (sendError) {
- // `handleSend` shows its own failures in the compose error and rethrows.
- if (error()) return;
- setError('Failed to send message');
- Telemetry.error(sendError, { surface: 'channel-compose' });
+ const sent = await sendToChannel({
+ channelId: dm.channel_id,
+ content,
+ mentions,
+ attachments,
+ navigate: { navigate: true, mergeHistory: true },
+ });
+ if (!sent)
+ throw new Error(
+ 'Could not send your message. Your draft has been kept.'
+ );
+ return;
}
- };
-
- const [scrollContainer, setScrollContainer] = createSignal<HTMLElement>();
-
- const markdownEditor = createConfiguredChannelMarkdownEditor({
- namespace: 'compose-input-markdown',
- resolveAppLink: useMacroMentionLinkResolver(),
- enableMentions: true,
- scrollContainer,
- onMentionCreate: (mention) => mentionsTracker.onMentionCreate(mention),
- onMentionRemove: (mention) => mentionsTracker.onMentionRemove(mention),
- onChange: (markdown) => inputState.setValue(markdown),
- onEnter: () => {
- if (isTouchDevice()) return false;
- fireAndForget(send(), 'channel-compose');
- return true;
- },
- sendMessage: () => fireAndForget(send(), 'channel-compose'),
- onPasteFilesAndDirs: (files, directories) => {
- fireAndForget(
- handleFileFolderDrop(files, directories, (entries) =>
- inputState.commands.attachFiles(entries.map((e) => e.file))
- ),
- 'channel-compose'
- );
- },
- });
- clearComposer = () => markdownEditor.controls.clear();
- const { isCompact: oneLineInput } = createComposerLayout(
- markdownEditor.buildHandle().lexical,
- {
- container: layout,
- mode: () =>
- inputState.view().showFormatRibbon ||
- inputState.view().attachments?.length
- ? 'expanded'
- : 'auto',
+ if (
+ destination.type === 'users' &&
+ channelName() &&
+ destination.users.length > 1
+ ) {
+ const { id } = await createChannelMutation.mutateAsync({
+ channel_type: 'private',
+ name: channelName() ?? null,
+ participants: destination.users,
+ });
+ await sendToChannel({
+ channelId: id,
+ content,
+ mentions,
+ attachments,
+ navigate: { navigate: true, mergeHistory: true },
+ });
+ } else {
+ await sendToUsers({
+ users: destination.users,
+ content,
+ mentions,
+ attachments,
+ navigate: { navigate: true, mergeHistory: true },
+ });
}
- );
+ }
const placeholder = createMemo(() => {
const name = channelName();
@@ -324,83 +216,7 @@ export function ChannelCompose() {
</div>
</div>
</div>
- {/* Full-frame mobile: error + composer float in the bottom accessory
- region above the dock; desktop renders them inline as before. */}
- <FloatRegionOrInline region="accessory">
- <Show when={error()}>
- <div class="shrink-0 w-full @min-[40rem]:px-4 touch:px-(--mobile-chrome-gutter)">
- <div class="mx-auto w-full macro-message-width macro-message-padding">
- <div class="text-sm font-mono text-failure-ink">{error()}</div>
- </div>
- </div>
- </Show>
- {/* ChannelInputContainer owns the mobile chrome gutter, so drop the
- desktop px-2 there. */}
- <div class="px-2 touch:px-0">
- <ChannelInputContainer>
- <Input.Root
- input={inputState.view()}
- commands={inputState.commands}
- >
- <ComposerSurface>
- <Input.DropZone
- onDragStart={(valid) => inputState.setIsDraggedOver(valid)}
- onDragEnd={() => inputState.setIsDraggedOver(false)}
- >
- <Input.Layout ref={setLayout} oneLineInput={oneLineInput()}>
- <Input.DropOverlay />
- <Input.Layout.Body>
- <Input.FormatRibbon>
- <FormatButtons
- selectionState={() => markdownEditor.selection}
- onInlineFormat={(format) =>
- applyInlineFormat(markdownEditor.lexical, format)
- }
- onNodeFormat={(format) =>
- applyNodeFormat(markdownEditor.lexical, format)
- }
- />
- </Input.FormatRibbon>
- <Input.Layout.Editor
- ref={setScrollContainer}
- on:click={(event) => {
- if (!isTouchDevice()) {
- event.stopPropagation();
- markdownEditor.controls.focus();
- }
- }}
- >
- <Input.Editor>
- <ComposerEditor
- config={markdownEditor}
- placeholder={placeholder()}
- autofocus={false}
- class="text-base"
- />
- </Input.Editor>
- </Input.Layout.Editor>
- <Input.Attachments kind="media" />
- <Input.Attachments kind="document" />
- </Input.Layout.Body>
-
- <Input.Layout.ActionsLeft>
- <Show
- when={!isPlatform('ios')}
- fallback={<Input.AttachNativeMediaAction />}
- >
- <Input.AttachFilesAction />
- </Show>
- </Input.Layout.ActionsLeft>
- <Input.Layout.ActionsRight>
- <Input.SendAction />
- </Input.Layout.ActionsRight>
- </Input.Layout>
- </Input.DropZone>
- </ComposerSurface>
- </Input.Root>
- </ChannelInputContainer>
- </div>
- </FloatRegionOrInline>
+ <DraftComposer placeholder={placeholder()} onSend={handleSend} />
</div>
</>
);
diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx
index 8f3686de59..8eaf4b25c7 100644
--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx
+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx
@@ -66,6 +66,7 @@ vi.mock('@channel/Bots/use-channel-bot-management', () => ({
}));
vi.mock('@app/features/chat/ChatWithAgentButton', () => ({}));
vi.mock('@channel/Attachments/ChannelAttachmentsTab', () => ({}));
+vi.mock('@channel/views/pending-direct-message', () => ({}));
vi.mock('@channel/Call/CallEventSync', () => ({}));
vi.mock('@channel/Call/ChannelCallAutoJoin', () => ({}));
vi.mock('@channel/Call/ChannelCallButton', () => ({}));
diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
index ae1e26e1c4..6b18713702 100644
--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
@@ -55,6 +55,14 @@ import {
import { ChannelInviteButton } from '@channel/channel-invite-button';
import { useChannelPictureActions } from '@channel/channel-picture';
import { ChannelParticipantsTab } from '@channel/Participants/ChannelParticipantsTab';
+import {
+ isPendingDirectMessageId,
+ pendingDirectMessageRecipient,
+} from '@channel/primitives/pending-direct-messages';
+import {
+ PendingDirectMessage,
+ PendingDirectMessageTitle,
+} from '@channel/views/pending-direct-message';
import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';
import { BlockSplitFileMenu } from '@components/app/split-layout/components/SplitFileMenu';
import {
@@ -99,6 +107,7 @@ import {
Match,
on,
onCleanup,
+ onMount,
Show,
Suspense,
Switch,
@@ -330,7 +339,44 @@ function NewTop(props: { channelId: string }) {
);
}
+/** A DM its first message will create, opened as a block (touch layouts). */
+function PendingDirectMessageBlock(props: { pendingId: string }) {
+ const panel = useSplitPanelOrThrow();
+ const recipientId = pendingDirectMessageRecipient(props.pendingId);
+ // A temporary id this tab didn't open (a reload, a restored layout) has no
+ // conversation behind it.
+ if (!recipientId) {
+ onMount(() => panel.handle.close());
+ return null;
+ }
+
+ return (
+ <>
+ <SplitHeaderLeft>
+ <HeaderIsland class="shrink">
+ <PendingDirectMessageTitle
+ pendingId={props.pendingId}
+ recipientId={recipientId}
+ />
+ </HeaderIsland>
+ </SplitHeaderLeft>
+ <PendingDirectMessage
+ pendingId={props.pendingId}
+ recipientId={recipientId}
+ />
+ </>
+ );
+}
+
export function NewChannelBlockAdapter(props: BlockChannelProps) {
+ const blockId = useBlockId();
+ if (isPendingDirectMessageId(blockId)) {
+ return <PendingDirectMessageBlock pendingId={blockId} />;
+ }
+ return <ChannelBlockAdapter {...props} />;
+}
+
+function ChannelBlockAdapter(props: BlockChannelProps) {
// Every other block gets its hotkey scope from `BlockContainer`, which the
// channel block does not render — so set `blockHotkeyScopeSignal` here or
// `useBlockEntityCommands` would register nothing at all. Commands go on
diff --git a/apps/web/src/features/channel/Input/DraftComposer.tsx b/apps/web/src/features/channel/Input/DraftComposer.tsx
new file mode 100644
index 0000000000..3f27c5d20d
--- /dev/null
+++ b/apps/web/src/features/channel/Input/DraftComposer.tsx
@@ -0,0 +1,201 @@
+import { FloatRegionOrInline } from '@components/app/mobile/float-regions/FloatRegion';
+import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-router/mention-links';
+import { ComposerEditor } from '@core/component/LexicalMarkdown/component/ComposerEditor';
+import { createComposerLayout } from '@core/component/LexicalMarkdown/utils/create-composer-layout';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { isPlatform } from '@core/util/platform';
+import {
+ chatRuleset,
+ handleFileFolderDrop,
+ uploadFile,
+} from '@core/util/upload';
+import { Telemetry } from '@macro-inc/observability';
+import { ComposerSurface } from '@ui';
+import { createSignal, Show } from 'solid-js';
+import { createInputAttachmentTracker } from './attachment-tracker';
+import { ChannelInputContainer } from './ChannelInputContainer';
+import { createConfiguredChannelMarkdownEditor } from './configured-markdown-editor';
+import { createInputState } from './create-input-state';
+import { FormatButtons } from './FormatButtons';
+import { Input } from './Input';
+import { createMentionsTracker } from './mentions-tracker';
+import type { InputSnapshot } from './types';
+import { uploadInputAttachments } from './upload-attachments';
+import { applyInlineFormat, applyNodeFormat } from './utils/formatting';
+
+/**
+ * The composer for a conversation that doesn't exist yet: the Draft message
+ * page and a DM that its first message will create. `onSend` makes the
+ * conversation and sends; an error it throws is shown above the composer and
+ * keeps the draft.
+ */
+export function DraftComposer(props: {
+ placeholder: string;
+ autofocus?: boolean;
+ onSend: (snapshot: InputSnapshot) => Promise<void>;
+}) {
+ const [layout, setLayout] = createSignal<HTMLDivElement>();
+ const [error, setError] = createSignal<string>();
+
+ const handleSend = async (snapshot: InputSnapshot) => {
+ setError(undefined);
+ try {
+ await props.onSend(snapshot);
+ } catch (sendError) {
+ setError(
+ sendError instanceof Error
+ ? sendError.message
+ : 'Failed to send message'
+ );
+ throw sendError;
+ }
+ };
+
+ const mentionsTracker = createMentionsTracker();
+ const attachmentTracker = createInputAttachmentTracker();
+ let clearComposer = () => {};
+
+ const inputState = createInputState({
+ initialInput: { mode: 'channel' as const },
+ mentions: mentionsTracker.mentions,
+ attachmentTracker,
+ clearComposer: () => clearComposer(),
+ attachFiles: async (files) => {
+ await uploadInputAttachments({
+ files,
+ tracker: attachmentTracker,
+ uploadFile: async (file) =>
+ uploadFile(file, chatRuleset, { hideProgressIndicator: true }),
+ });
+ },
+ clearInput: () => markdownEditor.controls.clear(),
+ callbacks: { onSend: handleSend },
+ });
+
+ const send = async () => {
+ try {
+ await inputState.commands.send();
+ } catch (sendError) {
+ // `handleSend` shows its own failures above the composer and rethrows.
+ if (error()) return;
+ setError('Failed to send message');
+ Telemetry.error(sendError, { surface: 'channel-compose' });
+ }
+ };
+
+ const [scrollContainer, setScrollContainer] = createSignal<HTMLElement>();
+
+ const markdownEditor = createConfiguredChannelMarkdownEditor({
+ namespace: 'compose-input-markdown',
+ resolveAppLink: useMacroMentionLinkResolver(),
+ enableMentions: true,
+ scrollContainer,
+ onMentionCreate: (mention) => mentionsTracker.onMentionCreate(mention),
+ onMentionRemove: (mention) => mentionsTracker.onMentionRemove(mention),
+ onChange: (markdown) => inputState.setValue(markdown),
+ onEnter: () => {
+ if (isTouchDevice()) return false;
+ fireAndForget(send(), 'channel-compose');
+ return true;
+ },
+ sendMessage: () => fireAndForget(send(), 'channel-compose'),
+ onPasteFilesAndDirs: (files, directories) => {
+ fireAndForget(
+ handleFileFolderDrop(files, directories, (entries) =>
+ inputState.commands.attachFiles(entries.map((e) => e.file))
+ ),
+ 'channel-compose'
+ );
+ },
+ });
+ clearComposer = () => markdownEditor.controls.clear();
+ const { isCompact: oneLineInput } = createComposerLayout(
+ markdownEditor.buildHandle().lexical,
+ {
+ container: layout,
+ mode: () =>
+ inputState.view().showFormatRibbon ||
+ inputState.view().attachments?.length
+ ? 'expanded'
+ : 'auto',
+ }
+ );
+
+ return (
+ // Full-frame mobile: error + composer float in the bottom accessory
+ // region above the dock; desktop renders them inline.
+ <FloatRegionOrInline region="accessory">
+ <Show when={error()}>
+ <div class="shrink-0 w-full @min-[40rem]:px-4 touch:px-(--mobile-chrome-gutter)">
+ <div class="mx-auto w-full macro-message-width macro-message-padding">
+ <div class="text-sm font-mono text-failure-ink">{error()}</div>
+ </div>
+ </div>
+ </Show>
+ {/* ChannelInputContainer owns the mobile chrome gutter, so drop the
+ desktop px-2 there. */}
+ <div class="px-2 touch:px-0">
+ <ChannelInputContainer>
+ <Input.Root input={inputState.view()} commands={inputState.commands}>
+ <ComposerSurface>
+ <Input.DropZone
+ onDragStart={(valid) => inputState.setIsDraggedOver(valid)}
+ onDragEnd={() => inputState.setIsDraggedOver(false)}
+ >
+ <Input.Layout ref={setLayout} oneLineInput={oneLineInput()}>
+ <Input.DropOverlay />
+ <Input.Layout.Body>
+ <Input.FormatRibbon>
+ <FormatButtons
+ selectionState={() => markdownEditor.selection}
+ onInlineFormat={(format) =>
+ applyInlineFormat(markdownEditor.lexical, format)
+ }
+ onNodeFormat={(format) =>
+ applyNodeFormat(markdownEditor.lexical, format)
+ }
+ />
+ </Input.FormatRibbon>
+ <Input.Layout.Editor
+ ref={setScrollContainer}
+ on:click={(event) => {
+ if (!isTouchDevice()) {
+ event.stopPropagation();
+ markdownEditor.controls.focus();
+ }
+ }}
+ >
+ <Input.Editor>
+ <ComposerEditor
+ config={markdownEditor}
+ placeholder={props.placeholder}
+ autofocus={props.autofocus ?? false}
+ class="text-base"
+ />
+ </Input.Editor>
+ </Input.Layout.Editor>
+ <Input.Attachments kind="media" />
+ <Input.Attachments kind="document" />
+ </Input.Layout.Body>
+
+ <Input.Layout.ActionsLeft>
+ <Show
+ when={!isPlatform('ios')}
+ fallback={<Input.AttachNativeMediaAction />}
+ >
+ <Input.AttachFilesAction />
+ </Show>
+ </Input.Layout.ActionsLeft>
+ <Input.Layout.ActionsRight>
+ <Input.SendAction />
+ </Input.Layout.ActionsRight>
+ </Input.Layout>
+ </Input.DropZone>
+ </ComposerSurface>
+ </Input.Root>
+ </ChannelInputContainer>
+ </div>
+ </FloatRegionOrInline>
+ );
+}
diff --git a/apps/web/src/features/channel/Participants/ChannelParticipantsTab.tsx b/apps/web/src/features/channel/Participants/ChannelParticipantsTab.tsx
index 29c05d6553..39f60225c6 100644
--- a/apps/web/src/features/channel/Participants/ChannelParticipantsTab.tsx
+++ b/apps/web/src/features/channel/Participants/ChannelParticipantsTab.tsx
@@ -1,12 +1,12 @@
-import { useSplitLayout } from '@components/app/split-layout/layout';
import { useChannel, useChannelType } from '@core/context/channels';
import { useUserId } from '@core/context/user';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { getDisplayName, idToEmail, tryMacroId } from '@core/user';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { useOpenDirectMessage } from '@core/util/open-direct-message';
import { useChannelParticipantsQuery } from '@queries/channel/channel-participants';
import { usePatchChannelMutation } from '@queries/channel/channels';
-import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';
import {
useAddParticipantsMutation,
useRemoveParticipantsMutation,
@@ -31,7 +31,6 @@ export function ChannelParticipantsTab(props: {
onCreateBot: () => void;
onOpenBot: (botId: string) => void;
}) {
- const { openWithSplit } = useSplitLayout();
const userId = useUserId();
const channel = useChannel(props.channelId);
const channelType = useChannelType(props.channelId);
@@ -40,7 +39,7 @@ export function ChannelParticipantsTab(props: {
const patchChannelMutation = usePatchChannelMutation();
const addParticipantsMutation = useAddParticipantsMutation();
const removeParticipantsMutation = useRemoveParticipantsMutation();
- const getOrCreateDmMutation = useGetOrCreateDirectMessageMutation();
+ const openDm = useOpenDirectMessage();
const [searchQuery, setSearchQuery] = createSignal('');
const participants = () => participantsQuery.data ?? [];
@@ -136,16 +135,9 @@ export function ChannelParticipantsTab(props: {
};
const openDirectMessage = (participantId: string, event: MouseEvent) => {
- getOrCreateDmMutation.mutate(
- { recipient_id: participantId },
- {
- onSuccess: ({ channel_id }) => {
- openWithSplit(
- { type: 'channel', id: channel_id },
- { activate: true, preferNewSplit: event.shiftKey }
- );
- },
- }
+ fireAndForget(
+ openDm(participantId, { activate: true, preferNewSplit: event.shiftKey }),
+ 'channel-participants'
);
};
diff --git a/apps/web/src/features/channel/primitives/pending-direct-messages.ts b/apps/web/src/features/channel/primitives/pending-direct-messages.ts
new file mode 100644
index 0000000000..f1fdfa8b25
--- /dev/null
+++ b/apps/web/src/features/channel/primitives/pending-direct-messages.ts
@@ -0,0 +1,43 @@
+/**
+ * DMs that don't exist yet. Opening a person you have no DM with shows the
+ * conversation under a temporary channel id, and its first message creates
+ * the real DM, which then takes its place. Until then nothing exists on the
+ * server, so neither person's DM list shows it.
+ *
+ * The temporary id maps to the person only in this tab's memory, so links and
+ * page views never carry their email. An id this tab doesn't know (a reload,
+ * a restored layout) opens nothing.
+ */
+const PENDING_DIRECT_MESSAGE_PREFIX = 'pending-dm-';
+
+const recipientsById = new Map<string, string>();
+const idsByRecipient = new Map<string, string>();
+
+export function isPendingDirectMessageId(id: string | undefined): boolean {
+ return !!id?.startsWith(PENDING_DIRECT_MESSAGE_PREFIX);
+}
+
+/** The temporary channel id for a DM with `recipientId`, reused until it's created. */
+export function pendingDirectMessageId(recipientId: string): string {
+ const existing = idsByRecipient.get(recipientId);
+ if (existing) return existing;
+ const id = `${PENDING_DIRECT_MESSAGE_PREFIX}${crypto.randomUUID()}`;
+ recipientsById.set(id, recipientId);
+ idsByRecipient.set(recipientId, id);
+ return id;
+}
+
+/** The person a temporary channel id stands for, if this tab opened it. */
+export function pendingDirectMessageRecipient(
+ id: string | undefined
+): string | undefined {
+ return id ? recipientsById.get(id) : undefined;
+}
+
+/** Drop a temporary id once its DM exists, so the next open finds the real one. */
+export function settlePendingDirectMessage(id: string): void {
+ const recipientId = recipientsById.get(id);
+ recipientsById.delete(id);
+ if (recipientId && idsByRecipient.get(recipientId) === id)
+ idsByRecipient.delete(recipientId);
+}
diff --git a/apps/web/src/features/channel/views/pending-direct-message.tsx b/apps/web/src/features/channel/views/pending-direct-message.tsx
new file mode 100644
index 0000000000..6231f4cf0d
--- /dev/null
+++ b/apps/web/src/features/channel/views/pending-direct-message.tsx
@@ -0,0 +1,101 @@
+import { useUserId } from '@core/context/user';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { getDisplayName, idToEmail, tryMacroId } from '@core/user';
+import { useSendMessageToPeople } from '@core/util/channels';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { Telemetry } from '@macro-inc/observability';
+import { DirectMessageEmptyState } from '../Channel/DirectMessageEmptyState';
+import { ChannelIcon } from '../channel-icon';
+import { DraftComposer } from '../Input/DraftComposer';
+import { buildPostMessageRequest } from '../Input/message-payload';
+import type { InputSnapshot } from '../Input/types';
+import { settlePendingDirectMessage } from '../primitives/pending-direct-messages';
+
+type PendingDirectMessageProps = {
+ /** The temporary channel id the conversation is open under. */
+ pendingId: string;
+ recipientId: string;
+};
+
+function recipientName(recipientId: string) {
+ return getDisplayName(tryMacroId(recipientId)) || idToEmail(recipientId);
+}
+
+/** As a created DM's composer names them: "First Last" shortens to "First". */
+function placeholderName(name: string) {
+ const parts = name.split(' ');
+ return parts.length === 2 ? parts[0] : name;
+}
+
+/** The DM's avatar and name, as a created DM's header shows them. */
+export function PendingDirectMessageTitle(props: PendingDirectMessageProps) {
+ const userId = useUserId();
+ const participantIds = () => [userId() ?? '', props.recipientId];
+
+ return (
+ <div class="ph-no-capture flex min-w-0 shrink items-center gap-2">
+ <span class="inline-flex size-4">
+ <ChannelIcon
+ channelId={props.pendingId}
+ channelType="direct_message"
+ participantIds={participantIds()}
+ avatarSize="sm"
+ class="[&_img]:rounded-full"
+ suppressClick
+ showTooltip={false}
+ />
+ </span>
+ <span class="truncate text-sm font-semibold">
+ {recipientName(props.recipientId)}
+ </span>
+ </div>
+ );
+}
+
+/**
+ * A DM with someone you haven't messaged yet, shown like an empty DM. Nothing
+ * exists on the server until the first message: sending it creates the DM,
+ * posts the message, and replaces this view with the conversation.
+ */
+export function PendingDirectMessage(props: PendingDirectMessageProps) {
+ const { sendToUsers } = useSendMessageToPeople();
+
+ const send = (snapshot: InputSnapshot) =>
+ Telemetry.span('channels.send_first_direct_message', async (span) => {
+ const { content, mentions, attachments } = buildPostMessageRequest({
+ snapshot,
+ });
+ // Navigate once the message is in: the created DM replaces this entry,
+ // so Back skips the conversation that no longer stands in for anything.
+ const sent = await sendToUsers({
+ users: [props.recipientId],
+ content,
+ mentions,
+ attachments,
+ navigate: { navigate: false, mergeHistory: true },
+ });
+ if (!sent) {
+ span.setAttr('channels.send_first_direct_message.outcome', 'failed');
+ throw new Error(
+ 'Could not send your message. Your draft has been kept.'
+ );
+ }
+ span.setAttr('channel.id', sent.channelId);
+ span.setAttr('channels.send_first_direct_message.outcome', 'sent');
+ settlePendingDirectMessage(props.pendingId);
+ fireAndForget(sent.navigateToChannel(), 'pending-direct-message');
+ });
+
+ return (
+ <div class="relative flex flex-col size-full panel">
+ <div class="flex min-h-0 grow flex-col overflow-y-auto touch:pt-(--mobile-content-inset-top)">
+ <DirectMessageEmptyState />
+ </div>
+ <DraftComposer
+ placeholder={`Type @ to share with ${placeholderName(recipientName(props.recipientId))}`}
+ autofocus={!isTouchDevice()}
+ onSend={send}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/channels-view/channels-view.test.tsx b/apps/web/src/features/channels-view/channels-view.test.tsx
index 4cfc06f37a..205f881249 100644
--- a/apps/web/src/features/channels-view/channels-view.test.tsx
+++ b/apps/web/src/features/channels-view/channels-view.test.tsx
@@ -159,6 +159,9 @@ vi.mock('./components/ChannelDetailView', () => ({
</div>
),
}));
+vi.mock('./components/PendingDirectMessageDetail', () => ({
+ PendingDirectMessageDetail: () => null,
+}));
vi.mock('./components/ChannelThreadsView', () => ({
ChannelThreadsView: () => <div data-testid="channel-threads" />,
}));
diff --git a/apps/web/src/features/channels-view/channels-view.tsx b/apps/web/src/features/channels-view/channels-view.tsx
index 1c08ad87ce..b5ebddcb96 100644
--- a/apps/web/src/features/channels-view/channels-view.tsx
+++ b/apps/web/src/features/channels-view/channels-view.tsx
@@ -11,6 +11,7 @@ import { useChannelByIdQuery } from '@channel/Channel/channel-entity';
import { ChannelAccessDenied } from '@channel/ChannelAccessDenied';
import { ChannelUnavailable } from '@channel/components/ChannelUnavailable';
import { DebugSuspense } from '@channel/DebugSuspense';
+import { isPendingDirectMessageId } from '@channel/primitives/pending-direct-messages';
import { prefetchChannelTarget } from '@channel/queries/prefetch-channel-target';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
@@ -36,6 +37,7 @@ import { ChannelDetailView } from './components/ChannelDetailView';
import { MAX_PINNED_CHANNELS } from './components/ChannelPins';
import { ChannelsMobileView } from './components/ChannelsMobileView';
import { ChannelThreadsView } from './components/ChannelThreadsView';
+import { PendingDirectMessageDetail } from './components/PendingDirectMessageDetail';
import { ChannelsRail } from './components/rail/ChannelsRail';
import { createChannelDetail } from './primitives/create-channel-detail';
import {
@@ -406,12 +408,21 @@ function ChannelDetailRouteContent() {
}
export function ChannelDetailRouteView() {
+ const { selectedChannel } = useChannelsView();
+ // A DM its first message will create has nothing to load yet.
+ const pendingId = () => {
+ const id = selectedChannel()?.id;
+ return isPendingDirectMessageId(id) ? id : undefined;
+ };
+
return (
<DebugSuspense
name="ChannelsView.detail-route"
fallback={<ChannelLoading />}
>
- <ChannelDetailRouteContent />
+ <Show when={pendingId()} keyed fallback={<ChannelDetailRouteContent />}>
+ {(id) => <PendingDirectMessageDetail pendingId={id} />}
+ </Show>
</DebugSuspense>
);
}
diff --git a/apps/web/src/features/channels-view/components/PendingDirectMessageDetail.tsx b/apps/web/src/features/channels-view/components/PendingDirectMessageDetail.tsx
new file mode 100644
index 0000000000..1346a6a029
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/PendingDirectMessageDetail.tsx
@@ -0,0 +1,44 @@
+import { ViewShell } from '@app/components/view-shell';
+import { pendingDirectMessageRecipient } from '@channel/primitives/pending-direct-messages';
+import {
+ PendingDirectMessage,
+ PendingDirectMessageTitle,
+} from '@channel/views/pending-direct-message';
+import { RedirectSplit } from '@components/app/split-layout/split-router/app-route-shell';
+import { Show } from 'solid-js';
+
+/**
+ * Chat's detail for a DM that its first message will create. A temporary id
+ * this tab didn't open (a reload, a restored layout) returns to the list.
+ */
+export function PendingDirectMessageDetail(props: { pendingId: string }) {
+ const recipientId = pendingDirectMessageRecipient(props.pendingId);
+
+ return (
+ <Show
+ when={recipientId}
+ keyed
+ fallback={
+ <RedirectSplit
+ to={{ type: 'component', id: 'channels' }}
+ mergeHistory
+ />
+ }
+ >
+ {(recipient) => (
+ <div class="flex size-full min-h-0 flex-col">
+ <ViewShell.TopBar class="gap-3 py-0">
+ <PendingDirectMessageTitle
+ pendingId={props.pendingId}
+ recipientId={recipient}
+ />
+ </ViewShell.TopBar>
+ <PendingDirectMessage
+ pendingId={props.pendingId}
+ recipientId={recipient}
+ />
+ </div>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/command/mobile/MobileSearchResults.test.tsx b/apps/web/src/features/command/mobile/MobileSearchResults.test.tsx
index d9c2df8765..96b2148c60 100644
--- a/apps/web/src/features/command/mobile/MobileSearchResults.test.tsx
+++ b/apps/web/src/features/command/mobile/MobileSearchResults.test.tsx
@@ -14,6 +14,7 @@ import {
within,
} from '@solidjs/testing-library';
import { CombinedError } from '@urql/core';
+import { okAsync } from 'neverthrow';
import { type Accessor, createSignal, onMount, Show } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { mergeCommandPeople } from '../contact-items';
@@ -107,9 +108,7 @@ vi.mock('@core/component/Toast/Toast', () => ({
toast: { failure: mocks.failure },
}));
vi.mock('@queries/channel/get-or-create-dm', () => ({
- useGetOrCreateDirectMessageMutation: () => ({
- mutateAsync: mocks.directMessage,
- }),
+ existingDirectMessage: mocks.directMessage,
}));
vi.mock('@queries/storage/databases', () => ({
useDatabaseDiscoverySync: vi.fn(),
@@ -329,8 +328,10 @@ it('preserves the search after a failed person lookup and on return from a succe
},
},
];
- mocks.directMessage.mockRejectedValueOnce(new Error('Unavailable'));
- mocks.directMessage.mockResolvedValueOnce({ channel_id: 'direct-message' });
+ mocks.directMessage.mockReturnValue(okAsync('direct-message'));
+ mocks.open.mockImplementationOnce(() => {
+ throw new Error('Unavailable');
+ });
SearchState.setQuery('teo');
SearchState.setCategory('people');
render(() => <MobileSearchResults />);
@@ -340,7 +341,6 @@ it('preserves the search after a failed person lookup and on return from a succe
'Unable to open result. Please try again.'
)
);
- expect(mocks.open).not.toHaveBeenCalled();
expect(SearchState.isOpen()).toBe(true);
expect(SearchState.query()).toBe('teo');
expect(SearchState.category()).toBe('people');
@@ -348,7 +348,8 @@ it('preserves the search after a failed person lookup and on return from a succe
fireEvent.click(screen.getByRole('button', { name: 'Teo' }));
expect(SearchState.isOpen()).toBe(true);
await waitFor(() =>
- expect(mocks.open).toHaveBeenCalledWith(
+ expect(mocks.open).toHaveBeenNthCalledWith(
+ 2,
{ type: 'channel', id: 'direct-message' },
{ reopen: 'latest' }
)
@@ -649,9 +650,9 @@ it.each(['before navigation', 'while away'])(
},
]);
};
- mocks.directMessage.mockImplementation(async () => {
+ mocks.directMessage.mockImplementation(() => {
if (arrival === 'before navigation') publishConversation();
- return { channel_id: 'new-dm' };
+ return okAsync('new-dm');
});
SearchState.setQuery('Person');
const view = render(() => <MobileSearchResults />);
diff --git a/apps/web/src/features/command/mobile/MobileSearchResults.tsx b/apps/web/src/features/command/mobile/MobileSearchResults.tsx
index 81d7a1675e..049d5c1925 100644
--- a/apps/web/src/features/command/mobile/MobileSearchResults.tsx
+++ b/apps/web/src/features/command/mobile/MobileSearchResults.tsx
@@ -13,6 +13,7 @@ import { toast } from '@core/component/Toast/Toast';
import type { QuickAccessItem } from '@core/context/quickAccess';
import { useIsAuthenticated, useUserId } from '@core/context/user';
import { fireAndForget } from '@core/util/fireAndForget';
+import { useOpenDirectMessage } from '@core/util/open-direct-message';
import { isTransientRequestError } from '@core/util/request-error';
import {
type EntityData,
@@ -22,7 +23,6 @@ import {
type SearchLocation,
} from '@entity';
import { Telemetry } from '@macro-inc/observability';
-import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';
import { useDatabaseDiscoverySync } from '@queries/storage/databases';
import { Button, CommandMenuListItem } from '@ui';
import { createMemo, createSignal, For, Show, Suspense } from 'solid-js';
@@ -125,7 +125,7 @@ function MobileNameResults(props: {
});
const { openWithSplit } = useSplitLayout();
const panel = useSplitPanelOrThrow();
- const directMessage = useGetOrCreateDirectMessageMutation();
+ const openDirectMessage = useOpenDirectMessage();
const open = async (item: QuickAccessItem) => {
await Telemetry.span('mobile.search.open', async (span) => {
span.setAttr('entity.id', item.id);
@@ -136,14 +136,7 @@ function MobileNameResults(props: {
id: projectRouteId({ id: item.id, section: 'overview' }),
});
} else if (item.kind === 'user') {
- const result = await directMessage.mutateAsync({
- recipient_id: item.id,
- parentSpan: span,
- });
- openWithSplit(
- { type: 'channel', id: result.channel_id },
- { reopen: 'latest' }
- );
+ await openDirectMessage(item.id, { parentSpan: span });
} else {
await openEntityInSplitFromUnifiedList(item.data, {
splitHandle: panel.handle,
diff --git a/apps/web/src/features/command/open-command-result.test.ts b/apps/web/src/features/command/open-command-result.test.ts
index e24573187c..1f65383e4d 100644
--- a/apps/web/src/features/command/open-command-result.test.ts
+++ b/apps/web/src/features/command/open-command-result.test.ts
@@ -36,8 +36,8 @@ vi.mock('@app/features/next-soup/soup-view/search-controllers', () => ({
vi.mock('@core/component/Toast/Toast', () => ({
toast: { failure: vi.fn(), alert: vi.fn() },
}));
-vi.mock('@queries/channel/get-or-create-dm', () => ({
- useGetOrCreateDirectMessageMutation: () => ({ mutateAsync: mocks.dm }),
+vi.mock('@core/util/open-direct-message', () => ({
+ useOpenDirectMessage: () => mocks.dm,
}));
vi.mock('@core/constant/allBlocks', () => ({
itemToBlockName: (item: { type: string }) =>
diff --git a/apps/web/src/features/command/open-command-result.ts b/apps/web/src/features/command/open-command-result.ts
index 669f696395..478e2241fc 100644
--- a/apps/web/src/features/command/open-command-result.ts
+++ b/apps/web/src/features/command/open-command-result.ts
@@ -13,9 +13,9 @@ import {
USE_MACRO_PR_SUMMARY_BLOCK,
} from '@core/constant/featureFlags';
import { fireAndForget } from '@core/util/fireAndForget';
+import { useOpenDirectMessage } from '@core/util/open-direct-message';
import { openExternalUrl } from '@core/util/url';
import { isGithubPrEntity } from '@entity';
-import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';
import { projectRouteId } from '../projects/core/route';
import { routineContent } from '../routines/routine-navigation';
import { getCategorySearchFilters } from './category-search-filters';
@@ -34,28 +34,14 @@ export function createCommandResultOpener(
const { openWithSplit } = useSplitLayout();
const navigateSearch = createGlobalSearchOpener(referredFrom);
const projectsFlag = useFeatureFlag(enableProjects);
- const getOrCreateDirectMessage = useGetOrCreateDirectMessageMutation();
+ const openDm = useOpenDirectMessage();
// A person without a conversation yet: open one, as the user card does.
const openDirectMessage = async (
recipientId: string,
openInNewSplit: boolean
) => {
- try {
- const { channel_id } = await getOrCreateDirectMessage.mutateAsync({
- recipient_id: recipientId,
- });
- openWithSplit(
- { type: 'channel', id: channel_id },
- {
- referredFrom,
- preferNewSplit: openInNewSplit,
- reopen: 'latest',
- }
- );
- globalSplitManager()?.returnFocus();
- } catch {
- toast.failure(t('commandMenu.unableToOpenConversation'));
- }
+ await openDm(recipientId, { referredFrom, preferNewSplit: openInNewSplit });
+ globalSplitManager()?.returnFocus();
};
const openEntity = (
diff --git a/apps/web/src/features/entity/owner/owner-display.test.tsx b/apps/web/src/features/entity/owner/owner-display.test.tsx
index a0080eb68a..f65d747566 100644
--- a/apps/web/src/features/entity/owner/owner-display.test.tsx
+++ b/apps/web/src/features/entity/owner/owner-display.test.tsx
@@ -1,5 +1,4 @@
import { cleanup, fireEvent, render } from '@solidjs/testing-library';
-import { ok } from 'neverthrow';
import { createSignal, type JSX } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -44,11 +43,8 @@ vi.mock('@queries/bots/profiles', () => ({
vi.mock('@queries/team/teams', () => ({
useUserTeamsQuery: () => mocks.teams,
}));
-vi.mock('@queries/channel/get-or-create-dm', () => ({
- getOrCreateDirectMessage: mocks.openDm,
-}));
-vi.mock('@components/app/split-layout/layout', () => ({
- useSplitLayout: () => ({ openWithSplit: vi.fn() }),
+vi.mock('@core/util/open-direct-message', () => ({
+ useOpenDirectMessage: () => mocks.openDm,
}));
vi.mock('@core/signal/profilePicture', () => ({
useProfilePictureUrl: () => [() => undefined],
@@ -78,7 +74,7 @@ beforeEach(() => {
mocks.requestedBotIds = [];
mocks.teams = settled([{ id: ENGINEERING, name: 'Engineering' }]);
mocks.openDm.mockReset();
- mocks.openDm.mockResolvedValue(ok({ channel_id: 'dm' }));
+ mocks.openDm.mockResolvedValue(undefined);
});
afterEach(cleanup);
@@ -209,6 +205,8 @@ describe('OwnerLabel', () => {
fireEvent.mouseDown(getByText('Engineering'));
expect(container.querySelectorAll('[data-slot="avatar"]').length).toBe(3);
- expect(mocks.openDm.mock.calls).toEqual([[PETER]]);
+ expect(mocks.openDm.mock.calls).toEqual([
+ [PETER, { activate: true, preferNewSplit: false }],
+ ]);
});
});
diff --git a/apps/web/src/lib/core/component/UserCardDrawer.test.tsx b/apps/web/src/lib/core/component/UserCardDrawer.test.tsx
index 597192ebae..92a8941651 100644
--- a/apps/web/src/lib/core/component/UserCardDrawer.test.tsx
+++ b/apps/web/src/lib/core/component/UserCardDrawer.test.tsx
@@ -4,6 +4,7 @@
import { render, screen, waitFor } from '@solidjs/testing-library';
import userEvent from '@testing-library/user-event';
+import { okAsync } from 'neverthrow';
import { type ComponentProps, type JSX, Show } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { openUserCard, UserCardDrawer } from './UserCardDrawer';
@@ -12,7 +13,7 @@ const mocks = vi.hoisted(() => ({
crmFlagEnabled: false,
openWithSplit: vi.fn(),
popoverSplit: vi.fn(),
- getOrCreateDm: vi.fn(),
+ existingDm: vi.fn(),
toastSuccess: vi.fn(),
toastFailure: vi.fn(),
}));
@@ -46,9 +47,7 @@ vi.mock('@core/user', () => ({
}));
vi.mock('@queries/channel/get-or-create-dm', () => ({
- useGetOrCreateDirectMessageMutation: () => ({
- mutateAsync: mocks.getOrCreateDm,
- }),
+ existingDirectMessage: mocks.existingDm,
}));
vi.mock('@app/features/crm/record-adapter', () => ({
@@ -91,7 +90,7 @@ beforeEach(() => {
mocks.crmFlagEnabled = false;
mocks.openWithSplit.mockReset();
mocks.popoverSplit.mockReset();
- mocks.getOrCreateDm.mockReset().mockResolvedValue({ channel_id: 'chan-1' });
+ mocks.existingDm.mockReset().mockReturnValue(okAsync(undefined));
mocks.toastSuccess.mockReset();
mocks.toastFailure.mockReset();
});
@@ -123,19 +122,38 @@ describe('UserCardDrawer', () => {
expect(screen.getByRole('button', { name: 'Assign task' })).toBeTruthy();
});
- it('opens a direct message and closes the sheet', async () => {
+ it('opens a DM that only the first message creates, and closes the sheet', async () => {
const user = userEvent.setup({ skipHover: true });
render(() => <UserCardDrawer />);
openJane();
await user.click(screen.getByRole('button', { name: 'DM' }));
- expect(mocks.getOrCreateDm).toHaveBeenCalledWith({
- recipient_id: 'macro|[email protected]',
- });
+ expect(mocks.existingDm).toHaveBeenCalledWith(
+ );
+ expect(mocks.openWithSplit).toHaveBeenCalledWith(
+ { type: 'channel', id: expect.stringMatching(/^pending-dm-/) },
+ { preferNewSplit: false }
+ );
expect(screen.queryByRole('button', { name: 'DM' })).toBeNull();
});
+ it('opens the existing DM with a person', async () => {
+ mocks.existingDm.mockReturnValue(okAsync('chan-1'));
+ const user = userEvent.setup({ skipHover: true });
+ render(() => <UserCardDrawer />);
+ openJane();
+
+ await user.click(screen.getByRole('button', { name: 'DM' }));
+
+ expect(mocks.openWithSplit).toHaveBeenCalledWith(
+ { type: 'channel', id: 'chan-1' },
+ { preferNewSplit: false, reopen: 'latest' }
+ );
+ });
+
it('copies the email and closes the sheet, which a toast confirms', async () => {
const user = userEvent.setup({ skipHover: true });
render(() => <UserCardDrawer />);
diff --git a/apps/web/src/lib/core/component/UserIcon.tsx b/apps/web/src/lib/core/component/UserIcon.tsx
index 445937d290..cbc536f92c 100644
--- a/apps/web/src/lib/core/component/UserIcon.tsx
+++ b/apps/web/src/lib/core/component/UserIcon.tsx
@@ -1,4 +1,3 @@
-import { useSplitLayout } from '@components/app/split-layout/layout';
import { ENABLE_PROFILE_PICTURES } from '@core/constant/featureFlags';
import { isBotPrincipalId } from '@core/constant/macroAgent';
import { staticFileSizedUrl } from '@core/constant/servers';
@@ -14,9 +13,9 @@ import {
useIsConnectedSecondaryInbox,
} from '@core/user';
import { fireAndForget } from '@core/util/fireAndForget';
+import { useOpenDirectMessage } from '@core/util/open-direct-message';
import RobotIcon from '@icon/system/regular/robot.svg';
import Trash from '@icon/system/regular/trash.svg?component-solid';
-import { getOrCreateDirectMessage } from '@queries/channel/get-or-create-dm';
import { Avatar, type AvatarSize, cn } from '@ui';
import { createMemo, Match, Show, Switch } from 'solid-js';
import { Dynamic } from 'solid-js/web';
@@ -143,24 +142,18 @@ export function UserIcon(props: UserIconProps) {
return props.email;
});
- const { openWithSplit } = useSplitLayout();
+ const openDirectMessage = useOpenDirectMessage();
const isConnectedSecondaryInbox = useIsConnectedSecondaryInbox();
- const openDm = async (recipientId: string, preferNewSplit: boolean) => {
- const result = await getOrCreateDirectMessage(recipientId);
- if (result.isErr()) {
- console.error('failed to get or create direct message', result.error);
- return;
- }
- openWithSplit(
- { type: 'channel', id: result.value.channel_id },
- { activate: true, preferNewSplit }
- );
- };
-
- const getOrCreateDm = (event: MouseEvent) => {
+ const openDm = (event: MouseEvent) => {
if (!props.id || isConnectedSecondaryInbox(props.id)) return;
- fireAndForget(openDm(props.id, event.shiftKey), 'user-icon-dm');
+ fireAndForget(
+ openDirectMessage(props.id, {
+ activate: true,
+ preferNewSplit: event.shiftKey,
+ }),
+ 'user-icon-dm'
+ );
};
const showTooltip = () => props.showTooltip !== false;
@@ -169,7 +162,7 @@ export function UserIcon(props: UserIconProps) {
// On touch the tap belongs to the user card, which offers the DM as one of
// its actions rather than jumping straight into a conversation.
const avatarMouseDown = () =>
- props.suppressClick || isTouchDevice() ? undefined : getOrCreateDm;
+ props.suppressClick || isTouchDevice() ? undefined : openDm;
const triggerClass = () =>
size() === 'fill' ? 'size-full' : 'inline-flex shrink-0';
@@ -215,7 +208,7 @@ export function UserIcon(props: UserIconProps) {
<Avatar
size={size()}
class={props.class}
- onMouseDown={props.suppressClick ? undefined : getOrCreateDm}
+ onMouseDown={props.suppressClick ? undefined : openDm}
>
<UserIconContent
id={props.id}
diff --git a/apps/web/src/lib/core/component/UserTooltip.test.tsx b/apps/web/src/lib/core/component/UserTooltip.test.tsx
index a6995f969d..26afaa6377 100644
--- a/apps/web/src/lib/core/component/UserTooltip.test.tsx
+++ b/apps/web/src/lib/core/component/UserTooltip.test.tsx
@@ -57,7 +57,7 @@ vi.mock('@core/user', () => ({
}));
vi.mock('@queries/channel/get-or-create-dm', () => ({
- useGetOrCreateDirectMessageMutation: () => ({ mutateAsync: vi.fn() }),
+ existingDirectMessage: vi.fn(),
}));
vi.mock('@app/features/crm/record-adapter', () => ({
diff --git a/apps/web/src/lib/core/component/firstPartyBotMark.test.tsx b/apps/web/src/lib/core/component/firstPartyBotMark.test.tsx
index a08cebf58e..0fbf4c0fce 100644
--- a/apps/web/src/lib/core/component/firstPartyBotMark.test.tsx
+++ b/apps/web/src/lib/core/component/firstPartyBotMark.test.tsx
@@ -14,11 +14,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { firstPartyBotMark } from './firstPartyBotMark';
import { UserIcon } from './UserIcon';
-vi.mock('@components/app/split-layout/layout', () => ({
- useSplitLayout: () => ({ openWithSplit: vi.fn() }),
-}));
-vi.mock('@queries/channel/get-or-create-dm', () => ({
- getOrCreateDirectMessage: vi.fn(),
+vi.mock('@core/util/open-direct-message', () => ({
+ useOpenDirectMessage: () => vi.fn(),
}));
vi.mock('@core/user', () => ({
getDisplayName: () => undefined,
diff --git a/apps/web/src/lib/core/component/userCardActions.tsx b/apps/web/src/lib/core/component/userCardActions.tsx
index f18f9b50a8..03bf131b2b 100644
--- a/apps/web/src/lib/core/component/userCardActions.tsx
+++ b/apps/web/src/lib/core/component/userCardActions.tsx
@@ -5,10 +5,10 @@ import { toast } from '@core/component/Toast/Toast';
import { isBotPrincipalId } from '@core/constant/macroAgent';
import { useUserId } from '@core/context/user';
import { useIsConnectedSecondaryInbox } from '@core/user';
+import { useOpenDirectMessage } from '@core/util/open-direct-message';
import WideChat from '@icon/system/regular/chat.svg';
import CopyIcon from '@icon/system/regular/copy.svg';
import WideTask from '@icon/system/regular/list-checks.svg';
-import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';
import {
type Accessor,
type Component,
@@ -69,10 +69,8 @@ export function useUserCardActions(
): Accessor<UserCardAction[]> {
const currentUserId = useUserId();
const isConnectedSecondaryInbox = useIsConnectedSecondaryInbox();
- const { openWithSplit, popoverSplit } = useSplitLayout();
- const getOrCreateDmMutation = useGetOrCreateDirectMessageMutation({
- onError: () => toast.failure('Failed to open direct message'),
- });
+ const { popoverSplit } = useSplitLayout();
+ const openDm = useOpenDirectMessage();
const userId = () => target().id;
const canTreatAsUser = () =>
@@ -114,15 +112,7 @@ export function useUserCardActions(
event.stopPropagation();
const recipientId = userId();
if (!recipientId) return;
- const preferNewSplit = event.shiftKey;
- // The mutation's onError callback handles failure feedback.
- const { channel_id } = await getOrCreateDmMutation.mutateAsync({
- recipient_id: recipientId,
- });
- openWithSplit(
- { type: 'channel', id: channel_id },
- { preferNewSplit, reopen: 'latest' }
- );
+ await openDm(recipientId, { preferNewSplit: event.shiftKey });
};
const openTaskComposer = (event: MouseEvent) => {
diff --git a/apps/web/src/lib/core/util/open-direct-message.ts b/apps/web/src/lib/core/util/open-direct-message.ts
new file mode 100644
index 0000000000..13bae7a4e1
--- /dev/null
+++ b/apps/web/src/lib/core/util/open-direct-message.ts
@@ -0,0 +1,81 @@
+import { pendingDirectMessageId } from '@channel/primitives/pending-direct-messages';
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import type { OpenWithSplitOptions } from '@components/app/split-layout/layoutManager';
+import { useUserId } from '@core/context/user';
+import { Telemetry, type TraceContext } from '@macro-inc/observability';
+import { existingDirectMessage } from '@queries/channel/get-or-create-dm';
+
+type OpenDirectMessageOptions = Pick<
+ OpenWithSplitOptions,
+ 'activate' | 'preferNewSplit' | 'referredFrom'
+> & {
+ /** The caller's span, kept across the lookup's await. */
+ parentSpan?: TraceContext;
+};
+
+/**
+ * Opens the conversation with a person without creating it: their existing
+ * DM, or a DM that doesn't exist yet, shown like an empty one, whose first
+ * message creates it. Opening someone's profile never leaves an empty DM in
+ * either person's list.
+ */
+export function useOpenDirectMessage() {
+ const { openWithSplit } = useSplitLayout();
+ const userId = useUserId();
+
+ return (
+ recipientId: string,
+ { parentSpan, ...options }: OpenDirectMessageOptions = {}
+ ) =>
+ (parentSpan ?? Telemetry.captureContext()).run(() =>
+ openDirectMessage(recipientId, options)
+ );
+
+ function openDirectMessage(
+ recipientId: string,
+ options: Omit<OpenDirectMessageOptions, 'parentSpan'>
+ ) {
+ return Telemetry.span('channels.open_direct_message', async (span) => {
+ const viewerId = userId();
+ // There is no DM with yourself; the server refuses to make one.
+ if (!viewerId || recipientId === viewerId) {
+ span.setAttr('channels.open_direct_message.outcome', 'skipped');
+ return;
+ }
+
+ const channelId = await span.span(
+ 'channels.find_direct_message',
+ async (lookup) => {
+ const existing = await existingDirectMessage(viewerId, recipientId);
+ // A channel list that fails to load only costs the history view:
+ // the first message still reaches an existing DM.
+ if (existing.isErr()) {
+ lookup.error(existing.error);
+ return undefined;
+ }
+ lookup.setAttr(
+ 'channels.find_direct_message.found',
+ existing.value !== undefined
+ );
+ return existing.value;
+ }
+ );
+
+ if (channelId) {
+ span.setAttr('channel.id', channelId);
+ span.setAttr('channels.open_direct_message.outcome', 'existing');
+ openWithSplit(
+ { type: 'channel', id: channelId },
+ { ...options, reopen: 'latest' }
+ );
+ return;
+ }
+
+ span.setAttr('channels.open_direct_message.outcome', 'pending');
+ openWithSplit(
+ { type: 'channel', id: pendingDirectMessageId(recipientId) },
+ options
+ );
+ });
+ }
+}
diff --git a/apps/web/src/lib/i18n/locales/da.ts b/apps/web/src/lib/i18n/locales/da.ts
index 589c671133..71b40ee358 100644
--- a/apps/web/src/lib/i18n/locales/da.ts
+++ b/apps/web/src/lib/i18n/locales/da.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: 'Projekt',
newProject: 'Nyt projekt',
contentAlreadyOpen: 'Indholdet er allerede åbent',
- unableToOpenConversation: 'Samtalen kunne ikke åbnes. Prøv igen.',
mobileSearchPlaceholder: 'Søg…',
closeSearch: 'Luk søgning',
searchFullTextFor: 'Fritekstsøg efter »{{query}}«',
diff --git a/apps/web/src/lib/i18n/locales/de.ts b/apps/web/src/lib/i18n/locales/de.ts
index 60ef4e8f42..563865f321 100644
--- a/apps/web/src/lib/i18n/locales/de.ts
+++ b/apps/web/src/lib/i18n/locales/de.ts
@@ -53,8 +53,6 @@ export default {
projectBadge: 'Projekt',
newProject: 'Neues Projekt',
contentAlreadyOpen: 'Inhalt bereits geöffnet',
- unableToOpenConversation:
- 'Unterhaltung konnte nicht geöffnet werden. Bitte erneut versuchen.',
mobileSearchPlaceholder: 'Suchen…',
closeSearch: 'Suche schließen',
searchFullTextFor: 'Volltextsuche nach „{{query}}“',
diff --git a/apps/web/src/lib/i18n/locales/en/command-menu.ts b/apps/web/src/lib/i18n/locales/en/command-menu.ts
index a7221ae78e..79805769e0 100644
--- a/apps/web/src/lib/i18n/locales/en/command-menu.ts
+++ b/apps/web/src/lib/i18n/locales/en/command-menu.ts
@@ -36,7 +36,6 @@ export default {
projectBadge: 'Project',
newProject: 'New project',
contentAlreadyOpen: 'Content already open',
- unableToOpenConversation: 'Unable to open conversation. Please try again.',
mobileSearchPlaceholder: 'Search…',
mobileSearchOrCreate: 'Search or create',
closeSearch: 'Close search',
diff --git a/apps/web/src/lib/i18n/locales/es.ts b/apps/web/src/lib/i18n/locales/es.ts
index 69bf1bb69e..d6351f67b7 100644
--- a/apps/web/src/lib/i18n/locales/es.ts
+++ b/apps/web/src/lib/i18n/locales/es.ts
@@ -53,8 +53,6 @@ export default {
projectBadge: 'Proyecto',
newProject: 'Nuevo proyecto',
contentAlreadyOpen: 'El contenido ya está abierto',
- unableToOpenConversation:
- 'No se pudo abrir la conversación. Inténtalo de nuevo.',
mobileSearchPlaceholder: 'Buscar…',
closeSearch: 'Cerrar búsqueda',
searchFullTextFor: 'Buscar en todo el texto “{{query}}”',
diff --git a/apps/web/src/lib/i18n/locales/fi.ts b/apps/web/src/lib/i18n/locales/fi.ts
index 3fd2bb6f00..b35f67f4dd 100644
--- a/apps/web/src/lib/i18n/locales/fi.ts
+++ b/apps/web/src/lib/i18n/locales/fi.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: 'Projekti',
newProject: 'Uusi projekti',
contentAlreadyOpen: 'Sisältö on jo auki',
- unableToOpenConversation: 'Keskustelua ei voitu avata. Yritä uudelleen.',
mobileSearchPlaceholder: 'Hae…',
closeSearch: 'Sulje haku',
searchFullTextFor: 'Hae koko tekstistä ”{{query}}”',
diff --git a/apps/web/src/lib/i18n/locales/fr.ts b/apps/web/src/lib/i18n/locales/fr.ts
index 7a4c26ad1e..793b198d3d 100644
--- a/apps/web/src/lib/i18n/locales/fr.ts
+++ b/apps/web/src/lib/i18n/locales/fr.ts
@@ -53,8 +53,6 @@ export default {
projectBadge: 'Projet',
newProject: 'Nouveau projet',
contentAlreadyOpen: 'Contenu déjà ouvert',
- unableToOpenConversation:
- 'Impossible d’ouvrir la conversation. Veuillez réessayer.',
mobileSearchPlaceholder: 'Rechercher…',
closeSearch: 'Fermer la recherche',
searchFullTextFor: 'Recherche en texte intégral de « {{query}} »',
diff --git a/apps/web/src/lib/i18n/locales/hi.ts b/apps/web/src/lib/i18n/locales/hi.ts
index f0cad88424..873822d957 100644
--- a/apps/web/src/lib/i18n/locales/hi.ts
+++ b/apps/web/src/lib/i18n/locales/hi.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: 'प्रोजेक्ट',
newProject: 'नया प्रोजेक्ट',
contentAlreadyOpen: 'कॉन्टेंट पहले से खुला है',
- unableToOpenConversation: 'बातचीत नहीं खुल सकी। कृपया फिर से कोशिश करें।',
mobileSearchPlaceholder: 'खोजें…',
closeSearch: 'खोज बंद करें',
searchFullTextFor: '“{{query}}” के लिए पूरे टेक्स्ट में खोजें',
diff --git a/apps/web/src/lib/i18n/locales/id.ts b/apps/web/src/lib/i18n/locales/id.ts
index e4b7faac93..926d3290e0 100644
--- a/apps/web/src/lib/i18n/locales/id.ts
+++ b/apps/web/src/lib/i18n/locales/id.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: 'Proyek',
newProject: 'Proyek baru',
contentAlreadyOpen: 'Konten sudah terbuka',
- unableToOpenConversation: 'Tidak dapat membuka percakapan. Coba lagi.',
mobileSearchPlaceholder: 'Cari…',
closeSearch: 'Tutup penelusuran',
searchFullTextFor: 'Cari teks lengkap untuk “{{query}}”',
diff --git a/apps/web/src/lib/i18n/locales/it.ts b/apps/web/src/lib/i18n/locales/it.ts
index 0415cf6052..bcb9d60aad 100644
--- a/apps/web/src/lib/i18n/locales/it.ts
+++ b/apps/web/src/lib/i18n/locales/it.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: 'Progetto',
newProject: 'Nuovo progetto',
contentAlreadyOpen: 'Contenuto già aperto',
- unableToOpenConversation: 'Impossibile aprire la conversazione. Riprova.',
mobileSearchPlaceholder: 'Cerca…',
closeSearch: 'Chiudi ricerca',
searchFullTextFor: 'Cerca nel testo completo «{{query}}»',
diff --git a/apps/web/src/lib/i18n/locales/ja.ts b/apps/web/src/lib/i18n/locales/ja.ts
index 0d684f138c..548c9fe754 100644
--- a/apps/web/src/lib/i18n/locales/ja.ts
+++ b/apps/web/src/lib/i18n/locales/ja.ts
@@ -53,8 +53,6 @@ export default {
projectBadge: 'プロジェクト',
newProject: '新規プロジェクト',
contentAlreadyOpen: 'コンテンツはすでに開いています',
- unableToOpenConversation:
- '会話を開けませんでした。もう一度お試しください。',
mobileSearchPlaceholder: '検索…',
closeSearch: '検索を閉じる',
searchFullTextFor: '「{{query}}」を全文検索',
diff --git a/apps/web/src/lib/i18n/locales/ko.ts b/apps/web/src/lib/i18n/locales/ko.ts
index 2ac1e23b33..66b16c3088 100644
--- a/apps/web/src/lib/i18n/locales/ko.ts
+++ b/apps/web/src/lib/i18n/locales/ko.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: '프로젝트',
newProject: '새 프로젝트',
contentAlreadyOpen: '이미 열려 있는 콘텐츠',
- unableToOpenConversation: '대화를 열 수 없습니다. 다시 시도해 주세요.',
mobileSearchPlaceholder: '검색…',
closeSearch: '검색 닫기',
searchFullTextFor: '“{{query}}” 전체 텍스트 검색',
diff --git a/apps/web/src/lib/i18n/locales/nb.ts b/apps/web/src/lib/i18n/locales/nb.ts
index 595a5a5ade..44a8726dfe 100644
--- a/apps/web/src/lib/i18n/locales/nb.ts
+++ b/apps/web/src/lib/i18n/locales/nb.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: 'Prosjekt',
newProject: 'Nytt prosjekt',
contentAlreadyOpen: 'Innholdet er allerede åpent',
- unableToOpenConversation: 'Kan ikke åpne samtalen. Prøv igjen.',
mobileSearchPlaceholder: 'Søk…',
closeSearch: 'Lukk søk',
searchFullTextFor: 'Søk i fulltekst etter «{{query}}»',
diff --git a/apps/web/src/lib/i18n/locales/nl.ts b/apps/web/src/lib/i18n/locales/nl.ts
index 1c3bcf8a57..be60892ead 100644
--- a/apps/web/src/lib/i18n/locales/nl.ts
+++ b/apps/web/src/lib/i18n/locales/nl.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: 'Project',
newProject: 'Nieuw project',
contentAlreadyOpen: 'Inhoud is al geopend',
- unableToOpenConversation: 'Kan gesprek niet openen. Probeer het opnieuw.',
mobileSearchPlaceholder: 'Zoeken…',
closeSearch: 'Zoeken sluiten',
searchFullTextFor: 'Volledige tekst doorzoeken op “{{query}}”',
diff --git a/apps/web/src/lib/i18n/locales/pl.ts b/apps/web/src/lib/i18n/locales/pl.ts
index f3aa9cc679..3dfabdcaae 100644
--- a/apps/web/src/lib/i18n/locales/pl.ts
+++ b/apps/web/src/lib/i18n/locales/pl.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: 'Projekt',
newProject: 'Nowy projekt',
contentAlreadyOpen: 'Ta zawartość jest już otwarta',
- unableToOpenConversation: 'Nie można otworzyć rozmowy. Spróbuj ponownie.',
mobileSearchPlaceholder: 'Szukaj…',
closeSearch: 'Zamknij wyszukiwanie',
searchFullTextFor: 'Szukaj w pełnym tekście „{{query}}”',
diff --git a/apps/web/src/lib/i18n/locales/pt-PT.ts b/apps/web/src/lib/i18n/locales/pt-PT.ts
index 5af672b4ea..77a850e798 100644
--- a/apps/web/src/lib/i18n/locales/pt-PT.ts
+++ b/apps/web/src/lib/i18n/locales/pt-PT.ts
@@ -53,8 +53,6 @@ export default {
projectBadge: 'Projeto',
newProject: 'Novo projeto',
contentAlreadyOpen: 'Conteúdo já aberto',
- unableToOpenConversation:
- 'Não foi possível abrir a conversa. Tente novamente.',
mobileSearchPlaceholder: 'Pesquisar…',
closeSearch: 'Fechar pesquisa',
searchFullTextFor: 'Pesquisar texto completo por «{{query}}»',
diff --git a/apps/web/src/lib/i18n/locales/ru.ts b/apps/web/src/lib/i18n/locales/ru.ts
index 6b0a469660..a23498b3b3 100644
--- a/apps/web/src/lib/i18n/locales/ru.ts
+++ b/apps/web/src/lib/i18n/locales/ru.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: 'Проект',
newProject: 'Новый проект',
contentAlreadyOpen: 'Содержимое уже открыто',
- unableToOpenConversation: 'Не удалось открыть беседу. Повторите попытку.',
mobileSearchPlaceholder: 'Поиск…',
closeSearch: 'Закрыть поиск',
searchFullTextFor: 'Полнотекстовый поиск «{{query}}»',
diff --git a/apps/web/src/lib/i18n/locales/sv.ts b/apps/web/src/lib/i18n/locales/sv.ts
index d2ee151bf3..2600e56cd0 100644
--- a/apps/web/src/lib/i18n/locales/sv.ts
+++ b/apps/web/src/lib/i18n/locales/sv.ts
@@ -53,8 +53,6 @@ export default {
projectBadge: 'Projekt',
newProject: 'Nytt projekt',
contentAlreadyOpen: 'Innehållet är redan öppet',
- unableToOpenConversation:
- 'Det gick inte att öppna konversationen. Försök igen.',
mobileSearchPlaceholder: 'Sök…',
closeSearch: 'Stäng sökning',
searchFullTextFor: 'Fritextsök efter ”{{query}}”',
diff --git a/apps/web/src/lib/i18n/locales/th.ts b/apps/web/src/lib/i18n/locales/th.ts
index c4f97028da..bd657eebc8 100644
--- a/apps/web/src/lib/i18n/locales/th.ts
+++ b/apps/web/src/lib/i18n/locales/th.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: 'โปรเจ็กต์',
newProject: 'โปรเจ็กต์ใหม่',
contentAlreadyOpen: 'เปิดเนื้อหานี้อยู่แล้ว',
- unableToOpenConversation: 'เปิดการสนทนาไม่ได้ โปรดลองอีกครั้ง',
mobileSearchPlaceholder: 'ค้นหา…',
closeSearch: 'ปิดการค้นหา',
searchFullTextFor: 'ค้นหาข้อความทั้งหมดสำหรับ “{{query}}”',
diff --git a/apps/web/src/lib/i18n/locales/translated-from.json b/apps/web/src/lib/i18n/locales/translated-from.json
index 60a8e1cd7b..a9657c7b20 100644
--- a/apps/web/src/lib/i18n/locales/translated-from.json
+++ b/apps/web/src/lib/i18n/locales/translated-from.json
@@ -58,7 +58,6 @@
"commandMenu.searchPlaceholder": "7f55382219",
"commandMenu.searchResults": "e978b00de4",
"commandMenu.selectItem": "2d94cc671b",
- "commandMenu.unableToOpenConversation": "1c536457c7",
"commandMenu.unableToOpenResult": "8e07b09554",
"commands.account": "7e1b0d5641",
"commands.autoDetectColorScheme": "8c712cb549",
diff --git a/apps/web/src/lib/i18n/locales/vi.ts b/apps/web/src/lib/i18n/locales/vi.ts
index 0d6adcbb61..bf2a1d50ad 100644
--- a/apps/web/src/lib/i18n/locales/vi.ts
+++ b/apps/web/src/lib/i18n/locales/vi.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: 'Dự án',
newProject: 'Dự án mới',
contentAlreadyOpen: 'Nội dung đã được mở',
- unableToOpenConversation: 'Không thể mở cuộc trò chuyện. Vui lòng thử lại.',
mobileSearchPlaceholder: 'Tìm kiếm…',
closeSearch: 'Đóng tìm kiếm',
searchFullTextFor: 'Tìm toàn văn “{{query}}”',
diff --git a/apps/web/src/lib/i18n/locales/zh-Hans.ts b/apps/web/src/lib/i18n/locales/zh-Hans.ts
index 2e39bd3ef9..ac825b266e 100644
--- a/apps/web/src/lib/i18n/locales/zh-Hans.ts
+++ b/apps/web/src/lib/i18n/locales/zh-Hans.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: '项目',
newProject: '新建项目',
contentAlreadyOpen: '内容已打开',
- unableToOpenConversation: '无法打开对话,请重试。',
mobileSearchPlaceholder: '搜索…',
closeSearch: '关闭搜索',
searchFullTextFor: '全文搜索“{{query}}”',
diff --git a/apps/web/src/lib/i18n/locales/zh-Hant.ts b/apps/web/src/lib/i18n/locales/zh-Hant.ts
index 6733376581..20bfb5e853 100644
--- a/apps/web/src/lib/i18n/locales/zh-Hant.ts
+++ b/apps/web/src/lib/i18n/locales/zh-Hant.ts
@@ -53,7 +53,6 @@ export default {
projectBadge: '專案',
newProject: '新增專案',
contentAlreadyOpen: '內容已開啟',
- unableToOpenConversation: '無法開啟對話,請再試一次。',
mobileSearchPlaceholder: '搜尋…',
closeSearch: '關閉搜尋',
searchFullTextFor: '全文搜尋「{{query}}」',
diff --git a/apps/web/src/lib/queries/channel/channels.ts b/apps/web/src/lib/queries/channel/channels.ts
index 73b22011f1..f828357161 100644
--- a/apps/web/src/lib/queries/channel/channels.ts
+++ b/apps/web/src/lib/queries/channel/channels.ts
@@ -55,6 +55,11 @@ export function useListChannelsQuery(enabled: Accessor<boolean> = () => true) {
return useQuery(() => ({ ...listChannelsQueryOptions, enabled: enabled() }));
}
+/** The viewer's channel list: the cached copy when loaded, fetched otherwise. */
+export function loadChannelList(): Promise<ApiChannelWithLatest[]> {
+ return queryClient.ensureQueryData(listChannelsQueryOptions);
+}
+
// The host is an app-level cache service, not component state; the key
// already namespaces on its client id.
function cachedGraphqlChannelsQueryOptions(cacheHost: CacheHost | undefined) {
diff --git a/apps/web/src/lib/queries/channel/get-or-create-dm.ts b/apps/web/src/lib/queries/channel/get-or-create-dm.ts
index 2b599f5009..b88da64cc8 100644
--- a/apps/web/src/lib/queries/channel/get-or-create-dm.ts
+++ b/apps/web/src/lib/queries/channel/get-or-create-dm.ts
@@ -2,12 +2,15 @@ import { fireAndForget } from '@core/util/fireAndForget';
import { throwOnErr } from '@core/util/result';
import { Telemetry, type TraceContext } from '@macro-inc/observability';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
+import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';
import {
type GetOrCreateChannelResponse,
storageServiceClient,
} from '@service-storage/client';
+import { ChannelType } from '@service-storage/generated/schemas/channelType';
import { useMutation } from '@tanstack/solid-query';
-import { invalidateListChannels } from './channels';
+import { ResultAsync } from 'neverthrow';
+import { invalidateListChannels, loadChannelList } from './channels';
type GetOrCreateDmResponse = GetOrCreateChannelResponse;
@@ -58,16 +61,36 @@ export function useGetOrCreateDirectMessageMutation(
}
/**
- * Resolves the 1:1 DM with a recipient when a control is pressed. Avatars in
- * a message list render by the dozen, and a mutation observer per avatar
- * costs setup for a press that rarely comes.
+ * The 1:1 DM between `viewerId` and `recipientId` in a channel list, picked as
+ * the server's get-or-create picks it: the oldest two-member DM with both.
*/
-export async function getOrCreateDirectMessage(recipientId: string) {
- const result = await storageServiceClient.getOrCreateDirectMessage({
- recipient_id: recipientId,
- });
- fireAndForget(invalidateListChannels(), 'channel-list');
- return result;
+function findDirectMessage(
+ channels: ApiChannelWithLatest[],
+ viewerId: string,
+ recipientId: string
+): string | undefined {
+ let found: ApiChannelWithLatest | undefined;
+ for (const channel of channels) {
+ if (channel.channel_type !== ChannelType.direct_message) continue;
+ if (channel.participants.length !== 2) continue;
+ const members = channel.participants.map(({ user_id }) => user_id);
+ if (!members.includes(viewerId) || !members.includes(recipientId)) continue;
+ if (!found || channel.created_at < found.created_at) found = channel;
+ }
+ return found?.id;
+}
+
+/**
+ * The viewer's existing DM with a recipient, without creating one. Reads the
+ * channel list the app already keeps, fetching it only when it isn't loaded.
+ */
+export function existingDirectMessage(
+ viewerId: string,
+ recipientId: string
+): ResultAsync<string | undefined, unknown> {
+ return ResultAsync.fromPromise(loadChannelList(), (error) => error).map(
+ (channels) => findDirectMessage(channels, viewerId, recipientId)
+ );
}
type GetOrCreatePrivateChannelParams = {
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index f8d2a3c38a..94607eecaf 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -84,7 +84,17 @@ new page cursor before deciding whether to request another page.
An empty human DM shows the centered conversations illustration and “Say hello”
above the composer. The copy explains that recipients without a Macro account
-receive the message by email. Opening the DM sends nothing. Sending a human
+receive the message by email. Opening the DM sends nothing.
+
+Opening a person you have no DM with shows this same empty DM, with their name
+and avatar in the header, under a temporary `pending-dm-` id kept only in that
+tab. Nothing exists on the server, so the DM is in neither person's list until
+the first message creates it and the view becomes the real conversation. Check
+that leaving without sending creates nothing, that the other person's list gains
+the DM only after the send, and that reloading a `pending-dm-` URL opens the
+Chat list on desktop and closes the pane on touch.
+
+Sending a human
message queues an immediate email for nonusers, including follow-up messages,
replies, and mentions; registered users retain their notification preferences.
Check narrow and wide panes: the composer stays usable, and the empty state
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index e3cf0f599b..e9d2185961 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -1074,7 +1074,12 @@ its page under Settings → Bots. An agent's avatar beside its channel messages
opens the same card. Touch devices have no hover, so tapping the mention
or the picture opens that same card as a bottom sheet; any action there runs and
dismisses the sheet. Desktop keeps click-to-DM on the picture itself, which touch
-drops in favour of the card's DM action.
+drops in favour of the card's DM action. DM, the picture click, channel and call
+participants, and people in Cmd+K open the existing DM. Without one they open
+the DM anyway, as an empty DM under a temporary `pending-dm-` id that nothing on
+the server knows; the first message creates the DM and replaces it, so opening
+someone never adds an empty DM to either person's list. See
+[Empty direct messages](channels.md#empty-direct-messages).
`Create` button (top-left) opens a menu of: Email E, Routine U, Agent A, Skill K,
Document D, Task T, Project P, Snippet S, Message M, Channel G, Call C, Canvas N, Folder F, Code O.
diff --git a/docs/agent-guide/search.md b/docs/agent-guide/search.md
index 6ce8e6fa15..29bebdadf3 100644
--- a/docs/agent-guide/search.md
+++ b/docs/agent-guide/search.md
@@ -27,7 +27,8 @@ independently of view tabs, mailbox selections, and saved facets. Commands and
creation shortcuts are excluded. Empty queries show recent entities.
Typed **All** and **People** name searches also find known teammates before their
first DM, with or without CRM. Existing one-to-one DMs replace person rows while
-preserving name/email matches; selecting a person opens their DM. Verify both
+preserving name/email matches; selecting a person opens their DM, which the
+first message creates when there isn't one yet. Verify both
categories with a teammate who has no conversation or CRM record.
Name search here, in Command K, and in the Chat sidebar finds a conversation by
its participants in any order, separated by spaces or commas, with name prefixes
@@ -83,8 +84,8 @@ scroll position. Opening a result does not promote it within that saved list,
even when its last-viewed time changes. Swiping back, pressing the native Back control, or using browser Back
returns to those results without focusing the input or reopening the keyboard.
Name-result ordering and scroll anchors identify a one-to-one DM by its other
-participant, so a person keeps their place when opening them creates a conversation
-with a new channel ID. Group conversations keep their own channel identity.
+participant, so a person keeps their place when their first message creates a
+conversation with a new channel ID. Group conversations keep their own channel identity.
Native Search captures lightweight state when covered so deeper navigation can
unmount it. History saves the query/category/mode, an account-scoped item ID and
offset within that row, a fallback pixel offset, and at most 200 ordering IDs per
@@ -108,8 +109,8 @@ from a historical snapshot. A later search
cannot overwrite an earlier entry. **Close search** ends the
session; opening Search from the dock starts in All/name mode. Mobile search state
does not modify desktop search state. The dock search row has no Ask AI button.
-If a person’s conversation lookup fails, search stays open with its query and
-category intact so the result can be retried.
+If opening a person fails, search stays open with its query and category intact
+so the result can be retried.
Verify sender-only `teo` matches with one- and two-character prefixes, then switch
categories with the keyboard up. In both name and full-text modes, scroll several
@@ -121,8 +122,8 @@ Open a result from midway through the list and confirm it keeps its original
position after Back, both when Search stays mounted and after deeper navigation
evicts it. Refresh row metadata and append pages; existing rows must keep their order.
Include a person without a DM: open them from midway through All/People results,
-then go Back and confirm that person's new DM is still in the same place and opens
-the existing conversation on a second selection. Repeat with the DM arriving after
+send them a message, then go Back and confirm that person's new DM is
+still in the same place and opens the existing conversation on a second selection. Repeat with the DM arriving after
Search unmounts, and verify group DMs stay separate.
Switch accounts with a scrolled Search entry still mounted, then remount that
entry: neither path should retain the previous account's rows or scroll offset.