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.

1.8 KB
Raw Blame
import type { TopicQuerySortBy } from '@lobechat/types';

import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';

/**
 * Fetch topics for the current session (agent or group)
 */
export const useFetchTopics = (
  options?: {
    excludeStatuses?: string[];
    excludeTriggers?: string[];
    onlyMine?: boolean;
    sortBy?: TopicQuerySortBy;
  },
  enabled = true,
) => {
  const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
  const [activeAgentId, activeGroupId, useFetchTopicsHook] = useChatStore((s) => [
    s.activeAgentId,
    s.activeGroupId,
    s.useFetchTopics,
  ]);

  const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);

  // If in group session, use groupId; otherwise use agentId
  const hasTopicData = useChatStore(
    (s) => !!s.topicDataMap[topicMapKey({ agentId: activeAgentId, groupId: activeGroupId })],
  );
  const { isValidating } = useFetchTopicsHook(enabled, {
    agentId: activeAgentId,
    ...(options?.excludeStatuses && options.excludeStatuses.length > 0
      ? { excludeStatuses: options.excludeStatuses }
      : {}),
    ...(options?.excludeTriggers && options.excludeTriggers.length > 0
      ? { excludeTriggers: options.excludeTriggers }
      : {}),
    groupId: activeGroupId,
    isInbox: activeGroupId ? false : isInbox,
    ...(options?.onlyMine ? { onlyMine: true } : {}),
    pageSize: topicPageSize,
    ...(options?.sortBy ? { sortBy: options.sortBy } : {}),
  });

  return {
    // isRevalidating: the store already shows topics, updating in background
    isRevalidating: isValidating && hasTopicData,
  };
};