mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-22 14:08:24 +00:00
fix(agent): implement shared DAG tree entries across comment sessions without entry duplication
This commit is contained in:
@@ -539,15 +539,17 @@ describe('Agent Database Activities Integration', () => {
|
||||
// Verify agentSession created
|
||||
const agentSession = await prisma.agentSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
include: { entries: true },
|
||||
})
|
||||
expect(agentSession).toBeDefined()
|
||||
expect(agentSession?.leafId).toBeDefined()
|
||||
|
||||
// Verify historical comment is converted and saved to entries (mentions replaced, prefixes added)
|
||||
expect(agentSession?.entries.length).toBe(1)
|
||||
// Verify historical comment is converted and saved to DAG entries via path traversal
|
||||
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
|
||||
const parsedEntry = agentSession?.entries[0].data as any
|
||||
const parsedEntry = pathEntries[0] as any
|
||||
expect(parsedEntry.message.content[0].text).toContain(
|
||||
`[${user.name} (owner)]: Hello <@${user.name}> check this`,
|
||||
)
|
||||
@@ -666,13 +668,13 @@ describe('Agent Database Activities Integration', () => {
|
||||
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)
|
||||
await prisma.assetComment.create({
|
||||
const msg1 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg1', creatorId: user.id },
|
||||
})
|
||||
// msg2 (top level)
|
||||
await prisma.assetComment.create({
|
||||
const msg2 = await prisma.assetComment.create({
|
||||
data: { assetId: asset.id, message: 'msg2', creatorId: user.id },
|
||||
})
|
||||
// msg3 (top level asking agent)
|
||||
@@ -689,7 +691,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
|
||||
// agent response msg4
|
||||
await prisma.assetComment.create({
|
||||
const msg4 = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
message: 'msg4',
|
||||
@@ -741,6 +743,34 @@ describe('Agent Database Activities Integration', () => {
|
||||
|
||||
// Reuses session3Id (Thread Session 1)
|
||||
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 () => {
|
||||
|
||||
@@ -517,7 +517,6 @@ export async function initializeAgentSessionActivity(params: {
|
||||
},
|
||||
})
|
||||
}
|
||||
const sessionId = session.id
|
||||
|
||||
const rootComment = await prisma.assetComment.findUnique({
|
||||
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({
|
||||
where: {
|
||||
assetId: userComment.assetId,
|
||||
@@ -558,86 +558,24 @@ export async function initializeAgentSessionActivity(params: {
|
||||
include: { creator: true },
|
||||
})
|
||||
|
||||
let mainPrevId: string | null = mainSession.leafId
|
||||
for (const c of topLevelComments) {
|
||||
const entryId = `${c.id}_${mainSession.id}`
|
||||
const existingEntry = await prisma.agentSessionEntry.findUnique({
|
||||
where: { id: entryId },
|
||||
select: { id: true },
|
||||
})
|
||||
if (existingEntry) {
|
||||
mainPrevId = existingEntry.id
|
||||
continue
|
||||
}
|
||||
// 2. Fetch thread replies up to userComment.createdAt if userComment is in a thread
|
||||
const threadReplies = userComment.replyToId
|
||||
? await prisma.assetComment.findMany({
|
||||
where: {
|
||||
replyToId: rootCommentId,
|
||||
createdAt: { lte: userComment.createdAt },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
include: { creator: true },
|
||||
})
|
||||
: []
|
||||
|
||||
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null
|
||||
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 allCommentsToSync = [...topLevelComments, ...threadReplies]
|
||||
|
||||
const message: AgentMessage = {
|
||||
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
|
||||
// Resolve user mentions from IDs to names and roles
|
||||
const mentionRegex = /<@([^>]+)>/g
|
||||
const mentionedUserIds = new Set<string>()
|
||||
for (const c of existingComments) {
|
||||
for (const c of allCommentsToSync) {
|
||||
if (c.message) {
|
||||
const matches = [...c.message.matchAll(mentionRegex)]
|
||||
for (const match of matches) {
|
||||
@@ -649,25 +587,18 @@ export async function initializeAgentSessionActivity(params: {
|
||||
const userIdToNameMap = new Map<string, string>()
|
||||
if (mentionedUserIds.size > 0) {
|
||||
const resolvedUsers = await prisma.user.findMany({
|
||||
where: {
|
||||
id: { in: Array.from(mentionedUserIds) },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
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)
|
||||
}
|
||||
if (u.name) userIdToNameMap.set(u.id, u.name)
|
||||
}
|
||||
}
|
||||
|
||||
const userRoleMap = new Map<string, string>()
|
||||
const humanCreatorIds = Array.from(
|
||||
new Set(
|
||||
existingComments
|
||||
allCommentsToSync
|
||||
.filter((c) => c.creator?.type !== 'agent' && c.creatorId)
|
||||
.map((c) => c.creatorId!),
|
||||
),
|
||||
@@ -685,24 +616,10 @@ export async function initializeAgentSessionActivity(params: {
|
||||
}
|
||||
}
|
||||
|
||||
// Save context as AgentSessionEntry records (with parent pointers)
|
||||
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
|
||||
}
|
||||
|
||||
function formatCommentMessage(c: (typeof allCommentsToSync)[0]): string {
|
||||
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null
|
||||
let messageContent = c.message || ''
|
||||
|
||||
// Replace <@USER_ID> with <@USER_NAME>
|
||||
messageContent = messageContent.replace(mentionRegex, (match, userId) => {
|
||||
const resolvedName = userIdToNameMap.get(userId)
|
||||
return resolvedName ? `<@${resolvedName}>` : match
|
||||
@@ -710,41 +627,92 @@ export async function initializeAgentSessionActivity(params: {
|
||||
|
||||
if (isAgent) {
|
||||
const agentName = c.creator?.name || 'Ai Agent'
|
||||
messageContent = `[Agent Message][${agentName}]: ${messageContent}`
|
||||
return `[Agent Message][${agentName}]: ${messageContent}`
|
||||
} else if (c.creator?.name) {
|
||||
const role = (c.creatorId ? userRoleMap.get(c.creatorId) : undefined) || 'user'
|
||||
messageContent = `[${c.creator.name} (${role})]: ${messageContent}`
|
||||
return `[${c.creator.name} (${role})]: ${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
|
||||
return messageContent
|
||||
}
|
||||
|
||||
// Update leafId of the session
|
||||
if (prevId && prevId !== session.leafId) {
|
||||
// 3. Sync top-level comments into agent_session_entries (DAG spine)
|
||||
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({
|
||||
where: { id: sessionId },
|
||||
data: { leafId: prevId },
|
||||
where: { id: mainSession.id },
|
||||
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) {
|
||||
|
||||
@@ -248,12 +248,12 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
||||
}
|
||||
|
||||
// Dynamically tag comments that currently have reply threads
|
||||
const commentIds = Array.from(new Set(pathEntries.map((e) => e.id.split('_')[0])))
|
||||
if (commentIds.length > 0) {
|
||||
const entryIds = pathEntries.map((e) => e.id)
|
||||
if (entryIds.length > 0) {
|
||||
const threadCounts = await prisma.assetComment.groupBy({
|
||||
by: ['replyToId'],
|
||||
where: {
|
||||
replyToId: { in: commentIds },
|
||||
replyToId: { in: entryIds },
|
||||
},
|
||||
})
|
||||
const commentIdsWithThreads = new Set<string>()
|
||||
@@ -264,15 +264,14 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
||||
if (commentIdsWithThreads.size > 0) {
|
||||
for (let i = 0; i < pathEntries.length; i++) {
|
||||
const entry = pathEntries[i]
|
||||
const baseCommentId = entry.id.split('_')[0]
|
||||
if (commentIdsWithThreads.has(baseCommentId) && entry.type === 'message') {
|
||||
if (commentIdsWithThreads.has(entry.id) && entry.type === 'message') {
|
||||
const cloned = structuredClone(entry)
|
||||
const msg = cloned.message as unknown as {
|
||||
content?: Array<{ type: string; text: string }>
|
||||
}
|
||||
if (Array.isArray(msg.content) && msg.content[0] && msg.content[0].type === 'text') {
|
||||
if (!msg.content[0].text.startsWith(`[Thread ID: ${baseCommentId}]`)) {
|
||||
msg.content[0].text = `[Thread ID: ${baseCommentId}] ${msg.content[0].text}`
|
||||
if (!msg.content[0].text.startsWith(`[Thread ID: ${entry.id}]`)) {
|
||||
msg.content[0].text = `[Thread ID: ${entry.id}] ${msg.content[0].text}`
|
||||
}
|
||||
}
|
||||
pathEntries[i] = cloned
|
||||
|
||||
Reference in New Issue
Block a user