Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

7.6 KB
Raw Blame
import { type ThreadItem, ThreadType, type UIChatMessage } from '@lobechat/types';

import { useAgentStore } from '@/store/agent';
import { agentChatConfigSelectors } from '@/store/agent/selectors';
import { type ChatStoreState } from '@/store/chat';
import { chatHelpers } from '@/store/chat/helpers';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';

import { genParentMessages } from './util';

// ============= Thread List Selectors ============= //

const currentTopicThreads = (s: ChatStoreState) => {
  if (!s.activeTopicId) return [];

  return s.threadMaps[s.activeTopicId] || [];
};

/**
 * Whether the active topic's thread list has a value to render β€” hydrated from
 * the local copy or fetched. With no active topic there is nothing to wait for.
 */
const isCurrentTopicThreadsLoaded = (s: ChatStoreState): boolean =>
  !s.activeTopicId || s.threadMaps[s.activeTopicId] !== undefined;

/**
 * The Portal's thread is missing from a list that was only restored from the
 * local copy. The snapshot may predate the thread, so this is still loading β€”
 * not "no such thread" β€” until the server answers.
 */
const isPortalThreadPending = (s: ChatStoreState): boolean => {
  const topicId = s.activeTopicId;
  if (!topicId || !s.portalThreadId) return false;

  const threads = s.threadMaps[topicId];
  if (threads === undefined) return true;
  if (threads.some((thread) => thread.id === s.portalThreadId)) return false;

  return s.threadListReplica?.entries[topicId]?.source === 'storage';
};

const currentPortalThread = (s: ChatStoreState): ThreadItem | undefined => {
  if (!s.portalThreadId) return undefined;

  const threads = currentTopicThreads(s);

  return threads.find((t) => t.id === s.portalThreadId);
};

const currentActiveThread = (s: ChatStoreState): ThreadItem | undefined => {
  if (!s.activeThreadId) return undefined;

  const threads = currentTopicThreads(s);

  return threads.find((t) => t.id === s.activeThreadId);
};

const isActiveThreadSubagent = (s: ChatStoreState): boolean => {
  const thread = currentActiveThread(s);
  // Only tool-spawned subagent threads are externally owned and read-only.
  // Direct @Agent isolation threads are ordinary target-Agent conversations
  // after the delegated run completes, so users can continue chatting there.
  return !!thread?.metadata?.sourceToolCallId;
};

const getThreadsByTopic = (topicId?: string) => (s: ChatStoreState) => {
  if (!topicId) return;

  return s.threadMaps[topicId];
};

const getThreadsBySourceMsgId = (id: string) => (s: ChatStoreState) => {
  const threads = currentTopicThreads(s);

  return threads.filter((t) => t.sourceMessageId === id);
};

const getIsolationThreadBySourceMsgId = (id: string) => (s: ChatStoreState) => {
  const threads = currentTopicThreads(s);

  return threads.find(
    (thread) => thread.sourceMessageId === id && thread.type === ThreadType.Isolation,
  );
};

const hasThreadBySourceMsgId = (id: string) => (s: ChatStoreState) => {
  const threads = currentTopicThreads(s);

  return threads.some((t) => t.sourceMessageId === id);
};

// ============= Thread Messages Selectors ============= //
// These are kept for Token calculation and AI title summarization
// Thread Chat component now uses dbMessagesMap directly

/**
 * Get main scope messages (without activeThreadId influence).
 * Always uses main scope key so that thread selectors work correctly
 * even when activeThreadId is set (i.e., viewing inside a subtopic).
 */
const getMainScopeMessages = (s: ChatStoreState): UIChatMessage[] => {
  if (!s.activeAgentId) return [];
  const mainKey = messageMapKey({
    agentId: s.activeAgentId,
    groupId: s.activeGroupId,
    topicId: s.activeTopicId,
  });
  return s.messagesMap[mainKey] || [];
};

/**
 * Raw main-scope rows, the same key as `getMainScopeMessages` but before conversation-flow
 * grouped them for display.
 */
const getMainScopeDbMessages = (s: ChatStoreState): UIChatMessage[] => {
  if (!s.activeAgentId) return [];
  const mainKey = messageMapKey({
    agentId: s.activeAgentId,
    groupId: s.activeGroupId,
    topicId: s.activeTopicId,
  });
  return (s.dbMessagesMap?.[mainKey] || []) as UIChatMessage[];
};

/**
 * Internal helper to get parent messages for a thread
 */
const getThreadParentMessages = (s: ChatStoreState, data: UIChatMessage[]) => {
  if (s.startToForkThread) {
    const startMessageId = s.threadStartMessageId!;

    // Filter out messages that belong to other threads
    const messages = data.filter((m) => !m.threadId);
    return genParentMessages(messages, startMessageId, s.newThreadMode);
  }

  const portalThread = currentPortalThread(s);
  return genParentMessages(data, portalThread?.sourceMessageId, portalThread?.type);
};

/**
 * Get thread child messages by thread ID
 *
 * Reads the raw main-scope rows rather than `messagesMap`: the rendered shape is the main
 * transcript, which deliberately leaves threads out, so a thread's replies only exist here
 * in `dbMessagesMap`.
 */
const getThreadChildMessages =
  (id?: string) =>
  (s: ChatStoreState): UIChatMessage[] => {
    const data = getMainScopeDbMessages(s);
    return data.filter((m) => !!id && m.threadId === id);
  };

/**
 * Raw DB-level child messages for a thread, keyed by `messageMapKey` thread scope.
 *
 * Use this for *counting* / *aggregating* over individual messages (e.g. the
 * subagent inspector chip's tool count + token total). Do NOT use it for
 * rendering β€” the display layer reads from `messagesMap` (which groups tools
 * into a virtual `assistantGroup`), so the shapes intentionally differ.
 *
 * Why `dbMessagesMap` not `messagesMap`: `messagesMap[thread_*]` only holds
 * the rendered shape ([user, assistantGroup]); individual `role==='tool'` /
 * `role==='assistant'` rows live in `dbMessagesMap[thread_*]`.
 */
const getThreadDbMessages =
  (id?: string) =>
  (s: ChatStoreState): UIChatMessage[] => {
    if (!id || !s.activeAgentId) return [];
    const key = messageMapKey({
      agentId: s.activeAgentId,
      groupId: s.activeGroupId,
      threadId: id,
      topicId: s.activeTopicId,
    });
    return (s.dbMessagesMap?.[key] || []) as UIChatMessage[];
  };

/**
 * Portal AI chats - used for AI title summarization
 */
const portalAIChats = (s: ChatStoreState) => {
  const data = getMainScopeMessages(s);
  const parentMessages = getThreadParentMessages(s, data);
  const childMessages = getThreadChildMessages(s.portalThreadId)(s);

  return [...parentMessages, ...childMessages].filter(Boolean) as UIChatMessage[];
};

/**
 * Portal AI chats with history config - used for workflow
 */
const portalAIChatsWithHistoryConfig = (s: ChatStoreState) => {
  const messages = portalAIChats(s);

  const enableHistoryCount = agentChatConfigSelectors.enableHistoryCount(useAgentStore.getState());
  const historyCount = agentChatConfigSelectors.historyCount(useAgentStore.getState());

  return chatHelpers.getSlicedMessages(messages, {
    enableHistoryCount,
    historyCount,
  });
};

/**
 * Portal display chats string - used for Token calculation
 */
const portalDisplayChatsString = (s: ChatStoreState) => {
  const messages = portalAIChats(s);
  return messages.map((m) => m.content).join('');
};

export const threadSelectors = {
  currentActiveThread,
  currentPortalThread,
  currentTopicThreads,
  getThreadChildMessages,
  getThreadDbMessages,
  getIsolationThreadBySourceMsgId,
  getThreadsBySourceMsgId,
  getThreadsByTopic,
  hasThreadBySourceMsgId,
  isActiveThreadSubagent,
  isCurrentTopicThreadsLoaded,
  isPortalThreadPending,
  portalAIChats,
  portalAIChatsWithHistoryConfig,
  portalDisplayChatsString,
};

// Re-export utility function for use in action.ts
export { genParentMessages } from './util';