import { BACKGROUND_CONTEXT as piContext } from '@earendil-works/chord/context' import { type Message as AgentMessage } from '@earendil-works/pi-ai' import { type Conversation, defineDoc, type Cursor, type EntryDraft, type JsonObject, } from '@earendil-works/pi-durable' import { secondToDegree } from '@shumai/core/src/utils/model3d' import { prisma } from '@shumai/db' import { ShumaiMessageEntry, type ShumaiMediaPosition, type ShumaiMessageContext, } from '@shumai/dtos' import { ApplicationFailure } from '@shumai/workflow-core' const ThreadContextDoc = defineDoc<{ commentIds: string[] }>({ kind: 'shumai.thread', version: 1, scope: 'conversation', history: 'latest', fork: 'initial', initial: () => ({ commentIds: [] }), checkpointWhen: () => true, }) export async function initializeCommentSession(params: { teamId: string agentId: string userCommentId: string userId?: string }): Promise { const userComment = await prisma.assetComment.findUnique({ where: { id: params.userCommentId }, select: { assetId: true, replyToId: true }, }) if (!userComment) { throw ApplicationFailure.create({ message: `User comment ${params.userCommentId} not found`, nonRetryable: true, }) } const rootCommentId = userComment.replyToId || params.userCommentId const threadKey = `agent-thread:${params.agentId}:${userComment.assetId}:${rootCommentId}` return prisma.$transaction(async (tx) => { // The lock and insert share a transaction, so rollback also releases ownership. // Unlike the writer lock, this key exists before a session ID has been chosen. await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${threadKey}, 0))` await tx.user.upsert({ where: { id: params.agentId }, update: {}, create: { id: params.agentId, name: 'Ai Agent', email: `${params.agentId}@shumai.ai`, type: 'agent', }, }) await tx.agent.upsert({ where: { id: params.agentId }, update: {}, create: { id: params.agentId, teamId: params.teamId, type: 'chat', config: { provider: 'openai', model: 'gpt-4' }, }, }) const existing = await tx.agentSession.findFirst({ where: { agentId: params.agentId, assetId: userComment.assetId, type: 'comment', userCommentId: rootCommentId, }, // Reuse the original session deterministically if older data contains duplicates. orderBy: { id: 'asc' }, }) if (existing) return existing.id const session = await tx.agentSession.create({ data: { agentId: params.agentId, userId: params.userId || null, cwd: process.cwd(), assetId: userComment.assetId, userCommentId: rootCommentId, type: 'comment', }, }) return session.id }) } /** Import passive history while the caller owns the generation's session writer. */ export async function synchronizeCommentContext(params: { conversation: Conversation sessionId: string teamId: string agentId: string userCommentId: string }): Promise { const userComment = await prisma.assetComment.findUnique({ where: { id: params.userCommentId }, include: { creator: true }, }) if (!userComment) { throw ApplicationFailure.create({ message: `User comment ${params.userCommentId} not found`, nonRetryable: true, }) } const rootCommentId = userComment.replyToId || userComment.id const rootComment = await prisma.assetComment.findUnique({ where: { id: rootCommentId }, include: { creator: true }, }) if (!rootComment) { throw ApplicationFailure.create({ message: `Root comment ${rootCommentId} not found`, nonRetryable: true, }) } // 1. Fetch top-level comments up to rootComment.createdAt sorted by id const topLevelComments = await prisma.assetComment.findMany({ where: { assetId: userComment.assetId, replyToId: null, createdAt: { lte: rootComment.createdAt }, }, orderBy: { id: 'asc' }, include: { creator: true, attachments: { include: { asset: true } }, }, }) // 2. Fetch thread replies up to userComment.createdAt excluding userComment itself const threadReplies = userComment.replyToId ? await prisma.assetComment.findMany({ where: { replyToId: rootCommentId, createdAt: { lte: userComment.createdAt }, id: { not: userComment.id }, }, orderBy: { id: 'asc' }, include: { creator: true, attachments: { include: { asset: true } }, }, }) : [] const replyCounts = await prisma.assetComment.groupBy({ by: ['replyToId'], where: { assetId: userComment.assetId, replyToId: { not: null }, message: { not: '__CHAT__' } }, _count: true, }) const counts = new Map(replyCounts.map((row) => [row.replyToId, row._count])) const allCommentsToSync = [...topLevelComments, ...threadReplies] // Resolve user mentions from IDs to names and roles const mentionRegex = /<@([^>]+)>/g const mentionedUserIds = new Set() for (const c of allCommentsToSync) { if (c.message) { const matches = [...c.message.matchAll(mentionRegex)] for (const match of matches) { mentionedUserIds.add(match[1]) } } } const userIdToNameMap = new Map() if (mentionedUserIds.size > 0) { const resolvedUsers = await prisma.user.findMany({ where: { id: { in: Array.from(mentionedUserIds) } }, select: { id: true, name: true }, }) for (const u of resolvedUsers) { if (u.name) userIdToNameMap.set(u.id, u.name) } } const userRoleMap = new Map() const humanCreatorIds = Array.from( new Set( allCommentsToSync .filter((c) => c.creator?.type !== 'agent' && c.creatorId) .map((c) => c.creatorId!), ), ) if (humanCreatorIds.length > 0) { const members = await prisma.teamMember.findMany({ where: { teamId: params.teamId, userId: { in: humanCreatorIds }, }, select: { userId: true, role: true }, }) for (const m of members) { userRoleMap.set(m.userId, m.role) } } const assetRecord = await prisma.asset.findUnique({ where: { id: userComment.assetId }, select: { media: true }, }) const proxyType = (assetRecord?.media as PrismaJson.MediaInfo | null)?.proxyType function buildCommentEntry(c: (typeof allCommentsToSync)[0]): EntryDraft { const isAgent = c.creator?.type === 'agent' || c.sessionId !== null let messageContent = c.message || '' messageContent = messageContent.replace(mentionRegex, (match, userId) => { const resolvedName = userIdToNameMap.get(userId) return resolvedName ? `<@${resolvedName}>` : match }) if (isAgent) { const message: AgentMessage = { role: 'assistant', content: [{ type: 'text', text: messageContent }], api: 'custom', provider: 'shumai', model: 'agent', usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, }, stopReason: 'stop', timestamp: c.createdAt.getTime(), } return { kind: 'pi.assistant', model: [message], data: { sourceCommentId: c.id }, } } let userObj: ShumaiMessageContext['user'] = undefined if (c.creator) { const role = (c.creatorId ? userRoleMap.get(c.creatorId) : undefined) || 'user' userObj = { id: c.creator.id, name: c.creator.name || 'Unknown', role, } } let position: ShumaiMediaPosition | undefined = undefined if (c.second !== null && c.second !== undefined) { if (proxyType === '3d') { position = { type: 'degree', degree: secondToDegree(c.second) } } else if (proxyType === 'pdf') { position = { type: 'page', page: Math.round(c.second) } } else { position = { type: 'time', seconds: c.second } } } const annotation = !!(c.annotation && Array.isArray(c.annotation) && c.annotation.length > 0) const attachedFiles: ShumaiMessageContext['attachedFiles'] = [] if (c.attachments && c.attachments.length > 0) { for (const att of c.attachments) { if (att.asset) { const attProxyType = (att.asset.media as PrismaJson.MediaInfo | null)?.proxyType attachedFiles.push({ id: att.asset.id, name: att.asset.name, type: att.asset.type, mediaType: attProxyType as 'image' | 'video' | 'pdf' | 'audio' | '3d' | 'other' | undefined, mimeType: att.asset.mediaType || undefined, }) } } } const commentDetails: ShumaiMessageContext = { id: c.id, ...(!c.replyToId && counts.get(c.id) ? { thread: { id: c.id, replyCount: counts.get(c.id)! } } : {}), ...(userObj ? { user: userObj } : {}), ...(position ? { position } : {}), ...(annotation ? { annotation: true, annotations: c.annotation as unknown as ShumaiMessageContext['annotations'], } : {}), ...(attachedFiles.length > 0 ? { attachedFiles } : {}), } return { kind: ShumaiMessageEntry.kind, model: [{ role: 'user' as const, content: messageContent, timestamp: c.createdAt.getTime() }], data: JSON.parse( JSON.stringify({ displayText: messageContent, timestamp: c.createdAt.getTime(), context: commentDetails, sourceCommentId: c.id, }), ) as JsonObject, } } const root = params.conversation const present = new Set() let cursor: Cursor | undefined do { const page = await root.entries({ order: 'ascending' }, 100, cursor, piContext) for (const entry of page.items) { if ( entry.data && typeof entry.data === 'object' && !Array.isArray(entry.data) && 'sourceCommentId' in entry.data && typeof entry.data.sourceCommentId === 'string' ) present.add(entry.data.sourceCommentId) } cursor = page.next } while (cursor) const candidates = allCommentsToSync.filter( (comment) => comment.id !== params.userCommentId && comment.sessionId !== params.sessionId && comment.message !== '__CHAT__' && !present.has(comment.id), ) if (!candidates.length) return // A comment and its agent workflows are created in the same DB transaction. // Reserve these comments for their live input, including across workflow retries. const threadCommentIds = candidates .filter((comment) => (comment.replyToId || comment.id) === rootCommentId) .map((comment) => comment.id) const tasks = threadCommentIds.length ? await prisma.workflowTask.findMany({ where: { assetId: userComment.assetId, type: 'chat', payload: { path: ['agent', 'agentId'], equals: params.agentId }, OR: threadCommentIds.map((id) => ({ payload: { path: ['agent', 'userCommentId'], equals: id }, })), }, select: { payload: true }, orderBy: { id: 'desc' }, }) : [] const liveComments = new Set(tasks.map((task) => task.payload?.agent?.userCommentId)) await root.commit(async (tx) => { const state = await tx.doc(ThreadContextDoc, root.id) for (const comment of candidates) { if (liveComments.has(comment.id) || state.commentIds.includes(comment.id)) continue await tx.appendEntry(root.id, buildCommentEntry(comment)) state.commentIds.push(comment.id) } }, piContext) }