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.9 KB
Raw Blame
import type { ChatTopicMetadata } from '@lobechat/types';
import {
  and,
  asc,
  eq,
  exists,
  gt,
  gte,
  inArray,
  isNotNull,
  isNull,
  lte,
  max,
  ne,
  not,
  notExists,
  notInArray,
  or,
  sql,
} from 'drizzle-orm';

import { messages, topics, userSettings } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { notShareVisitorTopic } from '../utils/shareVisitor';
import { notTrashed } from '../utils/softDelete';
import { CHANNEL_TOPIC_TRIGGER } from '../utils/topicVisibility';

export interface TopicSummaryCandidateCursor {
  id: string;
  lastMessageUpdatedAt: Date;
}

export interface ListTopicSummaryCandidatesOptions {
  cursor?: TopicSummaryCandidateCursor;
  force?: boolean;
  idleBefore: Date;
  limit: number;
  topicCreatedAfter: Date;
}

export interface TopicSummaryCandidate {
  id: string;
  lastMessageUpdatedAt: Date;
  userId: string;
  workspaceId: string | null;
}

// Mirrors `DEFAULT_TOPIC_AUTO_SUMMARY_SYSTEM_AGENT_ITEM.enabled`: users who have
// never touched the setting are opted out, so the missing-value default is false.
const isTopicAutoSummaryEnabled = sql<boolean>`COALESCE((${userSettings.systemAgent}->'topicAutoSummary'->>'enabled')::boolean, false) = true`;
const SYSTEM_TOPIC_TRIGGERS = [
  CHANNEL_TOPIC_TRIGGER,
  'cron',
  'eval',
  'task_manager',
  'task',
  'document',
];

export const topicSummaryEligibleMessage = and(
  isNotNull(messages.content),
  ne(messages.content, ''),
  inArray(messages.role, ['assistant', 'user']),
  // A message sitting in the recycle bin must neither feed nor date the summary.
  notTrashed(messages.isDeleted),
);

const getAutoSummaryWatermark = () =>
  sql<Date>`COALESCE(NULLIF(COALESCE(${topics.metadata}->'autoSummary'->>'lastMessageUpdatedAt', ''), '')::timestamptz, 'epoch'::timestamptz)`.mapWith(
    topics.updatedAt,
  );

const mergeAutoSummaryMetadata = (marker: NonNullable<ChatTopicMetadata['autoSummary']>) =>
  sql`COALESCE(${topics.metadata}, '{}'::jsonb) || ${JSON.stringify({ autoSummary: marker })}::jsonb`;

/** System-scoped queries used only by the authenticated background summary workflow. */
export class TopicSummaryModel {
  constructor(private readonly db: LobeChatDatabase) {}

  /** An eligible message that arrived after the given snapshot. */
  private newerEligibleMessage = (input: {
    lastMessageId: string;
    lastMessageUpdatedAt: Date;
    topicId: string;
  }) =>
    this.db
      .select({ id: messages.id })
      .from(messages)
      .where(
        and(
          eq(messages.topicId, input.topicId),
          topicSummaryEligibleMessage,
          or(
            gt(messages.updatedAt, input.lastMessageUpdatedAt),
            and(
              eq(messages.updatedAt, input.lastMessageUpdatedAt),
              gt(messages.id, input.lastMessageId),
            ),
          ),
        ),
      );

  listCandidates = async ({
    cursor,
    force = false,
    idleBefore,
    limit,
    topicCreatedAfter,
  }: ListTopicSummaryCandidatesOptions): Promise<TopicSummaryCandidate[]> => {
    const lastMessageUpdatedAt = max(messages.updatedAt).mapWith(messages.updatedAt);
    const cursorCondition = cursor
      ? or(
          gt(lastMessageUpdatedAt, cursor.lastMessageUpdatedAt),
          and(eq(lastMessageUpdatedAt, cursor.lastMessageUpdatedAt), gt(topics.id, cursor.id)),
        )
      : undefined;

    return this.db
      .select({
        id: topics.id,
        lastMessageUpdatedAt,
        userId: topics.userId,
        workspaceId: topics.workspaceId,
      })
      .from(topics)
      .innerJoin(messages, eq(messages.topicId, topics.id))
      .leftJoin(userSettings, eq(userSettings.id, topics.userId))
      .where(
        and(
          gte(topics.createdAt, topicCreatedAfter),
          // System-scoped read — no `buildWorkspaceWhere` funnel here, so the
          // recycle-bin gate is spelled out: never spend an LLM call on a
          // trashed topic.
          notTrashed(topics.isDeleted),
          topicSummaryEligibleMessage,
          or(isNull(topics.trigger), not(inArray(topics.trigger, SYSTEM_TOPIC_TRIGGERS))),
          or(isNull(topics.status), notInArray(topics.status, ['running', 'scheduled'])),
          // Visitor topics are creator-billed only through the share spend
          // gate; the auto-summary worker must never pick them, or a shared
          // agent's visitor turn would silently spend the creator's balance
          // outside the gate. See `notShareVisitorTopic` for the invariant.
          notShareVisitorTopic(),
          force ? undefined : isTopicAutoSummaryEnabled,
        ),
      )
      .groupBy(topics.id, topics.userId, topics.workspaceId, topics.metadata)
      .having(
        and(
          lte(lastMessageUpdatedAt, idleBefore),
          force ? undefined : ne(getAutoSummaryWatermark(), lastMessageUpdatedAt),
          cursorCondition,
        ),
      )
      .orderBy(asc(lastMessageUpdatedAt), asc(topics.id))
      .limit(limit);
  };

  updateSummaryIfCurrent = async (input: {
    description: string;
    lastMessageId: string;
    lastMessageUpdatedAt: Date;
    summary: string;
    topicId: string;
  }): Promise<boolean> => {
    const marker: NonNullable<ChatTopicMetadata['autoSummary']> = {
      lastMessageId: input.lastMessageId,
      lastMessageUpdatedAt: input.lastMessageUpdatedAt.toISOString(),
      summarizedAt: new Date().toISOString(),
      version: 1,
    };
    const snapshotMessage = this.db
      .select({ id: messages.id })
      .from(messages)
      .where(
        and(
          eq(messages.topicId, input.topicId),
          topicSummaryEligibleMessage,
          eq(messages.id, input.lastMessageId),
          eq(messages.updatedAt, input.lastMessageUpdatedAt),
        ),
      );
    const newerMessage = this.newerEligibleMessage(input);

    const rows = await this.db
      .update(topics)
      .set({
        description: input.description,
        historySummary: input.summary,
        metadata: mergeAutoSummaryMetadata(marker),
        updatedAt: new Date(),
      })
      .where(
        and(
          eq(topics.id, input.topicId),
          // Defense in depth against a visitor topic slipping past the
          // listCandidates filter and the service-layer guard (see
          // `notShareVisitorTopic`): the write fence itself refuses to touch
          // a share-visitor topic keyed only by id.
          notShareVisitorTopic(),
          // Trashed between candidate selection and commit → leave it alone.
          notTrashed(topics.isDeleted),
          exists(snapshotMessage),
          notExists(newerMessage),
        ),
      )
      .returning({ id: topics.id });

    return rows.length > 0;
  };

  /**
   * Advance the watermark without a summary when the model failed for a reason
   * only the user can fix, so the dispatch stops re-queueing the topic every run
   * until a new message arrives. A summary written earlier is kept.
   */
  markSummaryFailed = async (input: {
    lastMessageId: string;
    lastMessageUpdatedAt: Date;
    reason: string;
    topicId: string;
  }): Promise<boolean> => {
    const failure = {
      failedAt: new Date().toISOString(),
      failureReason: input.reason,
      lastMessageId: input.lastMessageId,
      lastMessageUpdatedAt: input.lastMessageUpdatedAt.toISOString(),
      version: 1,
    };

    const rows = await this.db
      .update(topics)
      .set({
        // Merge into the existing marker: `summarizedAt` from an earlier summary survives.
        metadata: sql`jsonb_set(COALESCE(${topics.metadata}, '{}'::jsonb), '{autoSummary}', COALESCE(${topics.metadata}->'autoSummary', '{}'::jsonb) || ${JSON.stringify(failure)}::jsonb)`,
      })
      .where(
        and(
          eq(topics.id, input.topicId),
          notShareVisitorTopic(),
          notTrashed(topics.isDeleted),
          // A newer message means a later run owns the watermark; never rewind it.
          notExists(this.newerEligibleMessage(input)),
        ),
      )
      .returning({ id: topics.id });

    return rows.length > 0;
  };
}