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.

58.1 KB
Raw Blame
import {
  AgentConversationContextBoundary,
  AgentConversationMessageStatus,
} from '@app/features/agent-conversations/agent-conversation-message';
import { AgentConversationsProvider } from '@app/features/agent-conversations/agent-conversations-provider';
import { AgentDmComposer } from '@app/features/agent-dms/agent-dm-composer';
import { openChatWithInput } from '@app/features/chat/ChatWithAgentButton';
import { taskSourceComposerContext } from '@app/features/task-composer/source-context';
import { t } from '@app/lib/i18n';
import { beginInteraction, usePending } from '@app/observability/flow';
import { startUiOperation } from '@app/observability/ui-operation';
import { createActivityTracker } from '@channel/activity-tracker';
import { useStartChannelCall } from '@channel/Call/use-start-channel-call';
import { DebugSuspense } from '@channel/DebugSuspense';
import {
  ChannelInput,
  type ChannelInputProps,
} from '@channel/Input/ChannelInput';
import { buildPostMessageSendPayload } from '@channel/Input/message-payload';
import {
  makeAttachmentTrackerPersistenceKey,
  makeInputValuePersistenceKey,
} from '@channel/Input/utils/persistence';
import {
  type MessageData,
  SearchHighlightTermsProvider,
} from '@channel/Message';
import { MaybeMessageActionDrawerManager } from '@channel/Mobile/MessageActionDrawerManager';
import { useMessageBotMentionUsers } from '@channel/use-channel-bot-mention-users';
import { useChannelParticipants } from '@channel/use-channel-participants';
import { FloatRegionOrInline } from '@components/app/mobile/float-regions/FloatRegion';
import { FloatRegions } from '@components/app/mobile/float-regions/float-region-state';
import { SwipableRowProvider } from '@components/app/mobile/SwipableRow';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { useSplitPanel } from '@components/app/split-layout/layoutUtils';
import {
  EntityLoadGate,
  toEntityLoadError,
} from '@core/component/EntityLoadGate';
import { FindBar } from '@core/component/FindBar';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { toast } from '@core/component/Toast/Toast';
import { ENABLE_CALLS } from '@core/constant/featureFlags';
import {
  useChannel,
  useChannelActivity,
  useChannelName,
  useChannelType,
} from '@core/context/channels';
import { useUserId } from '@core/context/user';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import type { DateValue } from '@core/util/date';
import { fireAndForget } from '@core/util/fireAndForget';
import {
  extractUserMentions,
  trimEdgeUserMentions,
} from '@core/util/taskExtraction';
import {
  buildMentionMarkdownString,
  markdownToPlainText,
} from '@macro-inc/lexical-core';
import { Telemetry } from '@macro-inc/observability';
import { MessageNotificationIndexContext } from '@notifications/components/MarkMessageNotifications';
import { recordChannelViewWhenIdle } from '@queries/channel/activity';
import { queryClient } from '@queries/client';
import { queryReadyGate } from '@queries/gate';
import {
  newMessageId,
  useDeleteMessageMutation,
  usePatchMessageMutation,
  useSendMessageMutation,
} from '@queries/messages/mutations';
import {
  useAddReactionMutation,
  useRemoveReactionMutation,
} from '@queries/messages/reactions';
import { threadRepliesQueryOptions } from '@queries/messages/thread-replies';
import {
  createMessageIndex,
  getMessageTimelineQueryKey,
  isMissingMessageError,
  type MessageTimelineData,
  useMessageTimelineQuery,
} from '@queries/messages/timeline';
import { timelineEntryKey } from '@queries/messages/timeline-entries';
import { usePostTypingUpdateMutation } from '@queries/messages/typing';
import { ChannelTypeEnum } from '@service-storage/client';
import { tourTarget } from '@ui/components/Tour';
import { cn } from '@ui/utils/classname';
import {
  createEffect,
  createMemo,
  createSignal,
  Match,
  on,
  onCleanup,
  onMount,
  type ParentProps,
  Show,
  Switch,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { CallRootLine } from '../Call/discussion/CallRootLine';
import { OutsideMessagesPopup } from '../Call/discussion/OutsideMessagesPopup';
import { outsideMessages } from '../Call/discussion/outside-messages';
import { ChannelAccessDenied } from '../ChannelAccessDenied';
import {
  createInputAttachmentTracker,
  type InputHandle,
  type InputSnapshot,
} from '../Input';
import { ChannelInputContainer } from '../Input/ChannelInputContainer';
import { hasSendableInputContent } from '../Input/utils/sendable-content';
import {
  decodeSystemActivityRow,
  mergesSystemActivity,
} from '../queries/system-activity';
import { SystemActivity } from '../SystemActivity';
import { ChannelThread } from '../Thread';
import { ThreadRow } from '../Thread/ThreadRow';
import { ThreadTypingIndicator } from '../Thread/ThreadTypingIndicator';
import { buildReplyTargetValue } from '../Thread/utils/message-actions';
import { CHANNEL_TOUR } from '../tour';
import { isUnifiedInputMode } from '../unified-input-mode';
import { ActiveCallMessage } from './ActiveCallMessage';
import { ChannelDropZone } from './ChannelDropZone';
import { ChannelLoading } from './ChannelLoading';
import { createChannelDragState } from './create-channel-drag-state';
import { createChannelFindBar } from './create-channel-find-bar';
import { createChannelHotkeys } from './create-channel-hotkeys';
import { createChannelKeyboardHandler } from './create-channel-keyboard-handler';
import { createChannelMessageActions } from './create-channel-message-actions';
import { createChannelUnreadNavigation } from './create-channel-unread-navigation';
import { createDeleteMessageConfirmation } from './create-delete-message-confirmation';
import { createMessageEditor } from './create-message-editor';
import { createMessageSelection } from './create-message-selection';
import {
  clearStaleRestoredChannelData,
  createTargetMessageController,
  type TargetMessageController,
} from './create-target-message-controller';
import { DirectMessageEmptyState } from './DirectMessageEmptyState';
import { buildChannelMessageListMeta } from './message-list-meta';
import { ScrollToBottomOverlay } from './ScrollToBottomOverlay';
import {
  ThreadList,
  type ThreadListNavigation,
  type ThreadListScrollSnapshot,
  type ThreadListScrollState,
} from './ThreadList';
import {
  createThreadManager,
  type ThreadManagerSnapshot,
} from './thread-manager';
import { createThreadPaginator } from './thread-paginator';
import { UnifiedEditInput } from './UnifiedEditInput';
import { UnifiedReplyInput } from './UnifiedReplyInput';
import { UnreadNotificationsOverlay } from './UnreadNotificationsOverlay';
import {
  createUnifiedInputManager,
  type UnifiedReplyTargetSnapshot,
} from './unified-input-manager';
import type { UnreadThread } from './unread-thread-navigation';

export type ChannelProps = {
  channelId: string;
  targetMessageId?: string | undefined;
  targetMessageReplyId?: string | undefined;
  lastViewedAt?: DateValue | null;
  initialMessagesStateSnapshot?: MessageTimelineStateSnapshot;
  onHandleReady?: (handle: ChannelHandle) => void;
  /** Whether to auto-focus the channel input on mount. Defaults to `!isTouchDevice()`. */
  autofocus?: boolean;
  /** Shows the channel inside a call, opened on that call's thread. */
  callPanel?: {
    /** The root of the call's thread. */
    rootId: string;
    onViewChannel: () => void;
    onOutsideCountChange?: (count: number) => void;
  };
};

export type MessageTimelineStateSnapshot = {
  scroll?: ThreadListScrollSnapshot;
  threads?: ThreadManagerSnapshot;
  /** The unified input's reply binding, persisted by ids only. */
  replyTarget?: UnifiedReplyTargetSnapshot;
};

export type ChannelHandle = {
  goToMessage: TargetMessageController['goToMessage'];
  goToLatest: (behavior?: ScrollBehavior) => void;
  getMessagesStateSnapshot: () => MessageTimelineStateSnapshot | undefined;
};

/** A composer that stays where it is, for a surface with no floating chrome. */
function InPlaceRegion(props: ParentProps) {
  return <>{props.children}</>;
}

export function Channel(props: ChannelProps) {
  // Read once: a channel doesn't change between being a panel and not.
  const callPanel = props.callPanel;
  // The panel has one composer however wide it is, always bound to a thread.
  const usesUnifiedInput = () => !!callPanel || isUnifiedInputMode();
  const userId = useUserId();
  const splitPanel = useSplitPanel();
  const channelCall = useStartChannelCall(() => props.channelId);

  // Full-frame mobile/tablet: the thread list spans the whole screen and messages
  // scroll behind the floating header islands (top) and the floating
  // input + dock (bottom). contentOffsetTop already includes the safe area.
  const threadListScrollInsets = () =>
    isTouchDevice()
      ? {
          start: splitPanel?.contentOffsetTop() ?? 0,
          // '4' here is a magic offset so that the ThreadRail correctly hits the the curved edge of the floating input. Not idea, but low impact and it works.
          end: FloatRegions.hostHeight() - 4,
        }
      : { start: 0, end: 0 };

  const sendMessageMutation = useSendMessageMutation();
  const patchMessageMutation = usePatchMessageMutation();
  const deleteMessageMutation = useDeleteMessageMutation();
  const typingMutation = usePostTypingUpdateMutation();
  const addReactionMutation = useAddReactionMutation();
  const removeReactionMutation = useRemoveReactionMutation();

  const [threadListNavigation, setThreadListNavigation] =
    createSignal<ThreadListNavigation>();
  const [threadListScrollState, setThreadListScrollState] =
    createSignal<ThreadListScrollState>();
  // Hosts the swipe-to-reply gesture listeners (mobile).
  const [threadListContainerEl, setThreadListContainerEl] =
    createSignal<HTMLElement>();

  // When opening without a target, clear stale data that was previously
  // restored from a load-around session so the query fetches from the bottom.
  if (!props.targetMessageId) {
    clearStaleRestoredChannelData(props.channelId);
  }

  const targetMessageController = createTargetMessageController({
    channelId: () => props.channelId,
    initialTargetMessageId: props.targetMessageId,
    initialTargetMessageReplyId: props.targetMessageReplyId,
    // changing the array reference is required to trigger the scroll effect
    messageKeys: () => [...messageIndex.keys],
    isReady: () => !!threadListNavigation(),
  });

  const messagesTarget = tourTarget(CHANNEL_TOUR.messages);
  const composerTarget = tourTarget(CHANNEL_TOUR.composer);
  const [channelInputSnapshot, setChannelInputSnapshot] =
    createSignal<InputSnapshot>();
  const [channelInputHandle, setChannelInputHandle] =
    createSignal<InputHandle>();

  const messagesQuery = useMessageTimelineQuery(
    () => ({ type: 'channel', id: (() => props.channelId)() }),
    targetMessageController.loadAroundMessageId
  );
  usePending('channel.messages', () => messagesQuery.isLoading);
  const isTargetMessageMissing = () =>
    targetMessageController.loadAroundMessageId() !== undefined &&
    isMissingMessageError(messagesQuery.error);
  const messagesLoadResult = {
    data: () => messagesQuery.data,
    // Pagination and background-refresh errors should not replace content that
    // has already loaded. Only initial-loading errors belong to the gate.
    error: () =>
      messagesQuery.isLoadingError && !isTargetMessageMissing()
        ? toEntityLoadError(messagesQuery.error)
        : undefined,
    // Keep the loading view mounted while the missing-target handler switches
    // the query back to the latest page.
    isPending: () => messagesQuery.isPending || isTargetMessageMissing(),
  };

  createEffect(
    on(
      [targetMessageController.loadAroundMessageId, () => messagesQuery.error],
      ([loadAroundMessageId, error]) => {
        if (!loadAroundMessageId || !isMissingMessageError(error)) return;

        toast.alert('Message no longer available', {
          subtext: 'Showing the latest messages instead.',
        });
        clearStaleRestoredChannelData(props.channelId);
        targetMessageController.reset();
      }
    )
  );

  // The index reads immediately, before EntityLoadGate's boundary exists.
  const messageIndex = createMessageIndex(
    () =>
      queryReadyGate(messagesQuery)
        ? (messagesQuery.data as MessageTimelineData)
        : undefined,
    mergesSystemActivity
  );

  const messageById = () => messageIndex.byId;
  // Loaded messages, oldest first; activity rows are not unread targets.
  const messages = createMemo(() => [...messageIndex.byId.values()]);
  const unread = createChannelUnreadNavigation({
    channelId: props.channelId,
    messages,
    activities: () => messageIndex.activityByKey,
    scrollState: threadListScrollState,
    container: threadListContainerEl,
    insets: threadListScrollInsets,
    onDestinationsChanged: () => threadListNavigation()?.requestLayoutUpdate(),
  });
  const participants = useChannelParticipants(() => props.channelId);
  const channelBotMentionUsers = useMessageBotMentionUsers(() => ({
    type: 'channel',
    id: props.channelId,
  }));

  const activity = useChannelActivity(props.channelId);

  // One view on entry, after the first page and away from the open's own
  // requests, and one on leaving. The channel remounts per id, so cleanup
  // covers every way out of it.
  let entryViewRecorded = false;
  createEffect(
    on(
      () => queryReadyGate(messagesQuery),
      (loaded) => {
        // The panel hides what's new in the channel, so it hasn't been seen.
        if (callPanel || !loaded || entryViewRecorded) return;
        entryViewRecorded = true;
        recordChannelViewWhenIdle(props.channelId);
      }
    )
  );
  onCleanup(() => {
    if (!callPanel) recordChannelViewWhenIdle(props.channelId);
  });

  // Rows newer than the call are the channel's, not the call's.
  const rowKeys = createMemo(() => {
    if (!callPanel) return messageIndex.entryKeys;
    const root = messageIndex.entryKeys.indexOf(callPanel.rootId);
    return root < 0 ? [] : messageIndex.entryKeys.slice(0, root + 1);
  });

  // A long-running call's row can be further back than the newest page.
  createEffect(
    on(
      () =>
        !!callPanel &&
        !messageById().has(callPanel.rootId) &&
        messagesQuery.hasNextPage &&
        !messagesQuery.isFetchingNextPage,
      (shouldLoadOlder) => {
        if (shouldLoadOlder) {
          fireAndForget(messagesQuery.fetchNextPage(), 'channel-call');
        }
      }
    )
  );

  const [outsideSince, setOutsideSince] = createSignal(
    new Date().toISOString()
  );
  const outside = createMemo(() =>
    callPanel
      ? outsideMessages(messageIndex.entries, {
          since: outsideSince(),
          currentUserId: userId(),
        })
      : []
  );
  createEffect(
    on(
      () => outside().length,
      (count) => callPanel?.onOutsideCountChange?.(count)
    )
  );
  const viewChannelFromPanel = () => {
    if (!callPanel) return;

    beginInteraction('call.panel.view_channel', {
      attributes: {
        'channel.id': props.channelId,
        'call.id': callPanel.rootId,
        'call.panel.outside_count': outside().length,
      },
      closeOnJoin: true,
    });
    setOutsideSince(new Date().toISOString());
    callPanel.onViewChannel();
  };

  const [liveCallRowVisible, setLiveCallRowVisible] = createSignal(false);

  const unifiedInput = createUnifiedInputManager({
    initialReplyTarget: props.initialMessagesStateSnapshot?.replyTarget,
    defaultThreadId: callPanel?.rootId,
    // Clear any highlight left by tapping the reply flag's navigate action.
    onReplyThreadReleased: (threadId) => releaseSelectionAndTarget(threadId),
  });

  const threadManager = createThreadManager(
    props.initialMessagesStateSnapshot?.threads
  );
  if (callPanel) {
    threadManager.getOrCreateThreadState(callPanel.rootId).setIsExpanded(true);
  }

  const prepareTargetReply = (threadId: string) => {
    // Expand before the virtualized row mounts so navigation never presents a
    // collapsed parent and then grows it in the viewport.
    threadManager.getOrCreateThreadState(threadId).setIsExpanded(true);
    // Reply data and the load-around message window can load in parallel. The
    // mounted query reuses this request and remains the owner of render state.
    queryClient.prefetchQuery(
      threadRepliesQueryOptions(
        { type: 'channel', id: props.channelId },
        threadId
      )
    );
  };

  if (props.targetMessageId && props.targetMessageReplyId) {
    prepareTargetReply(props.targetMessageId);
  }

  const threadPaginator = createThreadPaginator(messagesQuery);
  const messageEditor = createMessageEditor({
    parent: () => ({ type: 'channel', id: (() => props.channelId)() }),

    patchMessage: patchMessageMutation.mutate,
    onEditEnded: (message) => {
      // Clear any highlight left by tapping the edit flag's navigate action
      // (which selects and nav-targets the edited message's thread).
      if (usesUnifiedInput()) {
        releaseSelectionAndTarget(message.thread_id ?? message.id);
      }
    },
  });

  const activityTracker = createActivityTracker({
    lastViewedAt: () => activity()?.viewed_at,
    userId,
  });

  const listMetaByKey = createMemo(() =>
    buildChannelMessageListMeta(
      messageIndex.entries,
      activityTracker.isNewMessage,
      // Once there are no older pages left to fetch, the oldest loaded message
      // (index 0) is the true first message in the channel.
      !messagesQuery.hasNextPage,
      // Only an inline composer extends the rail before a reply exists.
      (message) =>
        !usesUnifiedInput() &&
        threadManager.getOrCreateThreadState(message.id).isReplying()
    )
  );

  const attachmentTracker = createInputAttachmentTracker({
    persistenceKey: makeAttachmentTrackerPersistenceKey({
      channelId: props.channelId,
    }),
  });

  const dragState = createChannelDragState({
    channelId: props.channelId,
  });

  const channelName = useChannelName(props.channelId);
  const channel = useChannel(props.channelId);
  const channelType = useChannelType(props.channelId);
  const { popoverSplit } = useSplitLayout();

  // Placeholder name: channels render as "#name"; a 1:1 DM named "First Last"
  // shortens to the first name, and group DMs like "A, B" keep their full name.
  const inputPlaceholderName = () => {
    const name = channelName();
    if (!name) return undefined;
    if (channel()?.agent_dm) return name;
    if (channelType() !== ChannelTypeEnum.DirectMessage) return `#${name}`;
    const parts = name.split(' ');
    return parts.length === 2 && !parts[0]?.endsWith(',') ? parts[0] : name;
  };

  const inputPlaceholder = () => {
    const name = inputPlaceholderName();
    if (channel()?.agent_dm) return `Message ${name ?? 'agent'}`;
    return name ? `Type @ to share with ${name}` : 'Type @ to share';
  };

  const buildChannelMessageMention = (message: {
    id: string;
    thread_id?: string | null;
  }) =>
    buildMentionMarkdownString({
      type: 'document',
      documentId: props.channelId,
      documentName: channelName() ?? '',
      blockName: 'channel',
      blockParams: {
        channel_message_id: message.id,
        ...(message.thread_id && { channel_thread_id: message.thread_id }),
      },
    });

  const openReplyInput = (message: MessageData) => {
    const threadId = message.thread_id ?? message.id;
    const state = threadManager.getOrCreateThreadState(threadId);
    if (usesUnifiedInput()) {
      unifiedInput.bindReply(message);
      state.setIsExpanded(true);
    } else {
      state.setIsReplying(true);
    }
    state.replyInputFocusRequest.request();
    return state;
  };

  const openReplyTargetInput = (
    message: MessageData,
    selectedText?: string,
    renderedText?: string
  ) => {
    const threadId = message.thread_id ?? message.id;
    const state = threadManager.getOrCreateThreadState(threadId);
    const beforeSnapshot = state.replyInputState();
    const nextSnapshot: InputSnapshot = {
      value: buildReplyTargetValue({
        channelId: props.channelId,
        message,
        selectedText,
        renderedText,
        existingValue: beforeSnapshot?.value,
      }),
      mentions: beforeSnapshot?.mentions ?? [],
      attachments: beforeSnapshot?.attachments ?? [],
    };

    state.setReplyInputState(nextSnapshot);
    if (usesUnifiedInput()) {
      unifiedInput.bindReply(message);
      state.setIsExpanded(true);
    } else {
      state.setIsReplying(true);
    }
    requestAnimationFrame(() => {
      state.replyInputHandle?.()?.restoreSnapshot(nextSnapshot, {
        focus: false,
        cursor: 'trailing-paragraph',
      });
      state.replyInputFocusRequest.request();
    });
  };

  const deleteConfirmation = createDeleteMessageConfirmation(
    deleteMessageMutation.mutate
  );

  const getMessageActions = createChannelMessageActions({
    parent: () => ({ type: 'channel', id: (() => props.channelId)() }),
    userId,
    deleteMessage: deleteConfirmation.requestDelete,
    addReaction: addReactionMutation.mutate,
    removeReaction: removeReactionMutation.mutate,
    onReply: (ctx) => {
      if (ctx.message.thread_id) {
        openReplyTargetInput(ctx.message, ctx.selectedText, ctx.renderedText);
        return;
      }
      openReplyInput(ctx.message);
    },
    onEdit: ({ message }) => {
      messageEditor.start(message);
    },
    onCreateTask: (ctx) => {
      const trimmedMarkdown = trimEdgeUserMentions(ctx.message.content);
      const plainText = markdownToPlainText(trimmedMarkdown).trim();
      const title =
        plainText.length > 70 ? `${plainText.slice(0, 70)}...` : plainText;
      const mentionedUserIds = extractUserMentions(ctx.message.content);
      popoverSplit({
        type: 'component',
        id: 'task-compose',
        params: {
          composerContext: taskSourceComposerContext({
            entity_type: 'CHANNEL',
            entity_id: props.channelId,
            specific_message_id: ctx.message.id,
          }),
          initialTitle: title,
          initialContent: buildChannelMessageMention(ctx.message),
          initialAssigneeIds:
            mentionedUserIds.length > 0 ? mentionedUserIds : undefined,
        },
      });
    },
    onChat: (ctx) => {
      openChatWithInput(`${buildChannelMessageMention(ctx.message)}\n\n`).catch(
        (error) => Telemetry.error(error, { surface: 'channel' })
      );
    },
  });

  const selection = createMessageSelection({
    keys: () => messageIndex.keys,
  });

  const selectMessage = (messageId: string) => {
    selection.select(messageId);
  };

  const clearSelection = () => {
    selection.clear();
  };

  const goToMessage: ChannelHandle['goToMessage'] = (messageId, replyId) => {
    cancelLatestNavigation();
    if (replyId) {
      clearSelection();
      prepareTargetReply(messageId);
    } else {
      selectMessage(messageId);
    }
    targetMessageController.goToMessage(messageId, replyId);
  };

  const goToUnread = (thread: UnreadThread | undefined) => {
    if (!thread) return;
    prepareTargetReply(thread.threadId);
    goToMessage(
      thread.threadId,
      thread.messageId === thread.threadId ? undefined : thread.messageId
    );
  };

  const releaseSelectionAndTarget = (threadId: string) => {
    if (selection.selectedId() === threadId) clearSelection();
    targetMessageController.clearActiveTarget(threadId);
  };

  const [threadListScrollSnapshot, setThreadListScrollSnapshot] = createSignal<
    ThreadListScrollSnapshot | undefined
  >(props.initialMessagesStateSnapshot?.scroll);

  const getMessagesStateSnapshot: ChannelHandle['getMessagesStateSnapshot'] =
    () => {
      const scroll = threadListScrollSnapshot();
      const threads = threadManager.getSnapshot();
      const boundReplyTarget = unifiedInput.getReplyTargetSnapshot();
      if (!scroll && !threads && !boundReplyTarget) return undefined;
      return {
        ...(scroll ? { scroll } : {}),
        ...(threads ? { threads } : {}),
        ...(boundReplyTarget ? { replyTarget: boundReplyTarget } : {}),
      };
    };

  const findBar = createChannelFindBar({
    channelId: () => props.channelId,
    goToMessage,
    clearSelection,
    isMessageLoaded: (id) => messageIndex.keys.includes(id),
  });

  // A latest request waits for both the query and the rendered list. Keeping
  // its identity prevents a late response from overriding newer navigation.
  let pendingLatest:
    | { phase: 'loading' | 'waiting-for-layout'; behavior?: ScrollBehavior }
    | undefined;
  const cancelLatestNavigation = () => {
    pendingLatest = undefined;
  };
  onCleanup(cancelLatestNavigation);

  const finishLatestNavigation = () => {
    if (
      pendingLatest?.phase !== 'waiting-for-layout' ||
      messagesQuery.isPending ||
      messagesQuery.hasPreviousPage
    )
      return;
    // Retained data is usable after a pagination error. Wait only if the query
    // has no data yet or the message index still contains the old page.
    const latestEntry = messagesQuery.data?.pages[0]?.entries[0];
    if (
      latestEntry !== undefined &&
      messageIndex.entryKeys.at(-1) === timelineEntryKey(latestEntry) &&
      threadListNavigation()?.scrollToLatest(pendingLatest.behavior)
    )
      cancelLatestNavigation();
  };

  const goToLatest: ChannelHandle['goToLatest'] = async (behavior) => {
    const request: NonNullable<typeof pendingLatest> = {
      phase: 'loading',
      behavior,
    };
    pendingLatest = request;
    try {
      const needsLatestPage =
        messagesQuery.hasPreviousPage ||
        !!targetMessageController.loadAroundMessageId();
      targetMessageController.reset();
      if (needsLatestPage) {
        await queryClient.resetQueries(
          {
            queryKey: getMessageTimelineQueryKey(
              { type: 'channel', id: props.channelId },
              null
            ),
          },
          { throwOnError: true }
        );
      }
      if (pendingLatest !== request) return;
      request.phase = 'waiting-for-layout';
      finishLatestNavigation();
    } catch {
      // The query presents the error; the failed request must not scroll later.
      if (pendingLatest === request) cancelLatestNavigation();
    }
  };

  const onThreadListScroll = (
    state: ThreadListScrollState,
    snapshot: ThreadListScrollSnapshot | undefined
  ) => {
    setThreadListScrollState(state);
    if (snapshot) setThreadListScrollSnapshot(snapshot);
    finishLatestNavigation();
  };

  const { messageListScopeId, attachMessageListRef, attachInputRef } =
    createChannelHotkeys({
      selection,
      scrollToMessage: (id, options) => {
        cancelLatestNavigation();
        return threadListNavigation()?.scrollToMessage(id, options) ?? false;
      },
      messageById,
      getMessageActions,
      userId,
      isEditing: () => !!messageEditor.state(),
      isInputEmpty: () =>
        (channelInputSnapshot()?.value.trim().length ?? 0) === 0,
      onOpenFindBar: findBar.open,
      onGoToBottom: goToLatest,
    });

  createChannelKeyboardHandler({
    scrollToLatest: () => threadListNavigation()?.scrollToLatest(),
    isNearBottom: () => threadListScrollState()?.isNearBottom ?? false,
    // The unified input's current binding — the edited message (the edit
    // face covers the reply face), else the reply target.
    boundMessageId: () => {
      const editing = messageEditor.state();
      if (editing) return editing.messageId;
      const replyTarget = unifiedInput.replyTarget();
      return replyTarget
        ? (replyTarget.replyId ?? replyTarget.threadId)
        : undefined;
    },
  });

  let sendSurfaceDisposed = false;
  onCleanup(() => {
    sendSurfaceDisposed = true;
  });

  const onSend: ChannelInputProps['onSend'] = (snapshot) => {
    const channelId = props.channelId;
    const senderId = userId();
    if (!senderId) return;
    const payload = buildPostMessageSendPayload({
      snapshot,
    });

    const optimisticId = newMessageId();
    // Send to the optimistic message's paint; channel.send follows delivery.
    const sendUi = startUiOperation('message.send', {
      attributes: { 'channel.id': channelId, 'message.id': optimisticId },
    });
    fireAndForget(
      Telemetry.span('channel.send', async (span) => {
        span.setAttr('message.id', optimisticId);
        span.setAttr('channel.id', channelId);
        try {
          await sendMessageMutation.mutateAsync({
            parentSpan: span,
            parent: { type: 'channel', id: channelId },
            senderId,
            optimisticId,
            onOptimisticInsert: sendUi.afterPaint,
            ...payload,
          });
          span.setAttr('composer.outcome', 'succeeded');
        } catch {
          sendUi.finish('error');
          span.error('Channel send failed');
          const handle = channelInputHandle();
          if (
            !handle ||
            sendSurfaceDisposed ||
            props.channelId !== channelId ||
            userId() !== senderId
          ) {
            span.setAttr('composer.outcome', 'unmounted');
            return;
          }
          const current = channelInputSnapshot();
          if (current && hasSendableInputContent(current)) {
            span.setAttr('composer.outcome', 'preserved_newer_draft');
            return;
          }
          handle.restoreSnapshot(snapshot);
          span.setAttr('composer.outcome', 'restored');
        }
      }),
      'channel-input'
    );
  };

  const onThreadListReady = (navigation: ThreadListNavigation) => {
    setThreadListNavigation(navigation);
    finishLatestNavigation();
    return () =>
      setThreadListNavigation((current) =>
        current === navigation ? undefined : current
      );
  };

  // Channel commands can queue before rows exist. Publish them on mount so
  // empty channels also support navigation and saving their input/thread state.
  onMount(() => {
    props.onHandleReady?.({
      goToMessage,
      goToLatest,
      getMessagesStateSnapshot,
    });
  });

  return (
    <AgentConversationsProvider
      channelId={props.channelId}
      // Only an agent DM has a conversing agent so far.
      hasAgents={!!channel()?.agent_dm}
    >
      <EntityLoadGate
        result={messagesLoadResult}
        loadingFallback={<ChannelLoading />}
        loadErrorTitle="Unable to load this channel"
        onRetry={() => fireAndForget(messagesQuery.refetch(), 'channel')}
        unauthorized={
          <ChannelAccessDenied
            channelId={props.channelId}
            onRefreshChannel={() =>
              fireAndForget(messagesQuery.refetch(), 'channel')
            }
          />
        }
      >
        <DebugSuspense name="Channel.root" fallback={<ChannelLoading />}>
          <deleteConfirmation.ConfirmationDialog />
          <StaticMarkdownContext host="channel">
            <SearchHighlightTermsProvider
              value={findBar.getSearchTermsForMessage}
            >
              <MaybeMessageActionDrawerManager>
                <ChannelDropZone dragState={dragState}>
                  <div
                    class="ph-no-capture relative flex-1 min-h-0 outline-none flex flex-col"
                    ref={(element) => {
                      attachMessageListRef(element);
                      messagesTarget(element);
                    }}
                    tabIndex={-1}
                    data-channel-message-list
                  >
                    <Show when={findBar.isOpen()}>
                      <FindBar
                        class="absolute top-2 right-3 z-10 w-80 max-w-[calc(100%-1.5rem)] touch:top-[calc(var(--mobile-content-inset-top,0)+0.5rem)]"
                        controller={findBar}
                        direction="desc"
                      />
                    </Show>
                    <Show
                      when={rowKeys().length > 0}
                      fallback={
                        <Show
                          when={
                            messagesQuery.isSuccess &&
                            channelType() === ChannelTypeEnum.DirectMessage &&
                            !channel()?.agent_dm
                          }
                        >
                          <DirectMessageEmptyState />
                        </Show>
                      }
                    >
                      <div
                        class={cn(
                          'relative flex-1 min-h-0',
                          callPanel && '[container-type:size]'
                        )}
                        ref={setThreadListContainerEl}
                      >
                        <MessageNotificationIndexContext.Provider
                          value={unread.unreadByMessage}
                        >
                          <SwipableRowProvider
                            container={threadListContainerEl}
                            triggerBehavior="spring-back"
                          >
                            <ThreadList
                              keys={rowKeys}
                              targetId={
                                targetMessageController.hasPendingElementScroll()
                                  ? targetMessageController.activeTargetMessageId()
                                  : undefined
                              }
                              insets={threadListScrollInsets()}
                              followOnAppend={!messagesQuery.hasPreviousPage}
                              onScrollNearTop={threadPaginator.shiftPaginate}
                              onScrollNearBottom={
                                threadPaginator.prependPaginate
                              }
                              onReady={onThreadListReady}
                              onScroll={onThreadListScroll}
                              onUserNavigation={cancelLatestNavigation}
                              initialPosition={
                                targetMessageController.activeTargetMessageId()
                                  ? {
                                      type: 'element',
                                      id: targetMessageController.activeTargetMessageId()!,
                                    }
                                  : props.initialMessagesStateSnapshot?.scroll
                                    ? {
                                        type: 'restore',
                                        snapshot:
                                          props.initialMessagesStateSnapshot
                                            .scroll,
                                      }
                                    : { type: 'latest' }
                              }
                            >
                              {(item) => {
                                const isNewestRow = () =>
                                  item.id === rowKeys().at(-1);
                                const callStatus = () =>
                                  messageIndex.callStatusByKey.get(item.id);
                                const isCallRow = () => !!callStatus();
                                const isPanelRoot = () =>
                                  item.id === callPanel?.rootId;
                                const activity = () =>
                                  messageIndex.activityByKey.get(item.id);
                                const message = () =>
                                  messageById().get(item.id);

                                return (
                                  <Switch>
                                    <Match when={activity()}>
                                      {(activity) => (
                                        <ThreadRow
                                          channelId={props.channelId}
                                          message={{
                                            created_at: activity().occurred_at,
                                          }}
                                          listMeta={listMetaByKey()[item.id]}
                                        >
                                          <SystemActivity
                                            channelId={props.channelId}
                                            event={decodeSystemActivityRow(
                                              messageIndex.activityGroupByKey.get(
                                                item.id
                                              ) ?? [activity()]
                                            )}
                                          />
                                          <Show when={isNewestRow()}>
                                            <ThreadTypingIndicator
                                              parent={{
                                                type: 'channel',
                                                id: props.channelId,
                                              }}
                                              threadId={null}
                                            />
                                          </Show>
                                        </ThreadRow>
                                      )}
                                    </Match>
                                    <Match when={message()}>
                                      {(m) => {
                                        const state =
                                          threadManager.getOrCreateThreadState(
                                            item.id
                                          );
                                        return (
                                          <div
                                            class={
                                              isPanelRoot()
                                                ? 'relative min-h-[100cqh]'
                                                : 'contents'
                                            }
                                          >
                                            <ChannelThread
                                              rootSlot={
                                                isCallRow()
                                                  ? () => (
                                                      <Show when={callStatus()}>
                                                        {(status) => (
                                                          <CallRootLine
                                                            channelId={
                                                              props.channelId
                                                            }
                                                            message={m()}
                                                            status={status()}
                                                            inCallPanel={isPanelRoot()}
                                                            onVisibilityChange={
                                                              setLiveCallRowVisible
                                                            }
                                                          />
                                                        )}
                                                      </Show>
                                                    )
                                                  : undefined
                                              }
                                              hideCollapsedPreview={isCallRow()}
                                              beforeMessage={
                                                <AgentConversationContextBoundary
                                                  messageId={item.id}
                                                />
                                              }
                                              afterMessage={
                                                <AgentConversationMessageStatus
                                                  messageId={item.id}
                                                />
                                              }
                                              hideTriggeredBy={
                                                !!channel()?.agent_dm
                                              }
                                              data={m}
                                              parent={() => ({
                                                type: 'channel',
                                                id: (() => props.channelId)(),
                                              })}
                                              isNewestThread={isNewestRow()}
                                              getMessageActions={
                                                getMessageActions
                                              }
                                              isFindBarOpen={findBar.isOpen}
                                              targetNavigation={{
                                                targetThreadId:
                                                  targetMessageController.activeTargetMessageId,
                                                targetMessageId: () =>
                                                  !targetMessageController.pendingTargetReplyId()
                                                    ? targetMessageController.pendingScrollTargetId()
                                                    : undefined,
                                                targetReplyId: () =>
                                                  targetMessageController.pendingScrollTargetId()
                                                    ? undefined
                                                    : targetMessageController.pendingTargetReplyId(),
                                                activeTargetReplyId:
                                                  targetMessageController.activeTargetMessageReplyId,
                                                positionTarget: (
                                                  _,
                                                  targetElement
                                                ) =>
                                                  threadListNavigation()?.scrollToElement(
                                                    targetElement
                                                  ) ?? false,
                                                onTargetMessageScrolled:
                                                  targetMessageController.completePendingScroll,
                                                onTargetReplyScrolled: (
                                                  replyId
                                                ) => {
                                                  targetMessageController.completePendingReplyScroll(
                                                    item.id,
                                                    replyId
                                                  );
                                                },
                                                onClearTarget:
                                                  releaseSelectionAndTarget,
                                              }}
                                              inputMode={
                                                usesUnifiedInput()
                                                  ? 'unified'
                                                  : 'inline'
                                              }
                                              unifiedReplyTarget={unifiedInput.replyTarget()}
                                              onMessageMount={
                                                unread.onMessageMount
                                              }
                                              onDisclosureMount={
                                                unread.onDisclosureMount
                                              }
                                              unreadMessageIds={unread
                                                .unreadByThread()
                                                .get(item.id)}
                                              isExpanded={state.isExpanded}
                                              setIsExpanded={
                                                state.setIsExpanded
                                              }
                                              isReplying={state.isReplying}
                                              setIsReplying={
                                                state.setIsReplying
                                              }
                                              replyInputState={
                                                state.replyInputState
                                              }
                                              setReplyInputState={
                                                state.setReplyInputState
                                              }
                                              setReplyInputEl={
                                                state.setReplyInputEl
                                              }
                                              replyInputHandle={
                                                state.replyInputHandle
                                              }
                                              setReplyInputHandle={
                                                state.setReplyInputHandle
                                              }
                                              replyInputFocusRequest={
                                                state.replyInputFocusRequest
                                              }
                                              listMeta={
                                                listMetaByKey()[item.id]
                                              }
                                              messageEditor={messageEditor}
                                              threadActions={{
                                                onDismissNewMessages:
                                                  activityTracker.dismissNewMessages,
                                              }}
                                              isNewMessage={
                                                activityTracker.isNewMessage
                                              }
                                              selectedMessageId={
                                                selection.selectedId
                                              }
                                              onSelectMessage={selectMessage}
                                              onClearSelection={clearSelection}
                                              messageListScopeId={
                                                messageListScopeId
                                              }
                                            />
                                            <Show
                                              when={
                                                isPanelRoot() &&
                                                m().thread.reply_count === 0
                                              }
                                            >
                                              <p class="pointer-events-none absolute inset-0 flex items-center justify-center px-6 text-center text-sm text-ink-muted">
                                                {t('calls.callThreadEmpty', {
                                                  channel:
                                                    channel()?.name ??
                                                    t('calls.thisChannel'),
                                                })}
                                              </p>
                                            </Show>
                                          </div>
                                        );
                                      }}
                                    </Match>
                                  </Switch>
                                );
                              }}
                            </ThreadList>
                          </SwipableRowProvider>

                          <Show when={callPanel}>
                            <Show
                              when={
                                threadListScrollState() &&
                                !threadListScrollState()?.isNearBottom
                              }
                            >
                              <button
                                type="button"
                                class="absolute top-2 left-1/2 z-10 -translate-x-1/2 rounded-full border border-edge-muted bg-surface px-3 py-1.5 text-xs shadow-lg not-touch:hover:overlay-hover not-touch:active:overlay-active"
                                onClick={() => goToLatest()}
                              >
                                {t('calls.backToCallThread')}
                              </button>
                            </Show>
                            <Show when={outside().length > 0}>
                              <OutsideMessagesPopup
                                messages={outside()}
                                onView={viewChannelFromPanel}
                              />
                            </Show>
                          </Show>
                          <Show when={!callPanel && !findBar.isOpen()}>
                            <Show when={unread.chip()}>
                              {(chip) => (
                                <UnreadNotificationsOverlay
                                  direction={chip().direction}
                                  count={chip().count}
                                  onClick={() => goToUnread(chip().thread)}
                                  bottomInset={threadListScrollInsets().end}
                                />
                              )}
                            </Show>
                            <Show when={unread.chip()?.direction !== 'above'}>
                              <ScrollToBottomOverlay
                                scrollState={threadListScrollState}
                                onScrollToBottom={goToLatest}
                              />
                            </Show>
                          </Show>
                        </MessageNotificationIndexContext.Provider>
                      </div>
                    </Show>
                    <Show when={!callPanel}>
                      <DebugSuspense name="Channel.active-call">
                        <ActiveCallMessage
                          channelId={props.channelId}
                          hidden={liveCallRowVisible()}
                          messageCount={(callId) =>
                            messageIndex.callStatusByKey.has(callId)
                              ? messageById().get(callId)?.thread.reply_count
                              : undefined
                          }
                          onOpenRow={(callId) => goToMessage(callId)}
                        />
                      </DebugSuspense>
                    </Show>
                  </div>
                  <DebugSuspense name="Channel.input">
                    <Dynamic
                      component={
                        callPanel ? InPlaceRegion : FloatRegionOrInline
                      }
                      region="accessory"
                    >
                      <ChannelInputContainer
                        ref={(el) => {
                          attachInputRef(el);
                          composerTarget(el);
                        }}
                      >
                        <Switch>
                          <Match
                            when={
                              usesUnifiedInput() &&
                              messageEditor.state()?.messageId
                            }
                            keyed
                          >
                            {(_messageId) => (
                              <UnifiedEditInput
                                channelId={props.channelId}
                                messageEditor={messageEditor}
                                onNavigateToMessage={(message) =>
                                  goToMessage(
                                    message.thread_id ?? message.id,
                                    message.thread_id ? message.id : undefined
                                  )
                                }
                              />
                            )}
                          </Match>
                          <Match
                            when={
                              usesUnifiedInput() &&
                              unifiedInput.replyTarget()?.threadId
                            }
                            keyed
                          >
                            {(threadId) => (
                              <UnifiedReplyInput
                                channelId={props.channelId}
                                threadId={threadId}
                                state={threadManager.getOrCreateThreadState(
                                  threadId
                                )}
                                getTargetMessage={() => {
                                  const target = unifiedInput.replyTarget();
                                  if (target?.message) return target.message;
                                  // A restored referenced reply has no resolvable
                                  // message (messageById only indexes thread
                                  // roots) — don't misattribute it to the root.
                                  if (target?.replyId) return undefined;
                                  return messageById().get(threadId);
                                }}
                                threadHasReplies={() =>
                                  (messageById().get(threadId)?.thread
                                    .reply_count ?? 0) > 0
                                }
                                pinnedLabel={
                                  threadId === callPanel?.rootId
                                    ? () => t('calls.replyingInCallThread')
                                    : undefined
                                }
                                onNavigateToTarget={() =>
                                  goToMessage(
                                    threadId,
                                    unifiedInput.replyTarget()?.replyId
                                  )
                                }
                                onExit={unifiedInput.closeReply}
                              />
                            )}
                          </Match>
                          <Match when={true}>
                            {/* An agent DM gates only a new message on its
                                agent: editing and thread replies stay open. */}
                            <AgentDmComposer
                              channelId={props.channelId}
                              botId={channel()?.agent_dm?.bot_id}
                            >
                              <ChannelInput
                                autofocus={props.autofocus}
                                collapsible
                                input={{
                                  mode: 'channel',
                                  id: `channel-input-${props.channelId}`,
                                  placeholder: inputPlaceholder(),
                                }}
                                participants={participants.users}
                                bots={channelBotMentionUsers}
                                attachmentTracker={attachmentTracker}
                                persistenceKey={makeInputValuePersistenceKey({
                                  channelId: props.channelId,
                                })}
                                onReady={(handle) => {
                                  dragState.setAttachFilesToChannel(
                                    handle.attachFiles
                                  );
                                  dragState.setEntityMentionInputHandlers(
                                    handle
                                  );
                                  setChannelInputHandle(handle);
                                }}
                                onChange={(snapshot) => {
                                  setChannelInputSnapshot(snapshot);
                                }}
                                onSend={onSend}
                                onStartCall={
                                  ENABLE_CALLS && !channelCall.isInThisChannel()
                                    ? () =>
                                        fireAndForget(
                                          channelCall.start(),
                                          'channel-call'
                                        )
                                    : undefined
                                }
                                callInProgress={channelCall.isCallInProgress()}
                                onStartTyping={() =>
                                  typingMutation.mutate({
                                    parent: {
                                      type: 'channel',
                                      id: props.channelId,
                                    },
                                    action: 'start',
                                  })
                                }
                                onStopTyping={() =>
                                  typingMutation.mutate({
                                    parent: {
                                      type: 'channel',
                                      id: props.channelId,
                                    },
                                    action: 'stop',
                                  })
                                }
                              />
                            </AgentDmComposer>
                          </Match>
                        </Switch>
                      </ChannelInputContainer>
                    </Dynamic>
                  </DebugSuspense>
                </ChannelDropZone>
              </MaybeMessageActionDrawerManager>
            </SearchHighlightTermsProvider>
          </StaticMarkdownContext>
        </DebugSuspense>
      </EntityLoadGate>
    </AgentConversationsProvider>
  );
}