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.

2.4 KB
Raw Blame
import { messageMapKey } from '@/store/chat/utils/messageMapKey';

import { type ChatStoreState } from '../../initialState';
import { operationSelectors } from '../operation/selectors';

const isMessageInReasoning = (id: string) => (s: ChatStoreState) =>
  operationSelectors.isMessageInReasoning(id)(s);

const isMessageInSearchWorkflow = (id: string) => (s: ChatStoreState) =>
  s.searchWorkflowLoadingIds.includes(id);

const isIntentUnderstanding = (id: string) => (s: ChatStoreState) =>
  isMessageInSearchWorkflow(id)(s);

const isCurrentSendMessageLoading = (s: ChatStoreState) => {
  const contextKey = messageMapKey({
    agentId: s.activeAgentId,
    groupId: s.activeGroupId,
    threadId: s.activeThreadId,
    topicId: s.activeTopicId,
  });
  const operationIds = s.operationsByContext[contextKey] || [];

  // Check if there's any running sendMessage operation
  return operationIds.some((opId) => {
    const op = s.operations[opId];
    return op && op.type === 'sendMessage' && op.status === 'running';
  });
};

const isCurrentSendMessageError = (s: ChatStoreState) => {
  const contextKey = messageMapKey({
    agentId: s.activeAgentId,
    groupId: s.activeGroupId,
    threadId: s.activeThreadId,
    topicId: s.activeTopicId,
  });
  const operationIds = s.operationsByContext[contextKey] || [];

  // Find the latest sendMessage operation with error
  for (const opId of [...operationIds].reverse()) {
    const op = s.operations[opId];
    if (op && op.type === 'sendMessage' && op.metadata.inputSendErrorMsg) {
      return op.metadata.inputSendErrorMsg;
    }
  }

  return undefined;
};

const isSendMessageLoadingForTopic = (topicKey: string) => (s: ChatStoreState) => {
  const operationIds = s.operationsByContext[topicKey] || [];

  // Check if there's any running sendMessage operation for this topic
  return operationIds.some((opId) => {
    const op = s.operations[opId];
    return op && op.type === 'sendMessage' && op.status === 'running';
  });
};

const gatewayFeed = (s: ChatStoreState) => s.gatewayFeed;

const gatewayFeedEntry = (operationId: string) => (s: ChatStoreState) => s.gatewayFeed[operationId];

export const gatewayFeedSelectors = {
  gatewayFeed,
  gatewayFeedEntry,
};

export const agentRunSelectors = {
  isCurrentSendMessageError,
  isCurrentSendMessageLoading,
  isIntentUnderstanding,
  isMessageInReasoning,
  isMessageInSearchWorkflow,
  isSendMessageLoadingForTopic,
};