fix(agent): scope agent comment sessions to thread sessions anchored at root comments

This commit is contained in:
yiling
2026-07-29 11:07:47 +08:00
parent d8c3f46a8d
commit b75e0c7fdc
3 changed files with 229 additions and 152 deletions
+108 -24
View File
@@ -572,48 +572,49 @@ describe('Agent Database Activities Integration', () => {
}, },
}) })
// 3. Initialize session for mention on mainComment2 (Main Session) // 3. Initialize session for mention on mainComment2 (creates Thread Session for mainComment2)
const mainSessionId = await initializeAgentSessionActivity({ const threadSession2Id = await initializeAgentSessionActivity({
teamId: team.id, teamId: team.id,
agentId: 'test-agent-id', agentId: 'test-agent-id',
userCommentId: mainComment2.id, userCommentId: mainComment2.id,
userId: user.id, userId: user.id,
}) })
const mainSession = await prisma.agentSession.findUnique({ const threadSession2 = await prisma.agentSession.findUnique({
where: { id: mainSessionId }, where: { id: threadSession2Id },
}) })
expect(mainSession?.userCommentId).toBeNull() // Main Session has userCommentId = null expect(threadSession2?.userCommentId).toBe(mainComment2.id)
// Main Session (userCommentId: null) is created during lazy sync
const mainSession = await prisma.agentSession.findFirst({
where: { assetId: asset.id, type: 'comment', userCommentId: null },
})
expect(mainSession).toBeDefined()
expect(mainSession?.userCommentId).toBeNull()
// Retrieve main session entries // Retrieve main session entries
const mainEntries = await prisma.agentSessionEntry.findMany({ const mainEntries = await prisma.agentSessionEntry.findMany({
where: { sessionId: mainSessionId }, where: { sessionId: mainSession!.id },
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
}) })
// Main session contains mainComment1, but NOT threadReply1 // Main session contains mainComment1 and mainComment2, but NOT threadReply1
expect(mainEntries.length).toBe(1) expect(mainEntries.length).toBe(2)
expect(mainEntries[0].id).toBe(mainComment1.id) expect(mainEntries[0].id).toContain(mainComment1.id)
expect(mainEntries[1].id).toContain(mainComment2.id)
const mainStorage = new DatabaseSessionStorage(mainSessionId) // 4. Initialize session for mention on threadReply1 (Thread Session for mainComment1)
const mainLeafId = await mainStorage.getLeafId() const threadSession1Id = await initializeAgentSessionActivity({
const mainPath = await mainStorage.getPathToRoot(mainLeafId)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mainText = (mainPath[0] as any).message.content[0].text
expect(mainText).toContain(`[Thread ID: ${mainComment1.id}]`)
// 4. Initialize session for mention on threadReply1 (Thread Session)
const threadSessionId = await initializeAgentSessionActivity({
teamId: team.id, teamId: team.id,
agentId: 'test-agent-id', agentId: 'test-agent-id',
userCommentId: threadReply1.id, userCommentId: threadReply1.id,
userId: user.id, userId: user.id,
}) })
const threadSession = await prisma.agentSession.findUnique({ const threadSession1 = await prisma.agentSession.findUnique({
where: { id: threadSessionId }, where: { id: threadSession1Id },
}) })
expect(threadSession?.userCommentId).toBe(mainComment1.id) // Thread Session has userCommentId = rootComment.id expect(threadSession1?.userCommentId).toBe(mainComment1.id) // Thread Session has userCommentId = rootComment.id
}) })
it('should dynamically tag top-level comments with [Thread ID: id] even if thread was created after initial sync', async () => { it('should dynamically tag top-level comments with [Thread ID: id] even if thread was created after initial sync', async () => {
@@ -621,7 +622,7 @@ describe('Agent Database Activities Integration', () => {
data: { assetId: asset.id, message: 'Question in msg3', creatorId: user.id }, data: { assetId: asset.id, message: 'Question in msg3', creatorId: user.id },
}) })
const session1Id = await initializeAgentSessionActivity({ await initializeAgentSessionActivity({
teamId: team.id, teamId: team.id,
agentId: 'test-agent-id', agentId: 'test-agent-id',
userCommentId: msg3.id, userCommentId: msg3.id,
@@ -648,17 +649,100 @@ describe('Agent Database Activities Integration', () => {
userId: user.id, userId: user.id,
}) })
const storage = new DatabaseSessionStorage(session1Id) // Check main session where top-level comments are stored
const mainSession = await prisma.agentSession.findFirst({
where: { assetId: asset.id, type: 'comment', userCommentId: null },
})
expect(mainSession).toBeDefined()
const storage = new DatabaseSessionStorage(mainSession!.id)
const leafId = await storage.getLeafId() const leafId = await storage.getLeafId()
const pathEntries = await storage.getPathToRoot(leafId) const pathEntries = await storage.getPathToRoot(leafId)
const msg3Entry = pathEntries.find((e) => e.id === msg3.id) const msg3Entry = pathEntries.find((e) => e.id.includes(msg3.id))
expect(msg3Entry).toBeDefined() expect(msg3Entry).toBeDefined()
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const text = (msg3Entry as any).message.content[0].text const text = (msg3Entry as any).message.content[0].text
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 () => {
// msg1 (top level)
await prisma.assetComment.create({
data: { assetId: asset.id, message: 'msg1', creatorId: user.id },
})
// msg2 (top level)
await prisma.assetComment.create({
data: { assetId: asset.id, message: 'msg2', creatorId: user.id },
})
// msg3 (top level asking agent)
const msg3 = await prisma.assetComment.create({
data: { assetId: asset.id, message: '[ask agent] msg3', creatorId: user.id },
})
// Initialize session for msg3
const session3Id = await initializeAgentSessionActivity({
teamId: team.id,
agentId: 'test-agent-id',
userCommentId: msg3.id,
userId: user.id,
})
// agent response msg4
await prisma.assetComment.create({
data: {
assetId: asset.id,
message: 'msg4',
creatorId: 'test-agent-id',
replyToId: msg3.id,
sessionId: session3Id,
},
})
// msg5 (top level asking agent)
const msg5 = await prisma.assetComment.create({
data: { assetId: asset.id, message: '[ask agent] msg5', creatorId: user.id },
})
// Initialize session for msg5
const session5Id = await initializeAgentSessionActivity({
teamId: team.id,
agentId: 'test-agent-id',
userCommentId: msg5.id,
userId: user.id,
})
const session3 = await prisma.agentSession.findUnique({ where: { id: session3Id } })
const session5 = await prisma.agentSession.findUnique({ where: { id: session5Id } })
// Thread Session 1 anchored at msg3.id
expect(session3?.userCommentId).toBe(msg3.id)
// Thread Session 2 anchored at msg5.id
expect(session5?.userCommentId).toBe(msg5.id)
// They should be distinct sessions
expect(session3Id).not.toBe(session5Id)
// msg7 (reply to msg3 asking agent again)
const msg7 = await prisma.assetComment.create({
data: {
assetId: asset.id,
message: '[ask agent again] msg7',
creatorId: user.id,
replyToId: msg3.id,
},
})
const session7Id = await initializeAgentSessionActivity({
teamId: team.id,
agentId: 'test-agent-id',
userCommentId: msg7.id,
userId: user.id,
})
// Reuses session3Id (Thread Session 1)
expect(session7Id).toBe(session3Id)
})
it('should return user name and role for team member', async () => { it('should return user name and role for team member', async () => {
const info = await getUserTeamInfoActivity({ const info = await getUserTeamInfoActivity({
userId: user.id, userId: user.id,
+114 -122
View File
@@ -1,7 +1,7 @@
import { import {
type AgentMessage, type AgentMessage,
type AgentTool, type AgentTool,
type SessionTreeEntry, type SessionTreeEntry,
} from '@earendil-works/pi-agent-core' } from '@earendil-works/pi-agent-core'
import { type ImageContent } from '@earendil-works/pi-ai' import { type ImageContent } from '@earendil-works/pi-ai'
import { assetService } from '@shumai/core/src/asset/asset' import { assetService } from '@shumai/core/src/asset/asset'
@@ -19,10 +19,10 @@ import { generateKeyBetween } from 'jittered-fractional-indexing'
import { ulid } from 'ulid' import { ulid } from 'ulid'
import { DatabaseSessionStorage } from '../database-session-storage' import { DatabaseSessionStorage } from '../database-session-storage'
import { import {
createAgentSession, createAgentSession,
fieldsToTypeBoxSchema, fieldsToTypeBoxSchema,
type AutofillField, type AutofillField,
type DbProviderInfo, type DbProviderInfo,
} from '../index' } from '../index'
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage' import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
@@ -494,9 +494,8 @@ export async function initializeAgentSessionActivity(params: {
throw new Error(`User comment ${params.userCommentId} not found`) throw new Error(`User comment ${params.userCommentId} not found`)
} }
const isThread = !!userComment.replyToId
const rootCommentId = userComment.replyToId || userComment.id const rootCommentId = userComment.replyToId || userComment.id
const targetUserCommentId = isThread ? rootCommentId : null const targetUserCommentId = rootCommentId
let session = await prisma.agentSession.findFirst({ let session = await prisma.agentSession.findFirst({
where: { where: {
@@ -520,127 +519,120 @@ export async function initializeAgentSessionActivity(params: {
} }
const sessionId = session.id const sessionId = session.id
// If this is a Thread Session, ensure preceding top-level comments up to rootCommentId are synced in Main Session first const rootComment = await prisma.assetComment.findUnique({
if (isThread) { where: { id: rootCommentId },
let mainSession = await prisma.agentSession.findFirst({ include: { creator: true },
where: { })
if (!rootComment) {
throw new Error(`Root comment ${rootCommentId} not found`)
}
// Ensure preceding top-level comments up to rootCommentId are synced in Main Session first
let mainSession = await prisma.agentSession.findFirst({
where: {
assetId: userComment.assetId,
type: 'comment',
userCommentId: null,
},
})
if (!mainSession) {
mainSession = await prisma.agentSession.create({
data: {
agentId,
userId: params.userId || null,
cwd: process.cwd(),
assetId: userComment.assetId, assetId: userComment.assetId,
type: 'comment',
userCommentId: null, userCommentId: null,
type: 'comment',
}, },
}) })
if (!mainSession) {
mainSession = await prisma.agentSession.create({
data: {
agentId,
userId: params.userId || null,
cwd: process.cwd(),
assetId: userComment.assetId,
userCommentId: null,
type: 'comment',
},
})
}
const topLevelComments = await prisma.assetComment.findMany({
where: {
assetId: userComment.assetId,
replyToId: null,
createdAt: { lte: userComment.createdAt },
},
orderBy: { createdAt: 'asc' },
include: { creator: true },
})
let mainPrevId: string | null = mainSession.leafId
for (const c of topLevelComments) {
const existingEntry = await prisma.agentSessionEntry.findUnique({
where: { id: c.id },
select: { id: true },
})
if (existingEntry) {
mainPrevId = existingEntry.id
continue
}
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 entryId = c.id
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 current session const topLevelComments = await prisma.assetComment.findMany({
let existingComments: Array<{ where: {
id: string assetId: userComment.assetId,
message: string | null replyToId: null,
createdAt: Date createdAt: { lte: rootComment.createdAt },
creatorId: string | null },
creator: { type: string; name: string } | null orderBy: { createdAt: 'asc' },
sessionId: string | null include: { creator: true },
replyToId: string | null })
}> = []
if (!isThread) { let mainPrevId: string | null = mainSession.leafId
// Main Session: Only fetch top-level comments (replyToId: null) for (const c of topLevelComments) {
existingComments = await prisma.assetComment.findMany({ const entryId = `${c.id}_${mainSession.id}`
where: { const existingEntry = await prisma.agentSessionEntry.findUnique({
assetId: userComment.assetId, where: { id: entryId },
replyToId: null, select: { id: true },
id: { not: userComment.id },
},
orderBy: { createdAt: 'asc' },
include: { creator: true },
}) })
} else { if (existingEntry) {
// Thread Session: Fetch root comment + replies in this specific thread (replyToId: rootCommentId) mainPrevId = existingEntry.id
const rootComment = await prisma.assetComment.findUnique({ continue
where: { id: rootCommentId },
include: { creator: true },
})
if (rootComment) {
const replies = await prisma.assetComment.findMany({
where: {
replyToId: rootCommentId,
id: { not: userComment.id },
},
orderBy: { createdAt: 'asc' },
include: { creator: true },
})
existingComments = [rootComment, ...replies]
} }
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 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) // 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
const mentionRegex = /<@([^>]+)>/g const mentionRegex = /<@([^>]+)>/g
@@ -696,9 +688,10 @@ export async function initializeAgentSessionActivity(params: {
// Save context as AgentSessionEntry records (with parent pointers) // Save context as AgentSessionEntry records (with parent pointers)
let prevId: string | null = session.leafId let prevId: string | null = session.leafId
for (const c of existingComments) { for (const c of existingComments) {
// Check if entry already exists for this comment const entryId = `${c.id}_${sessionId}`
// Check if entry already exists for this comment in this session
const existingEntry = await prisma.agentSessionEntry.findUnique({ const existingEntry = await prisma.agentSessionEntry.findUnique({
where: { id: c.id }, where: { id: entryId },
select: { id: true }, select: { id: true },
}) })
if (existingEntry) { if (existingEntry) {
@@ -723,7 +716,6 @@ export async function initializeAgentSessionActivity(params: {
messageContent = `[${c.creator.name} (${role})]: ${messageContent}` messageContent = `[${c.creator.name} (${role})]: ${messageContent}`
} }
const entryId = c.id
const message: AgentMessage = { const message: AgentMessage = {
role: 'user', role: 'user',
content: [{ type: 'text', text: messageContent }], content: [{ type: 'text', text: messageContent }],
@@ -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 entryIds = pathEntries.map((e) => e.id) const commentIds = Array.from(new Set(pathEntries.map((e) => e.id.split('_')[0])))
if (entryIds.length > 0) { if (commentIds.length > 0) {
const threadCounts = await prisma.assetComment.groupBy({ const threadCounts = await prisma.assetComment.groupBy({
by: ['replyToId'], by: ['replyToId'],
where: { where: {
replyToId: { in: entryIds }, replyToId: { in: commentIds },
}, },
}) })
const commentIdsWithThreads = new Set<string>() const commentIdsWithThreads = new Set<string>()
@@ -264,14 +264,15 @@ 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]
if (commentIdsWithThreads.has(entry.id) && entry.type === 'message') { const baseCommentId = entry.id.split('_')[0]
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: ${entry.id}]`)) { if (!msg.content[0].text.startsWith(`[Thread ID: ${baseCommentId}]`)) {
msg.content[0].text = `[Thread ID: ${entry.id}] ${msg.content[0].text}` msg.content[0].text = `[Thread ID: ${baseCommentId}] ${msg.content[0].text}`
} }
} }
pathEntries[i] = cloned pathEntries[i] = cloned