import { and, asc, eq, inArray, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { issueComments, issueLabels, issues, labels, primeDatabaseWorkTransactionId, } from "@paperclipai/db"; import type { BoardEventView, CommentView, SchemaBlock, } from "@paperclipai/shared"; import { notFound } from "../errors.js"; import { logger } from "../middleware/logger.js"; import { createActivityDetailsRedactor, logActivitiesBatch, publishActivity, type ActivityPublication, type LogActivityInput, } from "./activity-log.js"; import { createAdaptiveCompanyBatcher, type PendingEntry, } from "./adaptive-company-batcher.js"; import { forEachPostCommitSafely } from "./headless-board-events-write.js"; import { appendBoardEvents, mintTimeOrderedUuid, publishCommittedBoardEvent, serializeCommentView, touchChannelsLastActivity, type AppendBoardEventInput, type HeadlessActorContext, } from "./headless-common.js"; export interface CoalescedCommentInput { actor: HeadlessActorContext; targetIssue: { id: string; identifier: string | null; companyId: string; channelId: string | null; kvLabels: Record | null; }; channelPath: string | null; authorUserId: string | null; bodyText: string; mergedKvLabels: Record; validatedBlocks: SchemaBlock[]; internal: boolean; } export interface CoalescedCommentResult { comment: CommentView; created: boolean; } async function runCoalescedCommentsBatch( db: Db, companyId: string, entries: Array>, allowFallback: boolean, ): Promise { const publications: ActivityPublication[] = []; const committedEvents: BoardEventView[] = []; const rejectedEntries: Array<{ entry: PendingEntry; error: unknown; }> = []; let outcomes: Array<{ entry: PendingEntry; result: CoalescedCommentResult; }>; try { const activityRedactor = await createActivityDetailsRedactor(db); outcomes = await db.transaction(async (tx) => { const distinctIssueIds = Array.from( new Set(entries.map((e) => e.item.targetIssue.id)), ).sort(); const lockedIssues = distinctIssueIds.length === 1 ? await tx .select({ id: issues.id, kvLabels: issues.kvLabels }) .from(issues) .where( and( eq(issues.companyId, companyId), eq(issues.id, distinctIssueIds[0]!), ), ) .for("no key update") : await tx .select({ id: issues.id, kvLabels: issues.kvLabels }) .from(issues) .where( and( eq(issues.companyId, companyId), inArray(issues.id, distinctIssueIds), ), ) .orderBy(asc(issues.id)) .for("no key update"); const currentKvByIssueId = new Map>(); for (const row of lockedIssues) { currentKvByIssueId.set( row.id, (row.kvLabels ?? {}) as Record, ); } const activeEntries: Array< PendingEntry > = []; for (const entry of entries) { if (!currentKvByIssueId.has(entry.item.targetIssue.id)) { rejectedEntries.push({ entry, error: notFound("Issue not found") }); } else { activeEntries.push(entry); } } if (activeEntries.length === 0) { return []; } const activeIssueIds = Array.from( new Set(activeEntries.map((e) => e.item.targetIssue.id)), ); const tagsByIssueId = new Map(); const tagRows = await tx .select({ issueId: issueLabels.issueId, name: labels.name }) .from(issueLabels) .innerJoin(labels, eq(issueLabels.labelId, labels.id)) .where( and( eq(issueLabels.companyId, companyId), inArray(issueLabels.issueId, activeIssueIds), ), ) .orderBy(asc(labels.name)); for (const r of tagRows) { let arr = tagsByIssueId.get(r.issueId); if (!arr) { arr = []; tagsByIssueId.set(r.issueId, arr); } arr.push(r.name); } const now = new Date(); const nowMs = now.getTime(); const plannedComments = activeEntries.map((entry) => ({ entry, commentId: mintTimeOrderedUuid(nowMs), createdAt: now, })); if (activeIssueIds.length === 1) { await tx .update(issues) .set({ updatedAt: now }) .where( and( eq(issues.companyId, companyId), eq(issues.id, activeIssueIds[0]!), ), ); } else { await tx .update(issues) .set({ updatedAt: now }) .where( and( eq(issues.companyId, companyId), inArray(issues.id, activeIssueIds), ), ); } const insertedRows = await tx .insert(issueComments) .values( plannedComments.map(({ entry: { item }, commentId, createdAt }) => ({ id: commentId, companyId, issueId: item.targetIssue.id, authorAgentId: item.actor.agentId, authorUserId: item.authorUserId, authorType: item.actor.agentId ? ("agent" as const) : ("user" as const), actorProfile: item.actor.actorProfile, body: item.bodyText, kvLabels: item.mergedKvLabels, schemaBlocks: item.validatedBlocks, noSync: item.internal, clientRequestId: null, createdAt, updatedAt: createdAt, })), ) .returning({ id: issueComments.id, issueId: issueComments.issueId, body: issueComments.body, authorType: issueComments.authorType, authorUserId: issueComments.authorUserId, authorAgentId: issueComments.authorAgentId, actorProfile: issueComments.actorProfile, kvLabels: issueComments.kvLabels, schemaBlocks: issueComments.schemaBlocks, noSync: issueComments.noSync, createdAt: issueComments.createdAt, xid: sql`pg_current_xact_id()::text`, }); const insertedById = new Map(insertedRows.map((row) => [row.id, row])); const firstXid = insertedRows[0]?.xid; if (firstXid) { primeDatabaseWorkTransactionId(tx, firstXid); } await touchChannelsLastActivity( tx, plannedComments.map((p) => p.entry.item.targetIssue.channelId), now, ); const activityInputs: LogActivityInput[] = plannedComments.map( ({ entry: { item }, commentId }) => { const identifier = item.targetIssue.identifier ?? item.targetIssue.id; return { companyId, actorType: item.actor.principalType === "agent" ? "agent" : "user", actorId: item.actor.principalType === "agent" ? item.actor.agentId! : (item.actor.userId ?? "local-board"), agentId: item.actor.agentId, issueId: item.targetIssue.id, responsibleUserIdOverride: item.actor.responsibleUserId, action: "issue.comment_added", entityType: "issue", entityId: item.targetIssue.id, details: { commentId, identifier, internal: item.internal, source: "headless", ...(item.actor.actorProfile ? { actorProfile: item.actor.actorProfile } : {}), }, }; }, ); await logActivitiesBatch(tx as unknown as Db, activityInputs, publications, { redactor: activityRedactor, }); const eventInputs: AppendBoardEventInput[] = plannedComments.map( ({ entry: { item }, commentId }) => { const identifier = item.targetIssue.identifier ?? item.targetIssue.id; return { companyId, type: "comment.posted", channelId: item.targetIssue.channelId, channelPath: item.channelPath, issueId: item.targetIssue.id, identifier, actor: item.actor, payload: { commentId, body: item.bodyText.slice(0, 4000), blocks: item.validatedBlocks, labels: item.mergedKvLabels, kvLabels: currentKvByIssueId.get(item.targetIssue.id) ?? item.targetIssue.kvLabels ?? {}, tagLabels: tagsByIssueId.get(item.targetIssue.id) ?? [], internal: item.internal, }, }; }, ); const appendedEvents = await appendBoardEvents(tx, eventInputs); committedEvents.push(...appendedEvents); return plannedComments.map((plan, idx) => { const inserted = insertedById.get(plan.commentId)!; const evt = appendedEvents[idx]!; const identifier = plan.entry.item.targetIssue.identifier ?? plan.entry.item.targetIssue.id; return { entry: plan.entry, result: { comment: serializeCommentView(inserted, identifier, evt.cursor), created: true, }, }; }); }); } catch (err) { if (allowFallback && entries.length > 1) { for (const single of entries) { await runCoalescedCommentsBatch(db, companyId, [single], false); } return; } for (const rej of rejectedEntries) { rej.entry.reject(rej.error); } const unsettled = new Set( entries.filter((e) => !rejectedEntries.some((r) => r.entry === e)), ); for (const entry of unsettled) { entry.reject(err); } return; } for (const rej of rejectedEntries) { rej.entry.reject(rej.error); } forEachPostCommitSafely(publications, publishActivity, (pub, err) => { logger.warn({ err, companyId: pub.companyId }, "post-commit activity listener failed"); }); forEachPostCommitSafely(committedEvents, publishCommittedBoardEvent, (evt, err) => { logger.warn({ err, companyId: evt.companyId, seq: evt.seq }, "post-commit board event listener failed"); }); for (const outcome of outcomes) { outcome.entry.resolve(outcome.result); } } export const executeCoalescedHeadlessComment = createAdaptiveCompanyBatcher< CoalescedCommentInput, CoalescedCommentResult >(runCoalescedCommentsBatch, { backpressureMessage: "Too many concurrent channel replies queued for this company; retry shortly", });