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.

19.5 KB
Raw Blame
import type {
  AcceptanceAccessRequest,
  AcceptanceAccessRequestStatus,
  AcceptanceCommentAttachmentRef,
  AcceptanceCommentKind,
  AcceptanceCommentMetadata,
  AcceptanceCommentSource,
  AcceptanceCommentTime,
  AcceptanceReviewAnnotation,
  DocumentCommentJson,
} from '@lobechat/types';
import { and, asc, count, desc, eq, gte, inArray, isNull, ne, sql } from 'drizzle-orm';

import type { AcceptanceCommentRow } from '../schemas/acceptanceComment';
import { acceptanceComments } from '../schemas/acceptanceComment';
import type { LobeChatDatabase } from '../type';

export const ACCEPTANCE_COMMENT_PARENT_NOT_FOUND = 'Parent comment not found in this acceptance';
export const ACCEPTANCE_COMMENT_RATE_LIMITED = 'Too many comments in the window';

/**
 * One person's emoji on one comment is one row, and the idempotency key is
 * derived rather than supplied: the unique index on
 * (acceptance, author, client_id) is then what stops the same person reacting
 * twice with the same emoji, with no read-modify-write in between.
 */
export const acceptanceReactionClientId = (commentId: string, emoji: string) =>
  `reaction:${commentId}:${emoji}`;

const MAX_COMMENTS_PER_ACCEPTANCE = 1000;

export interface CreateAcceptanceCommentParams {
  acceptanceId: string;
  /** Present only for `evidence` anchors; replies and approvals carry none. */
  anchor?: {
    checkItemId: string;
    evidenceId: string;
    rect: AcceptanceReviewAnnotation['rect'];
    time?: AcceptanceCommentTime;
  };
  /** Files to hang on the remark, kept apart from the body. */
  attachments?: AcceptanceCommentAttachmentRef[];
  /** Sign the row as this agent; ownership still keys on `authorUserId`. */
  authorAgentId?: string;
  authorUserId: string;
  clientId: string;
  content: string;
  contextRunId?: string;
  /** The editor's JSON, when a person wrote the body in one. */
  editorData?: DocumentCommentJson;
  kind?: AcceptanceCommentKind;
  /** Open, server-written per-remark facts. */
  metadata?: AcceptanceCommentMetadata;
  parentCommentId?: string;
  /**
   * Ceiling for this author on this acceptance, enforced inside the write's own
   * transaction. Counting outside it would be advisory only: a handful of
   * parallel requests all read the same under-limit count before any of them
   * commits, which is exactly how a flood arrives.
   */
  rateLimit?: { max: number; since: Date };
  /** The product page the remark was made on (embedded acceptance toolbar). */
  source?: AcceptanceCommentSource;
  workspaceId?: string | null;
}

export interface CreateAcceptanceCommentResult {
  comment: AcceptanceCommentRow;
  /** true when the idempotency key already existed and nothing new was written. */
  isDuplicate: boolean;
}

/**
 * Collaboration rows on an acceptance. Deliberately NOT ownership-scoped: who
 * may read or write a given acceptance's discussion is decided by the router
 * from the acceptance's own visibility and workspace, the same rule the bundle
 * read uses. The model only guarantees structural integrity (threads stay
 * inside one acceptance, tombstones keep replies readable).
 */
export class AcceptanceCommentModel {
  private readonly db: LobeChatDatabase;

  constructor(db: LobeChatDatabase) {
    this.db = db;
  }

  create = async (
    params: CreateAcceptanceCommentParams,
  ): Promise<CreateAcceptanceCommentResult> => {
    return this.db.transaction(async (tx) => {
      const isAccessRequest = params.kind === 'access_request';
      if (params.rateLimit || isAccessRequest)
        // One author on one acceptance is the contended pair, and the lock is
        // released when this transaction ends either way. Everybody else writes
        // in parallel exactly as before.
        await tx.execute(
          sql`select pg_advisory_xact_lock(hashtext(${params.acceptanceId}), hashtext(${params.authorUserId}))`,
        );

      // One standing access request per person. Checked under the lock above,
      // in the same transaction as the insert: checked before it, two tabs
      // asking at once would each see none and both write a pending request β€”
      // and a grant on the older one would not count, since only the newest
      // request is ever read back as the grant.
      if (isAccessRequest) {
        const [standing] = await tx
          .select()
          .from(acceptanceComments)
          .where(
            and(
              eq(acceptanceComments.acceptanceId, params.acceptanceId),
              eq(acceptanceComments.authorUserId, params.authorUserId),
              eq(acceptanceComments.kind, 'access_request'),
              isNull(acceptanceComments.parentCommentId),
              isNull(acceptanceComments.deletedAt),
            ),
          )
          .orderBy(desc(acceptanceComments.createdAt), desc(acceptanceComments.id))
          .limit(1);
        const status = standing?.metadata?.accessRequest?.status;
        if (standing && (status === 'pending' || status === 'granted'))
          return { comment: standing, isDuplicate: true };
      }

      let parentCommentId: string | undefined;
      if (params.parentCommentId) {
        const [parent] = await tx
          .select({
            acceptanceId: acceptanceComments.acceptanceId,
            id: acceptanceComments.id,
            parentCommentId: acceptanceComments.parentCommentId,
          })
          .from(acceptanceComments)
          .where(eq(acceptanceComments.id, params.parentCommentId))
          .limit(1)
          .for('key share');
        if (!parent || parent.acceptanceId !== params.acceptanceId) {
          throw new Error(ACCEPTANCE_COMMENT_PARENT_NOT_FOUND);
        }
        // Replies to a reply flatten onto the thread root. A reaction does not:
        // it answers the exact comment it was clicked on, reply or root.
        parentCommentId =
          params.kind === 'reaction' ? parent.id : (parent.parentCommentId ?? parent.id);
      }

      const isReaction = params.kind === 'reaction';
      const isReply = Boolean(parentCommentId) && !isReaction;
      const anchor = parentCommentId ? undefined : params.anchor;
      const [inserted] = await tx
        .insert(acceptanceComments)
        .values({
          acceptanceId: params.acceptanceId,
          anchorRect: anchor?.rect ?? null,
          anchorType: anchor ? 'evidence' : 'acceptance',
          attachments: params.attachments?.length ? params.attachments : null,
          authorAgentId: params.authorAgentId ?? null,
          authorUserId: params.authorUserId,
          checkItemId: anchor?.checkItemId ?? null,
          clientId: params.clientId,
          content: params.content,
          contextRunId: params.contextRunId ?? null,
          editorData: params.editorData ?? null,
          evidenceId: anchor?.evidenceId ?? null,
          kind: isReply ? 'comment' : (params.kind ?? 'comment'),
          parentCommentId: parentCommentId ?? null,
          metadata: anchor?.time
            ? { ...params.metadata, evidenceAnchor: { time: anchor.time } }
            : (params.metadata ?? null),
          // A page belongs to the thread it opened, never to a reply or reaction.
          source: parentCommentId ? null : (params.source ?? null),
          workspaceId: params.workspaceId ?? null,
        })
        .onConflictDoNothing({
          target: [
            acceptanceComments.acceptanceId,
            acceptanceComments.authorUserId,
            acceptanceComments.clientId,
          ],
        })
        .returning();

      if (inserted) {
        if (params.rateLimit) {
          const [recent] = await tx
            .select({ total: count() })
            .from(acceptanceComments)
            .where(
              and(
                eq(acceptanceComments.acceptanceId, params.acceptanceId),
                eq(acceptanceComments.authorUserId, params.authorUserId),
                ne(acceptanceComments.kind, 'reaction'),
                gte(acceptanceComments.createdAt, params.rateLimit.since),
              ),
            );
          // The row just written is part of this count, so the first one over
          // the ceiling rolls itself back and nothing lands.
          if ((recent?.total ?? 0) > params.rateLimit.max)
            throw new Error(ACCEPTANCE_COMMENT_RATE_LIMITED);
        }
        return { comment: inserted, isDuplicate: false };
      }

      const [existing] = await tx
        .select()
        .from(acceptanceComments)
        .where(
          and(
            eq(acceptanceComments.acceptanceId, params.acceptanceId),
            eq(acceptanceComments.authorUserId, params.authorUserId),
            eq(acceptanceComments.clientId, params.clientId),
          ),
        )
        .limit(1);
      return { comment: existing, isDuplicate: true };
    });
  };

  findById = async (id: string) => {
    const [row] = await this.db
      .select()
      .from(acceptanceComments)
      .where(eq(acceptanceComments.id, id))
      .limit(1);
    return row;
  };

  /**
   * Recent rows of one acceptance, oldest first. A discussion on one delivery is
   * small by nature (a handful of people over a handful of rounds), so the page
   * reads it whole and groups threads client-side.
   *
   * The cap takes the NEWEST rows and hands them back in reading order. Taking
   * the oldest would mean that past the cap a successful post never appears β€”
   * the write succeeds, the reload drops it, and the author is told nothing.
   * Retain roots referenced by recent replies even outside that window: they
   * carry the evidence anchor and resolution state needed to read each reply.
   */
  listByAcceptance = async (acceptanceId: string) => {
    const rows = await this.db
      .select()
      .from(acceptanceComments)
      .where(eq(acceptanceComments.acceptanceId, acceptanceId))
      .orderBy(desc(acceptanceComments.createdAt), desc(acceptanceComments.id))
      .limit(MAX_COMMENTS_PER_ACCEPTANCE);
    const visibleIds = new Set(rows.map((row) => row.id));
    const missingRootIds = [
      ...new Set(
        rows.flatMap((row) =>
          row.kind !== 'reaction' && row.parentCommentId && !visibleIds.has(row.parentCommentId)
            ? [row.parentCommentId]
            : [],
        ),
      ),
    ];
    if (missingRootIds.length === 0) return rows.reverse();

    const roots = await this.db
      .select()
      .from(acceptanceComments)
      .where(
        and(
          eq(acceptanceComments.acceptanceId, acceptanceId),
          inArray(acceptanceComments.id, missingRootIds),
        ),
      )
      .orderBy(asc(acceptanceComments.createdAt), asc(acceptanceComments.id));
    // Missing roots precede the capped window. Keep the DB's ordering (including
    // timestamp precision and ID tie-breaks) rather than sorting hydrated Dates.
    return [...roots, ...rows.reverse()];
  };

  /**
   * Remove one comment. A root that still has replies becomes a tombstone so
   * the replies keep their context; a reply whose tombstoned root has no other
   * replies takes the root with it.
   *
   * `by.authorUserId` scopes the removal to that author's own row β€” the normal
   * case. `by.moderator` skips the author check for someone the caller has
   * already established may moderate this acceptance: since the discussion is
   * open to anyone holding a public link, its owner needs a way to take a
   * remark down, and the author of an unwanted remark is exactly who will not
   * remove it. The router decides who that is; the model only obeys.
   */
  delete = async (
    id: string,
    by: { authorUserId: string } | { moderator: true },
  ): Promise<'hard' | 'soft' | false> => {
    const authorUserId = 'authorUserId' in by ? by.authorUserId : undefined;
    const ownRow = (rowId: string) =>
      authorUserId
        ? and(eq(acceptanceComments.id, rowId), eq(acceptanceComments.authorUserId, authorUserId))
        : eq(acceptanceComments.id, rowId);
    return this.db.transaction(async (tx) => {
      const [target] = await tx
        .select({
          deletedAt: acceptanceComments.deletedAt,
          id: acceptanceComments.id,
          parentCommentId: acceptanceComments.parentCommentId,
        })
        .from(acceptanceComments)
        .where(ownRow(id))
        .limit(1);
      if (!target) return false;

      /**
       * Every deletion in a thread takes the root's lock first, then the row it
       * is actually removing. Locking the root serializes the sweep below: two
       * people deleting the last two replies at once would otherwise each count
       * the other's uncommitted sibling, both skip the sweep, and leave an empty
       * tombstone standing forever. Taking the two locks in a fixed order β€” root
       * before child β€” also keeps a root deletion and a child deletion from
       * deadlocking on each other.
       */
      const rootId = target.parentCommentId ?? target.id;
      const [root] = await tx
        .select({ deletedAt: acceptanceComments.deletedAt, id: acceptanceComments.id })
        .from(acceptanceComments)
        .where(eq(acceptanceComments.id, rootId))
        .limit(1)
        .for('update');
      if (!root) return false;

      // Re-read the target under its own lock: the wait above may have outlived
      // the snapshot the first read came from.
      const [comment] = target.parentCommentId
        ? await tx
            .select({
              deletedAt: acceptanceComments.deletedAt,
              id: acceptanceComments.id,
              parentCommentId: acceptanceComments.parentCommentId,
            })
            .from(acceptanceComments)
            .where(ownRow(id))
            .limit(1)
            .for('update')
        : [{ ...target, deletedAt: root.deletedAt }];
      if (!comment || comment.deletedAt) return false;

      // Reactions are children but not replies: a comment nobody answered is
      // still deletable outright, and its reactions go with it.
      const [replyCount] = await tx
        .select({ total: count() })
        .from(acceptanceComments)
        .where(
          and(eq(acceptanceComments.parentCommentId, id), ne(acceptanceComments.kind, 'reaction')),
        );

      if ((replyCount?.total ?? 0) > 0) {
        // The tombstone keeps the replies' context and nothing else: every way
        // the body could still be read β€” the plain text, the editor's own tree,
        // and the attached files β€” goes with it.
        await tx
          .update(acceptanceComments)
          .set({
            attachments: null,
            content: '',
            deletedAt: new Date(),
            editorData: null,
            updatedAt: new Date(),
          })
          .where(eq(acceptanceComments.id, id));
        return 'soft';
      }

      await tx.delete(acceptanceComments).where(eq(acceptanceComments.parentCommentId, id));
      await tx.delete(acceptanceComments).where(eq(acceptanceComments.id, id));

      // A tombstone only exists to hold its replies up; `root` is this reply's
      // parent, locked and re-read above, so the count below is exclusive.
      if (comment.parentCommentId && root.deletedAt) {
        const [siblings] = await tx
          .select({ total: count() })
          .from(acceptanceComments)
          .where(
            and(
              eq(acceptanceComments.parentCommentId, root.id),
              ne(acceptanceComments.kind, 'reaction'),
            ),
          );
        if ((siblings?.total ?? 0) === 0) {
          await tx
            .delete(acceptanceComments)
            .where(eq(acceptanceComments.parentCommentId, root.id));
          await tx.delete(acceptanceComments).where(eq(acceptanceComments.id, root.id));
        }
      }
      return 'hard';
    });
  };

  /** Take back one's own emoji. Absent rows are a no-op, so a double click is safe. */
  removeReaction = async (params: {
    acceptanceId: string;
    authorUserId: string;
    commentId: string;
    emoji: string;
  }) => {
    const deleted = await this.db
      .delete(acceptanceComments)
      .where(
        and(
          eq(acceptanceComments.acceptanceId, params.acceptanceId),
          eq(acceptanceComments.authorUserId, params.authorUserId),
          eq(
            acceptanceComments.clientId,
            acceptanceReactionClientId(params.commentId, params.emoji),
          ),
          eq(acceptanceComments.kind, 'reaction'),
        ),
      )
      .returning({ id: acceptanceComments.id });
    return deleted.length > 0;
  };

  /**
   * One person's standing access request on one acceptance: their newest
   * surviving `access_request` row, whatever its answer. Withdrawing the request
   * (deleting the row) is how a requester gives a grant back, and a moderator
   * taking it down takes the grant with it.
   */
  findLatestAccessRequest = async (acceptanceId: string, authorUserId: string) => {
    const [row] = await this.db
      .select()
      .from(acceptanceComments)
      .where(
        and(
          eq(acceptanceComments.acceptanceId, acceptanceId),
          eq(acceptanceComments.authorUserId, authorUserId),
          eq(acceptanceComments.kind, 'access_request'),
          isNull(acceptanceComments.parentCommentId),
          isNull(acceptanceComments.deletedAt),
        ),
      )
      .orderBy(desc(acceptanceComments.createdAt), desc(acceptanceComments.id))
      .limit(1);
    return row;
  };

  /** Whether a decider has granted this person `permission` on this acceptance. */
  hasAccessGrant = async (
    acceptanceId: string,
    userId: string,
    permission: AcceptanceAccessRequest['permission'],
  ) => {
    const request = (await this.findLatestAccessRequest(acceptanceId, userId))?.metadata
      ?.accessRequest;
    return request?.status === 'granted' && request.permission === permission;
  };

  /**
   * Move an access request from `from` to `next`. Conditional on the status the
   * caller read, so two deciders answering at once cannot both win β€” the second
   * update matches nothing and returns undefined.
   */
  answerAccessRequest = async (
    id: string,
    from: AcceptanceAccessRequestStatus,
    next: AcceptanceAccessRequest,
  ) => {
    const [row] = await this.db
      .update(acceptanceComments)
      .set({
        metadata: sql`jsonb_set(coalesce(${acceptanceComments.metadata}, '{}'::jsonb), '{accessRequest}', ${JSON.stringify(next)}::jsonb)`,
        updatedAt: new Date(),
      })
      .where(
        and(
          eq(acceptanceComments.id, id),
          eq(acceptanceComments.kind, 'access_request'),
          isNull(acceptanceComments.deletedAt),
          sql`${acceptanceComments.metadata} -> 'accessRequest' ->> 'status' = ${from}`,
        ),
      )
      .returning();
    return row;
  };

  resolveRoots = async (acceptanceId: string, rootIds: string[], userId: string) => {
    if (!rootIds.length) return [];
    return this.db
      .update(acceptanceComments)
      .set({ resolvedAt: new Date(), resolvedByUserId: userId, updatedAt: new Date() })
      .where(
        and(
          eq(acceptanceComments.acceptanceId, acceptanceId),
          inArray(acceptanceComments.id, rootIds),
          isNull(acceptanceComments.parentCommentId),
          isNull(acceptanceComments.resolvedAt),
          isNull(acceptanceComments.deletedAt),
        ),
      )
      .returning();
  };

  /** Mark a thread root handled (or reopen it). Replies are not resolvable. */
  setResolved = async (rootId: string, resolved: boolean, userId: string) => {
    const [row] = await this.db
      .update(acceptanceComments)
      .set(
        resolved
          ? { resolvedAt: new Date(), resolvedByUserId: userId, updatedAt: new Date() }
          : { resolvedAt: null, resolvedByUserId: null, updatedAt: new Date() },
      )
      .where(and(eq(acceptanceComments.id, rootId), isNull(acceptanceComments.parentCommentId)))
      .returning();
    return row;
  };
}