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.

18.2 KB
Raw Blame
import { normalizeHeterogeneousMessageError } from '@lobechat/heterogeneous-agents/errors';
import { normalizeChatMessageError } from '@lobechat/model-runtime/errors';
import {
  type ChatMessageError,
  type ChatMessagePluginError,
  type ChatTranslate,
  type CreateMessageParams,
  type CreateMessageResult,
  type HeterogeneousToolStateSnapshot,
  type MessageMetadata,
  type MessagePluginItem,
  type ModelRankItem,
  type TopicMessageSearchMatch,
  type UIChatMessage,
  type UpdateMessageParams,
  type UpdateMessageRAGParams,
  type UpdateMessageResult,
} from '@lobechat/types';
import { type HeatmapsProps } from '@lobehub/charts';
import pMap from 'p-map';

import { lambdaClient } from '@/libs/trpc/client';
import { workTypeOptIn } from '@/services/workTypeOptIn';

import { abortableRequest } from '../utils/abortableRequest';
import type { MessageListPage, MessageRoundCursor } from './cache';
import { supportsRoundCursor } from './cache';
import { readMessagesByRoundCursor, takePrimedMessageListPage } from './roundCursorPage';

/**
 * Query context for message operations
 * Contains identifiers needed for querying/filtering messages after mutations
 */
export interface MessageQueryContext {
  agentId?: string;
  groupId?: string;
  threadId?: string | null;
  topicId?: string | null;
  topicShareId?: string;
}

export interface MessageReadQueryContext {
  agentId?: string | null;
  /** Agent-share visitor surface — routes the read through `shareChat.getMessages`. */
  agentShareId?: string;
  groupId?: string | null;
  /**
   * Ask the server for render-facing tool view models instead of the stored
   * payloads. Only set it for a read whose result is never turned into an LLM
   * context in the browser — see `readConversationMessages`.
   */
  projectToolPayloads?: boolean;
  /**
   * Skip the Work-summary assembly on the server — set by mid-stream
   * refetches (tool_end / step_complete) so each tool round doesn't re-run
   * the per-type Work queries. See `QueryMessageParams.skipWorks`.
   */
  skipWorks?: boolean;
  threadId?: string | null;
  topicId?: string | null;
  topicShareId?: string;
}

export type MessageBatchOperation =
  | {
      message: CreateMessageParams;
      type: 'createMessage';
    }
  | {
      id: string;
      type: 'updateMessage';
      value: Partial<UpdateMessageParams>;
    }
  | {
      id: string;
      type: 'updateToolMessage';
      value: {
        content?: string;
        heterogeneousToolState?: HeterogeneousToolStateSnapshot;
        metadata?: Record<string, any>;
        pluginError?: any;
        pluginState?: Record<string, any>;
      };
    };

export interface MessageBatchMutationResult {
  results?: Array<{
    error?: string;
    id?: string;
    index: number;
    success: boolean;
    type: MessageBatchOperation['type'];
  }>;
  success?: boolean;
}

export class MessageBatchMutationError extends Error {
  constructor(public readonly result: MessageBatchMutationResult) {
    const failed = result.results?.filter((item) => !item.success) ?? [];
    const reasons = [...new Set(failed.map((item) => item.error).filter(Boolean))];
    super(
      `Message batch mutation failed for ${failed.length || 'unknown'} operation(s)` +
        (reasons.length > 0 ? `: ${reasons.join('; ')}` : ''),
    );
  }
}

const getBatchMutationAbortKey = (operations: MessageBatchOperation[]) => {
  if (operations.length !== 1) return;

  const [operation] = operations;
  if (operation.type === 'updateToolMessage') return `tool-message-${operation.id}`;
};

/** Matches the `getToolResultPayloads` input cap in the lambda router. */
const TOOL_PAYLOAD_BATCH_SIZE = 500;

export class MessageService {
  batchMutate = async (operations: MessageBatchOperation[], signal?: AbortSignal) => {
    const input = {
      operations: operations.map((operation) => {
        if (operation.type === 'createMessage') {
          return {
            message: operation.message,
            type: operation.type,
          };
        }

        return {
          id: operation.id,
          type: operation.type,
          value: operation.value,
        };
      }),
    } as any;

    return signal
      ? lambdaClient.message.batchMutate.mutate(input, { signal })
      : lambdaClient.message.batchMutate.mutate(input);
  };

  batchMutateOrThrow = async (operations: MessageBatchOperation[]) => {
    const execute = async (signal?: AbortSignal) => {
      const result = (await (signal
        ? this.batchMutate(operations, signal)
        : this.batchMutate(operations))) as MessageBatchMutationResult;
      const hasFailedOperation = result.results?.some((item) => !item.success) ?? false;
      const hasCompleteResults = result.results?.length === operations.length;

      if (result.success !== true || !hasCompleteResults || hasFailedOperation) {
        throw new MessageBatchMutationError(result);
      }

      return result;
    };

    const abortKey = getBatchMutationAbortKey(operations);

    return abortKey ? abortableRequest.execute(abortKey, execute) : execute();
  };

  createMessage = async (params: CreateMessageParams): Promise<CreateMessageResult> => {
    return lambdaClient.message.createMessage.mutate(params as any);
  };

  getMessages = async (params: MessageReadQueryContext): Promise<UIChatMessage[]> => {
    // Agent-share visitor surface: the owner-scoped query below resolves rows in
    // the CALLER's scope, so it would come back empty for a visitor (share rows
    // belong to the creator). Route through the share-authorized read instead.
    // A share context without a topic is the visitor's new-topic bucket —
    // nothing to fetch.
    if (params.agentShareId) {
      if (!params.topicId) return [];

      const shared = await lambdaClient.shareChat.getMessages.query({
        includeFileWorks: true,
        shareId: params.agentShareId,
        topicId: params.topicId,
      });

      return shared as unknown as UIChatMessage[];
    }

    // Opt into `file` (and any future gated) work summaries in the message
    // payload. This client ships the descriptor fallback; clients that predate
    // the `file` type run the old service without the flag and stay on the
    // legacy set. See resolveAllowedWorkTypes.
    const data = await lambdaClient.message.getMessages.query({
      ...params,
      ...workTypeOptIn(),
    });

    return data as unknown as UIChatMessage[];
  };

  /**
   * Stored tool payload for a message whose projected copy dropped it
   * (`UIChatMessage.payloadOmitted`). Called by detail surfaces on open, never
   * as part of loading a conversation.
   */
  getToolResultPayload = async (messageId: string) => {
    return lambdaClient.message.getToolResultPayload.query({ messageId });
  };

  /** Status per pending card id (`null` when gone) plus a revision of the topic, for the approval poll. */
  getInterventionSnapshot = async (topicId: string, messageIds: string[]) =>
    lambdaClient.message.getInterventionSnapshot.query({ messageIds, topicId });

  /**
   * Bulk form, for surfaces that need every omitted row at once (export).
   *
   * Chunked to the endpoint's own cap: a tool-dense topic can hold more
   * projected rows than one request accepts, and the schema would reject the
   * whole set rather than return what it could.
   */
  getToolResultPayloads = async (messageIds: string[]) => {
    const chunks: string[][] = [];
    for (let i = 0; i < messageIds.length; i += TOOL_PAYLOAD_BATCH_SIZE) {
      chunks.push(messageIds.slice(i, i + TOOL_PAYLOAD_BATCH_SIZE));
    }

    const results = await pMap(
      chunks,
      (ids) => lambdaClient.message.getToolResultPayloads.query({ messageIds: ids }),
      { concurrency: 3 },
    );

    return Object.assign({}, ...results) as Record<
      string,
      { content: string; pluginState?: unknown }
    >;
  };

  /**
   * The newest window of a conversation for the message-list cache. Topic
   * conversations read it by round cursor so the page also says whether any
   * older history exists (`olderCursor: null` → the topic start is loaded, and
   * scrolling up must not fetch). Other contexts return the plain list, whose
   * older history is unknown.
   */
  getMessageListPage = async (
    params: MessageReadQueryContext,
  ): Promise<MessageListPage | UIChatMessage[]> => {
    if (!supportsRoundCursor(params)) return this.getMessages(params);

    // A page primed for this conversation (see `primeMessageListPage`) answers
    // its first read; if that request failed, read again rather than fail.
    const primed = takePrimedMessageListPage(params);
    if (primed) return primed.catch(() => readMessagesByRoundCursor(params, null));

    return readMessagesByRoundCursor(params, null);
  };

  /**
   * Load one round-aligned page of history strictly OLDER than `cursor` (the
   * start of the oldest loaded round). Intentionally outside the
   * `runMessageListQuery` client-cache policy: older pages are additive and
   * merged by the earlier-history layer in `services/message/cache`.
   */
  getEarlierMessages = async (
    params: MessageReadQueryContext,
    cursor: MessageRoundCursor,
  ): Promise<MessageListPage> => {
    // Agent-share pages read through `shareChat.getMessages`, which has no
    // round cursor: report the start as reached so the shared view keeps its
    // current window instead of hitting the authed endpoint.
    if (params.agentShareId) return { messages: [], olderCursor: null };

    if (supportsRoundCursor(params)) return readMessagesByRoundCursor(params, cursor);

    const data = await lambdaClient.message.getMessages.query({
      ...params,
      before: { createdAt: new Date(cursor.createdAt), id: cursor.id },
      ...workTypeOptIn(),
    });

    return { messages: data as unknown as UIChatMessage[] };
  };

  searchInTopic = async (params: {
    keyword: string;
    topicId: string;
  }): Promise<TopicMessageSearchMatch[]> => {
    return lambdaClient.message.searchInTopic.query(params);
  };

  diagnoseTopic = async (params: { agentId?: string | null; topicId: string }) => {
    return lambdaClient.message.diagnoseTopic.query(params);
  };

  repairTopic = async (params: { agentId?: string | null; topicId: string }) => {
    return lambdaClient.message.repairTopic.mutate(params);
  };

  countMessages = async (params?: {
    approximate?: boolean;
    endDate?: string;
    range?: [string, string];
    startDate?: string;
  }): Promise<number> => {
    return lambdaClient.message.count.query(params);
  };

  countWords = async (params?: {
    endDate?: string;
    range?: [string, string];
    startDate?: string;
  }): Promise<number> => {
    return lambdaClient.message.countWords.query(params);
  };

  rankModels = async (): Promise<ModelRankItem[]> => {
    return lambdaClient.message.rankModels.query();
  };

  getHeatmaps = async (): Promise<HeatmapsProps['data']> => {
    return lambdaClient.message.getHeatmaps.query();
  };

  getTokenHeatmaps = async (): Promise<HeatmapsProps['data']> => {
    return lambdaClient.message.getTokenHeatmaps.query();
  };

  updateMessageError = async (id: string, value: ChatMessageError, ctx?: MessageQueryContext) => {
    const error = normalizeHeterogeneousMessageError(normalizeChatMessageError(value));

    return lambdaClient.message.update.mutate({
      ...ctx,
      id,
      value: { error },
    });
  };

  updateMessagePluginArguments = async (id: string, value: string | Record<string, any>) => {
    const args = typeof value === 'string' ? value : JSON.stringify(value);
    return lambdaClient.message.updateMessagePlugin.mutate({ id, value: { arguments: args } });
  };

  /**
   * Update tool arguments by toolCallId - updates both tool message and parent assistant message in one transaction
   * This is the preferred method for updating tool arguments as it prevents race conditions
   *
   * @param toolCallId - The tool call ID (stable identifier from AI response)
   * @param value - The new arguments value
   * @param ctx - Message query context
   */
  updateToolArguments = async (
    toolCallId: string,
    value: string | Record<string, unknown>,
    ctx?: MessageQueryContext,
  ) => {
    return lambdaClient.message.updateToolArguments.mutate({ ...ctx, toolCallId, value });
  };

  updateMessage = async (
    id: string,
    value: Partial<UpdateMessageParams>,
    ctx?: MessageQueryContext,
  ): Promise<UpdateMessageResult> => {
    return lambdaClient.message.update.mutate({
      ...ctx,
      id,
      value,
    });
  };

  updateMessageTranslate = async (id: string, translate: Partial<ChatTranslate> | false) => {
    return lambdaClient.message.updateTranslate.mutate({ id, value: translate as ChatTranslate });
  };

  updateMessageMetadata = async (
    id: string,
    value: Partial<MessageMetadata>,
    ctx?: MessageQueryContext,
  ): Promise<UpdateMessageResult> => {
    return abortableRequest.execute(`message-metadata-${id}`, (signal) =>
      lambdaClient.message.updateMetadata.mutate({ ...ctx, id, value }, { signal }),
    );
  };

  updateMessagePluginState = async (
    id: string,
    value: Record<string, any>,
    ctx?: MessageQueryContext,
  ): Promise<UpdateMessageResult> => {
    return lambdaClient.message.updatePluginState.mutate({ ...ctx, id, value });
  };

  updateMessagePluginError = async (
    id: string,
    error: ChatMessagePluginError | null,
    ctx?: MessageQueryContext,
  ): Promise<UpdateMessageResult> => {
    return lambdaClient.message.updatePluginError.mutate({ ...ctx, id, value: error as any });
  };

  updateMessagePlugin = async (
    id: string,
    value: Partial<Omit<MessagePluginItem, 'id'>>,
    ctx?: MessageQueryContext,
  ): Promise<UpdateMessageResult> => {
    return lambdaClient.message.updateMessagePlugin.mutate({ ...ctx, id, value });
  };

  updateMessageRAG = async (
    id: string,
    data: UpdateMessageRAGParams,
    ctx?: MessageQueryContext,
  ): Promise<UpdateMessageResult> => {
    return lambdaClient.message.updateMessageRAG.mutate({ ...ctx, id, value: data });
  };

  /**
   * Update tool message with content, metadata, pluginState, and pluginError in a single request
   * This prevents race conditions when updating multiple fields
   * Uses abortableRequest to cancel previous requests for the same message
   */
  updateToolMessage = async (
    id: string,
    value: {
      content?: string;
      heterogeneousToolState?: HeterogeneousToolStateSnapshot;
      metadata?: Record<string, any>;
      pluginError?: any;
      pluginState?: Record<string, any>;
    },
    ctx?: MessageQueryContext,
  ): Promise<UpdateMessageResult> => {
    return abortableRequest.execute(`tool-message-${id}`, (signal) =>
      lambdaClient.message.updateToolMessage.mutate({ ...ctx, id, value }, { signal }),
    );
  };

  removeMessage = async (id: string, ctx?: MessageQueryContext): Promise<UpdateMessageResult> => {
    return lambdaClient.message.removeMessage.mutate({ ...ctx, id });
  };

  /**
   * Moves the messages to the recycle bin. `permanent` hard-deletes instead —
   * only for internal cleanup whose rows must never be restorable.
   */
  removeMessages = async (
    ids: string[],
    ctx?: MessageQueryContext,
    options?: { permanent?: boolean },
  ): Promise<UpdateMessageResult> => {
    return lambdaClient.message.removeMessages.mutate({
      ...ctx,
      ids,
      ...(options?.permanent ? { permanent: true } : {}),
    });
  };

  removeMessagesByAssistant = async (sessionId: string, topicId?: string) => {
    return lambdaClient.message.removeMessagesByAssistant.mutate({ sessionId, topicId });
  };

  removeMessagesByGroup = async (groupId: string, topicId?: string) => {
    return lambdaClient.message.removeMessagesByGroup.mutate({ groupId, topicId });
  };

  /**
   * Add files to a message
   * Used to associate exported files from code interpreter with the tool message
   */
  addFilesToMessage = async (
    id: string,
    fileIds: string[],
    ctx?: MessageQueryContext,
  ): Promise<UpdateMessageResult> => {
    return lambdaClient.message.addFilesToMessage.mutate({ ...ctx, fileIds, id });
  };

  // =============== Compression ===============

  /**
   * Create a compression group for old messages
   * Returns placeholder group and messages to summarize
   */
  createCompressionGroup = async (params: {
    agentId: string;
    groupId?: string | null;
    messageIds: string[];
    threadId?: string | null;
    topicId: string;
  }): Promise<{
    messageGroupId: string;
    messages: UIChatMessage[];
    messagesToSummarize: UIChatMessage[];
  }> => {
    const result = await lambdaClient.message.createCompressionGroup.mutate(params);
    return {
      messageGroupId: result.messageGroupId,
      messages: (result.messages || []) as unknown as UIChatMessage[],
      messagesToSummarize: (result.messagesToSummarize || []) as unknown as UIChatMessage[],
    };
  };

  /**
   * Finalize compression by updating group with generated summary
   */
  finalizeCompression = async (params: {
    agentId: string;
    content: string;
    groupId?: string | null;
    messageGroupId: string;
    sourceGroupIds?: string[];
    threadId?: string | null;
    topicId: string;
  }): Promise<{ messages?: UIChatMessage[] }> => {
    const result = await lambdaClient.message.finalizeCompression.mutate(params);
    return {
      messages: (result.messages || []) as unknown as UIChatMessage[],
    };
  };

  /**
   * Update message group metadata (e.g., expanded state)
   */
  updateMessageGroupMetadata = async (params: {
    context: {
      agentId: string;
      groupId?: string | null;
      threadId?: string | null;
      topicId: string;
    };
    expanded?: boolean;
    messageGroupId: string;
  }): Promise<{ messages: UIChatMessage[] }> => {
    const result = await lambdaClient.message.updateMessageGroupMetadata.mutate(params);
    return {
      messages: (result.messages || []) as unknown as UIChatMessage[],
    };
  };

  /**
   * Cancel compression by deleting the compression group and restoring original messages
   */
  cancelCompression = async (params: {
    agentId: string;
    groupId?: string | null;
    messageGroupId: string;
    threadId?: string | null;
    topicId: string;
  }): Promise<{ messages: UIChatMessage[] }> => {
    const result = await lambdaClient.message.cancelCompression.mutate(params);
    return { messages: (result.messages || []) as unknown as UIChatMessage[] };
  };
}

export const messageService = new MessageService();