From b75e0c7fdcd48ee6d22be5cd07b9b3a071e0565d Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 29 Jul 2026 11:07:47 +0800 Subject: [PATCH] fix(agent): scope agent comment sessions to thread sessions anchored at root comments --- packages/agent/src/activities/agent.test.ts | 132 ++++++++-- packages/agent/src/activities/agent.ts | 236 +++++++++--------- .../agent/src/database-session-storage.ts | 13 +- 3 files changed, 229 insertions(+), 152 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index aedf0ab6..aa5c8483 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -572,48 +572,49 @@ describe('Agent Database Activities Integration', () => { }, }) - // 3. Initialize session for mention on mainComment2 (Main Session) - const mainSessionId = await initializeAgentSessionActivity({ + // 3. Initialize session for mention on mainComment2 (creates Thread Session for mainComment2) + const threadSession2Id = await initializeAgentSessionActivity({ teamId: team.id, agentId: 'test-agent-id', userCommentId: mainComment2.id, userId: user.id, }) - const mainSession = await prisma.agentSession.findUnique({ - where: { id: mainSessionId }, + const threadSession2 = await prisma.agentSession.findUnique({ + 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 const mainEntries = await prisma.agentSessionEntry.findMany({ - where: { sessionId: mainSessionId }, + where: { sessionId: mainSession!.id }, orderBy: { createdAt: 'asc' }, }) - // Main session contains mainComment1, but NOT threadReply1 - expect(mainEntries.length).toBe(1) - expect(mainEntries[0].id).toBe(mainComment1.id) + // Main session contains mainComment1 and mainComment2, but NOT threadReply1 + expect(mainEntries.length).toBe(2) + expect(mainEntries[0].id).toContain(mainComment1.id) + expect(mainEntries[1].id).toContain(mainComment2.id) - const mainStorage = new DatabaseSessionStorage(mainSessionId) - const mainLeafId = await mainStorage.getLeafId() - 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({ + // 4. Initialize session for mention on threadReply1 (Thread Session for mainComment1) + const threadSession1Id = await initializeAgentSessionActivity({ teamId: team.id, agentId: 'test-agent-id', userCommentId: threadReply1.id, userId: user.id, }) - const threadSession = await prisma.agentSession.findUnique({ - where: { id: threadSessionId }, + const threadSession1 = await prisma.agentSession.findUnique({ + 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 () => { @@ -621,7 +622,7 @@ describe('Agent Database Activities Integration', () => { data: { assetId: asset.id, message: 'Question in msg3', creatorId: user.id }, }) - const session1Id = await initializeAgentSessionActivity({ + await initializeAgentSessionActivity({ teamId: team.id, agentId: 'test-agent-id', userCommentId: msg3.id, @@ -648,17 +649,100 @@ describe('Agent Database Activities Integration', () => { 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 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() // eslint-disable-next-line @typescript-eslint/no-explicit-any const text = (msg3Entry as any).message.content[0].text 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 () => { const info = await getUserTeamInfoActivity({ userId: user.id, diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index 365d1092..20f2c55f 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -1,7 +1,7 @@ import { - type AgentMessage, - type AgentTool, - type SessionTreeEntry, + type AgentMessage, + type AgentTool, + type SessionTreeEntry, } from '@earendil-works/pi-agent-core' import { type ImageContent } from '@earendil-works/pi-ai' import { assetService } from '@shumai/core/src/asset/asset' @@ -19,10 +19,10 @@ import { generateKeyBetween } from 'jittered-fractional-indexing' import { ulid } from 'ulid' import { DatabaseSessionStorage } from '../database-session-storage' import { - createAgentSession, - fieldsToTypeBoxSchema, - type AutofillField, - type DbProviderInfo, + createAgentSession, + fieldsToTypeBoxSchema, + type AutofillField, + type DbProviderInfo, } from '../index' 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`) } - const isThread = !!userComment.replyToId const rootCommentId = userComment.replyToId || userComment.id - const targetUserCommentId = isThread ? rootCommentId : null + const targetUserCommentId = rootCommentId let session = await prisma.agentSession.findFirst({ where: { @@ -520,127 +519,120 @@ export async function initializeAgentSessionActivity(params: { } const sessionId = session.id - // If this is a Thread Session, ensure preceding top-level comments up to rootCommentId are synced in Main Session first - if (isThread) { - let mainSession = await prisma.agentSession.findFirst({ - where: { + const rootComment = await prisma.assetComment.findUnique({ + where: { id: rootCommentId }, + include: { creator: true }, + }) + 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, - type: 'comment', 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 - let existingComments: Array<{ - id: string - message: string | null - createdAt: Date - creatorId: string | null - creator: { type: string; name: string } | null - sessionId: string | null - replyToId: string | null - }> = [] + const topLevelComments = await prisma.assetComment.findMany({ + where: { + assetId: userComment.assetId, + replyToId: null, + createdAt: { lte: rootComment.createdAt }, + }, + orderBy: { createdAt: 'asc' }, + include: { creator: true }, + }) - if (!isThread) { - // Main Session: Only fetch top-level comments (replyToId: null) - existingComments = await prisma.assetComment.findMany({ - where: { - assetId: userComment.assetId, - replyToId: null, - id: { not: userComment.id }, - }, - orderBy: { createdAt: 'asc' }, - 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 }, }) - } else { - // Thread Session: Fetch root comment + replies in this specific thread (replyToId: rootCommentId) - const rootComment = await prisma.assetComment.findUnique({ - 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] + 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 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 const mentionRegex = /<@([^>]+)>/g @@ -696,9 +688,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) { - // 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({ - where: { id: c.id }, + where: { id: entryId }, select: { id: true }, }) if (existingEntry) { @@ -723,7 +716,6 @@ export async function initializeAgentSessionActivity(params: { messageContent = `[${c.creator.name} (${role})]: ${messageContent}` } - const entryId = c.id const message: AgentMessage = { role: 'user', content: [{ type: 'text', text: messageContent }], diff --git a/packages/agent/src/database-session-storage.ts b/packages/agent/src/database-session-storage.ts index b02fa7d7..28d167d9 100644 --- a/packages/agent/src/database-session-storage.ts +++ b/packages/agent/src/database-session-storage.ts @@ -248,12 +248,12 @@ export class DatabaseSessionStorage implements SessionStorage e.id) - if (entryIds.length > 0) { + const commentIds = Array.from(new Set(pathEntries.map((e) => e.id.split('_')[0]))) + if (commentIds.length > 0) { const threadCounts = await prisma.assetComment.groupBy({ by: ['replyToId'], where: { - replyToId: { in: entryIds }, + replyToId: { in: commentIds }, }, }) const commentIdsWithThreads = new Set() @@ -264,14 +264,15 @@ export class DatabaseSessionStorage implements SessionStorage 0) { for (let i = 0; i < pathEntries.length; 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 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: ${entry.id}]`)) { - msg.content[0].text = `[Thread ID: ${entry.id}] ${msg.content[0].text}` + if (!msg.content[0].text.startsWith(`[Thread ID: ${baseCommentId}]`)) { + msg.content[0].text = `[Thread ID: ${baseCommentId}] ${msg.content[0].text}` } } pathEntries[i] = cloned