fix(agent): implement shared DAG tree entries across comment sessions without entry duplication

This commit is contained in:
yiling
2026-07-29 11:21:55 +08:00
parent b75e0c7fdc
commit 343750e178
3 changed files with 141 additions and 144 deletions
+38 -8
View File
@@ -539,15 +539,17 @@ describe('Agent Database Activities Integration', () => {
// Verify agentSession created // Verify agentSession created
const agentSession = await prisma.agentSession.findUnique({ const agentSession = await prisma.agentSession.findUnique({
where: { id: sessionId }, where: { id: sessionId },
include: { entries: true },
}) })
expect(agentSession).toBeDefined() expect(agentSession).toBeDefined()
expect(agentSession?.leafId).toBeDefined() expect(agentSession?.leafId).toBeDefined()
// Verify historical comment is converted and saved to entries (mentions replaced, prefixes added) // Verify historical comment is converted and saved to DAG entries via path traversal
expect(agentSession?.entries.length).toBe(1) const storage = new DatabaseSessionStorage(sessionId)
const pathEntries = await storage.getPathToRoot(agentSession!.leafId)
expect(pathEntries.length).toBe(2)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- entry data is stored as Json in DB and needs casting to check properties // eslint-disable-next-line @typescript-eslint/no-explicit-any -- entry data is stored as Json in DB and needs casting to check properties
const parsedEntry = agentSession?.entries[0].data as any const parsedEntry = pathEntries[0] as any
expect(parsedEntry.message.content[0].text).toContain( expect(parsedEntry.message.content[0].text).toContain(
`[${user.name} (owner)]: Hello <@${user.name}> check this`, `[${user.name} (owner)]: Hello <@${user.name}> check this`,
) )
@@ -666,13 +668,13 @@ describe('Agent Database Activities Integration', () => {
expect(text).toContain(`[Thread ID: ${msg3.id}]`) expect(text).toContain(`[Thread ID: ${msg3.id}]`)
}) })
it('should create separate thread sessions when agent is mentioned in top-level comments (msg3 & msg5) and reuse session on thread follow-ups', async () => { it('should create separate thread sessions when agent is mentioned in top-level comments (msg3 & msg5) sharing DAG entries without duplication', async () => {
// msg1 (top level) // msg1 (top level)
await prisma.assetComment.create({ const msg1 = await prisma.assetComment.create({
data: { assetId: asset.id, message: 'msg1', creatorId: user.id }, data: { assetId: asset.id, message: 'msg1', creatorId: user.id },
}) })
// msg2 (top level) // msg2 (top level)
await prisma.assetComment.create({ const msg2 = await prisma.assetComment.create({
data: { assetId: asset.id, message: 'msg2', creatorId: user.id }, data: { assetId: asset.id, message: 'msg2', creatorId: user.id },
}) })
// msg3 (top level asking agent) // msg3 (top level asking agent)
@@ -689,7 +691,7 @@ describe('Agent Database Activities Integration', () => {
}) })
// agent response msg4 // agent response msg4
await prisma.assetComment.create({ const msg4 = await prisma.assetComment.create({
data: { data: {
assetId: asset.id, assetId: asset.id,
message: 'msg4', message: 'msg4',
@@ -741,6 +743,34 @@ describe('Agent Database Activities Integration', () => {
// Reuses session3Id (Thread Session 1) // Reuses session3Id (Thread Session 1)
expect(session7Id).toBe(session3Id) expect(session7Id).toBe(session3Id)
// VERIFY DAG ENTRY SHARING & NO DUPLICATION
// Every shared comment must have EXACTLY 1 row in agent_session_entries with id = comment.id
const msg1Entries = await prisma.agentSessionEntry.findMany({ where: { id: msg1.id } })
const msg2Entries = await prisma.agentSessionEntry.findMany({ where: { id: msg2.id } })
const msg3Entries = await prisma.agentSessionEntry.findMany({ where: { id: msg3.id } })
expect(msg1Entries.length).toBe(1)
expect(msg2Entries.length).toBe(1)
expect(msg3Entries.length).toBe(1)
// Verify DatabaseSessionStorage path traversal for session 3 vs session 5
const storage3 = new DatabaseSessionStorage(session3Id)
const path3 = await storage3.getPathToRoot(msg4.id)
const path3Ids = path3.map((e) => e.id)
expect(path3Ids).toContain(msg1.id)
expect(path3Ids).toContain(msg2.id)
expect(path3Ids).toContain(msg3.id)
expect(path3Ids).toContain(msg4.id)
expect(path3Ids).not.toContain(msg5.id)
const storage5 = new DatabaseSessionStorage(session5Id)
const path5 = await storage5.getPathToRoot(msg5.id)
const path5Ids = path5.map((e) => e.id)
expect(path5Ids).toContain(msg1.id)
expect(path5Ids).toContain(msg2.id)
expect(path5Ids).toContain(msg3.id)
expect(path5Ids).toContain(msg5.id)
expect(path5Ids).not.toContain(msg4.id)
}) })
it('should return user name and role for team member', async () => { it('should return user name and role for team member', async () => {
+97 -129
View File
@@ -517,7 +517,6 @@ export async function initializeAgentSessionActivity(params: {
}, },
}) })
} }
const sessionId = session.id
const rootComment = await prisma.assetComment.findUnique({ const rootComment = await prisma.assetComment.findUnique({
where: { id: rootCommentId }, where: { id: rootCommentId },
@@ -548,6 +547,7 @@ export async function initializeAgentSessionActivity(params: {
}) })
} }
// 1. Fetch top-level comments up to rootComment.createdAt
const topLevelComments = await prisma.assetComment.findMany({ const topLevelComments = await prisma.assetComment.findMany({
where: { where: {
assetId: userComment.assetId, assetId: userComment.assetId,
@@ -558,86 +558,24 @@ export async function initializeAgentSessionActivity(params: {
include: { creator: true }, include: { creator: true },
}) })
let mainPrevId: string | null = mainSession.leafId // 2. Fetch thread replies up to userComment.createdAt if userComment is in a thread
for (const c of topLevelComments) { const threadReplies = userComment.replyToId
const entryId = `${c.id}_${mainSession.id}` ? await prisma.assetComment.findMany({
const existingEntry = await prisma.agentSessionEntry.findUnique({ where: {
where: { id: entryId }, replyToId: rootCommentId,
select: { id: true }, createdAt: { lte: userComment.createdAt },
}) },
if (existingEntry) { orderBy: { createdAt: 'asc' },
mainPrevId = existingEntry.id include: { creator: true },
continue })
} : []
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null const allCommentsToSync = [...topLevelComments, ...threadReplies]
let messageContent = c.message || ''
if (isAgent) {
const agentName = c.creator?.name || 'Ai Agent'
messageContent = `[Agent Message][${agentName}]: ${messageContent}`
} else if (c.creator?.name) {
messageContent = `[${c.creator.name} (user)]: ${messageContent}`
}
const message: AgentMessage = { // Resolve user mentions from IDs to names and roles
role: 'user',
content: [{ type: 'text', text: messageContent }],
timestamp: c.createdAt.getTime(),
}
await prisma.agentSessionEntry.create({
data: {
id: entryId,
sessionId: mainSession.id,
assetId: userComment.assetId,
type: 'message',
parentId: mainPrevId,
createdAt: c.createdAt,
data: { message },
},
})
mainPrevId = entryId
}
if (mainPrevId && mainPrevId !== mainSession.leafId) {
await prisma.agentSession.update({
where: { id: mainSession.id },
data: { leafId: mainPrevId },
})
}
// Fetch existing comments as context for Thread Session
const precedingTopLevelComments = await prisma.assetComment.findMany({
where: {
assetId: userComment.assetId,
replyToId: null,
createdAt: { lte: rootComment.createdAt },
id: { notIn: [userComment.id, rootCommentId] },
},
orderBy: { createdAt: 'asc' },
include: { creator: true },
})
const threadReplies = await prisma.assetComment.findMany({
where: {
replyToId: rootCommentId,
id: { not: userComment.id },
},
orderBy: { createdAt: 'asc' },
include: { creator: true },
})
const existingComments = [
...precedingTopLevelComments,
...(rootCommentId !== userComment.id ? [rootComment] : []),
...threadReplies,
]
existingComments.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())
// Check which top-level comments have reply threads (for prompt tagging)
// Resolve user mentions from IDs to names
const mentionRegex = /<@([^>]+)>/g const mentionRegex = /<@([^>]+)>/g
const mentionedUserIds = new Set<string>() const mentionedUserIds = new Set<string>()
for (const c of existingComments) { for (const c of allCommentsToSync) {
if (c.message) { if (c.message) {
const matches = [...c.message.matchAll(mentionRegex)] const matches = [...c.message.matchAll(mentionRegex)]
for (const match of matches) { for (const match of matches) {
@@ -649,25 +587,18 @@ export async function initializeAgentSessionActivity(params: {
const userIdToNameMap = new Map<string, string>() const userIdToNameMap = new Map<string, string>()
if (mentionedUserIds.size > 0) { if (mentionedUserIds.size > 0) {
const resolvedUsers = await prisma.user.findMany({ const resolvedUsers = await prisma.user.findMany({
where: { where: { id: { in: Array.from(mentionedUserIds) } },
id: { in: Array.from(mentionedUserIds) }, select: { id: true, name: true },
},
select: {
id: true,
name: true,
},
}) })
for (const u of resolvedUsers) { for (const u of resolvedUsers) {
if (u.name) { if (u.name) userIdToNameMap.set(u.id, u.name)
userIdToNameMap.set(u.id, u.name)
}
} }
} }
const userRoleMap = new Map<string, string>() const userRoleMap = new Map<string, string>()
const humanCreatorIds = Array.from( const humanCreatorIds = Array.from(
new Set( new Set(
existingComments allCommentsToSync
.filter((c) => c.creator?.type !== 'agent' && c.creatorId) .filter((c) => c.creator?.type !== 'agent' && c.creatorId)
.map((c) => c.creatorId!), .map((c) => c.creatorId!),
), ),
@@ -685,24 +616,10 @@ export async function initializeAgentSessionActivity(params: {
} }
} }
// Save context as AgentSessionEntry records (with parent pointers) function formatCommentMessage(c: (typeof allCommentsToSync)[0]): string {
let prevId: string | null = session.leafId
for (const c of existingComments) {
const entryId = `${c.id}_${sessionId}`
// Check if entry already exists for this comment in this session
const existingEntry = await prisma.agentSessionEntry.findUnique({
where: { id: entryId },
select: { id: true },
})
if (existingEntry) {
prevId = existingEntry.id
continue
}
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null const isAgent = c.creator?.type === 'agent' || c.sessionId !== null
let messageContent = c.message || '' let messageContent = c.message || ''
// Replace <@USER_ID> with <@USER_NAME>
messageContent = messageContent.replace(mentionRegex, (match, userId) => { messageContent = messageContent.replace(mentionRegex, (match, userId) => {
const resolvedName = userIdToNameMap.get(userId) const resolvedName = userIdToNameMap.get(userId)
return resolvedName ? `<@${resolvedName}>` : match return resolvedName ? `<@${resolvedName}>` : match
@@ -710,41 +627,92 @@ export async function initializeAgentSessionActivity(params: {
if (isAgent) { if (isAgent) {
const agentName = c.creator?.name || 'Ai Agent' const agentName = c.creator?.name || 'Ai Agent'
messageContent = `[Agent Message][${agentName}]: ${messageContent}` return `[Agent Message][${agentName}]: ${messageContent}`
} else if (c.creator?.name) { } else if (c.creator?.name) {
const role = (c.creatorId ? userRoleMap.get(c.creatorId) : undefined) || 'user' const role = (c.creatorId ? userRoleMap.get(c.creatorId) : undefined) || 'user'
messageContent = `[${c.creator.name} (${role})]: ${messageContent}` return `[${c.creator.name} (${role})]: ${messageContent}`
} }
return messageContent
const message: AgentMessage = {
role: 'user',
content: [{ type: 'text', text: messageContent }],
timestamp: c.createdAt.getTime(),
}
await prisma.agentSessionEntry.create({
data: {
id: entryId,
sessionId,
assetId: userComment.assetId,
type: 'message',
parentId: prevId,
createdAt: c.createdAt,
data: { message },
},
})
prevId = entryId
} }
// Update leafId of the session // 3. Sync top-level comments into agent_session_entries (DAG spine)
if (prevId && prevId !== session.leafId) { let mainPrevId: string | null = null
for (const c of topLevelComments) {
const existingEntry = await prisma.agentSessionEntry.findUnique({
where: { id: c.id },
select: { id: true },
})
if (!existingEntry) {
const messageContent = formatCommentMessage(c)
const message: AgentMessage = {
role: 'user',
content: [{ type: 'text', text: messageContent }],
timestamp: c.createdAt.getTime(),
}
await prisma.agentSessionEntry.create({
data: {
id: c.id,
sessionId: mainSession.id,
assetId: userComment.assetId,
type: 'message',
parentId: mainPrevId,
createdAt: c.createdAt,
data: { message },
},
})
}
mainPrevId = c.id
}
if (mainPrevId) {
await prisma.agentSession.update({ await prisma.agentSession.update({
where: { id: sessionId }, where: { id: mainSession.id },
data: { leafId: prevId }, data: { leafId: mainPrevId },
}) })
} }
return sessionId // 4. Sync thread replies and set Thread Session leafId
let threadLeafId: string = rootCommentId
if (threadReplies.length > 0) {
let lastReplyParentId: string = rootCommentId
for (const reply of threadReplies) {
const existingReplyEntry = await prisma.agentSessionEntry.findUnique({
where: { id: reply.id },
select: { id: true },
})
if (!existingReplyEntry) {
const messageContent = formatCommentMessage(reply)
const message: AgentMessage = {
role: 'user',
content: [{ type: 'text', text: messageContent }],
timestamp: reply.createdAt.getTime(),
}
await prisma.agentSessionEntry.create({
data: {
id: reply.id,
sessionId: session.id,
assetId: userComment.assetId,
type: 'message',
parentId: lastReplyParentId,
createdAt: reply.createdAt,
data: { message },
},
})
}
lastReplyParentId = reply.id
}
threadLeafId = lastReplyParentId
}
await prisma.agentSession.update({
where: { id: session.id },
data: { leafId: threadLeafId },
})
return session.id
} }
export async function deleteCommentActivity(commentId: string) { export async function deleteCommentActivity(commentId: string) {
@@ -248,12 +248,12 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
} }
// Dynamically tag comments that currently have reply threads // Dynamically tag comments that currently have reply threads
const commentIds = Array.from(new Set(pathEntries.map((e) => e.id.split('_')[0]))) const entryIds = pathEntries.map((e) => e.id)
if (commentIds.length > 0) { if (entryIds.length > 0) {
const threadCounts = await prisma.assetComment.groupBy({ const threadCounts = await prisma.assetComment.groupBy({
by: ['replyToId'], by: ['replyToId'],
where: { where: {
replyToId: { in: commentIds }, replyToId: { in: entryIds },
}, },
}) })
const commentIdsWithThreads = new Set<string>() const commentIdsWithThreads = new Set<string>()
@@ -264,15 +264,14 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
if (commentIdsWithThreads.size > 0) { if (commentIdsWithThreads.size > 0) {
for (let i = 0; i < pathEntries.length; i++) { for (let i = 0; i < pathEntries.length; i++) {
const entry = pathEntries[i] const entry = pathEntries[i]
const baseCommentId = entry.id.split('_')[0] if (commentIdsWithThreads.has(entry.id) && entry.type === 'message') {
if (commentIdsWithThreads.has(baseCommentId) && entry.type === 'message') {
const cloned = structuredClone(entry) const cloned = structuredClone(entry)
const msg = cloned.message as unknown as { const msg = cloned.message as unknown as {
content?: Array<{ type: string; text: string }> content?: Array<{ type: string; text: string }>
} }
if (Array.isArray(msg.content) && msg.content[0] && msg.content[0].type === 'text') { if (Array.isArray(msg.content) && msg.content[0] && msg.content[0].type === 'text') {
if (!msg.content[0].text.startsWith(`[Thread ID: ${baseCommentId}]`)) { if (!msg.content[0].text.startsWith(`[Thread ID: ${entry.id}]`)) {
msg.content[0].text = `[Thread ID: ${baseCommentId}] ${msg.content[0].text}` msg.content[0].text = `[Thread ID: ${entry.id}] ${msg.content[0].text}`
} }
} }
pathEntries[i] = cloned pathEntries[i] = cloned