From b75e0c7fdcd48ee6d22be5cd07b9b3a071e0565d Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 29 Jul 2026 11:07:47 +0800 Subject: [PATCH 1/9] 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 From 343750e17862efec85ef20ee2d08e7bedf16c866 Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 29 Jul 2026 11:21:55 +0800 Subject: [PATCH 2/9] fix(agent): implement shared DAG tree entries across comment sessions without entry duplication --- packages/agent/src/activities/agent.test.ts | 46 +++- packages/agent/src/activities/agent.ts | 226 ++++++++---------- .../agent/src/database-session-storage.ts | 13 +- 3 files changed, 141 insertions(+), 144 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index aa5c8483..096edebd 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -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 () => { diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index 20f2c55f..c7545c99 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -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() - 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() 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() 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) { diff --git a/packages/agent/src/database-session-storage.ts b/packages/agent/src/database-session-storage.ts index 28d167d9..b02fa7d7 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.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() @@ -264,15 +264,14 @@ export class DatabaseSessionStorage implements SessionStorage 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 From acb64f44bb10a6a3c461c62c1b15db3a06d70735 Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 29 Jul 2026 11:33:26 +0800 Subject: [PATCH 3/9] fix(agent): prevent userComment entry duplication by passing userCommentId as active prompt entry ID --- packages/agent/src/activities/agent.test.ts | 56 +++++++++++++++---- packages/agent/src/activities/agent.ts | 8 ++- .../agent/src/database-session-storage.ts | 7 +++ packages/agent/src/index.ts | 3 + 4 files changed, 60 insertions(+), 14 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index 096edebd..a9997d19 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -546,7 +546,7 @@ describe('Agent Database Activities Integration', () => { // 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) + expect(pathEntries.length).toBe(1) // 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 = pathEntries[0] as any @@ -594,16 +594,15 @@ describe('Agent Database Activities Integration', () => { expect(mainSession).toBeDefined() expect(mainSession?.userCommentId).toBeNull() - // Retrieve main session entries + // Retrieve main session entries (contains top-level comments prior to mainComment2) const mainEntries = await prisma.agentSessionEntry.findMany({ where: { sessionId: mainSession!.id }, orderBy: { createdAt: 'asc' }, }) - // Main session contains mainComment1 and mainComment2, but NOT threadReply1 - expect(mainEntries.length).toBe(2) + // Main session contains mainComment1, but NOT threadReply1 or mainComment2 (which is appended by piAgent.prompt) + expect(mainEntries.length).toBe(1) expect(mainEntries[0].id).toContain(mainComment1.id) - expect(mainEntries[1].id).toContain(mainComment2.id) // 4. Initialize session for mention on threadReply1 (Thread Session for mainComment1) const threadSession1Id = await initializeAgentSessionActivity({ @@ -748,10 +747,8 @@ describe('Agent Database Activities Integration', () => { // 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) @@ -759,20 +756,57 @@ describe('Agent Database Activities Integration', () => { 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 path5 = await storage5.getPathToRoot(session5!.leafId!) 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 set thread session leafId to preceding comment so userComment is not pre-inserted before piAgent.prompt runs', async () => { + // msg1 (top level) + const msg1 = await prisma.assetComment.create({ + data: { assetId: asset.id, message: 'msg1', creatorId: user.id }, + }) + // msg2 (top level) + const msg2 = 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: '<@shumai-x1> what did i say', creatorId: user.id }, + }) + + const sessionId = await initializeAgentSessionActivity({ + teamId: team.id, + agentId: 'test-agent-id', + userCommentId: msg3.id, + userId: user.id, + }) + + const threadSession = await prisma.agentSession.findUnique({ + where: { id: sessionId }, + }) + + // The leafId for the thread session MUST be msg2.id (preceding comment), NOT msg3.id, + // because piAgent.prompt(msg3.message) will append msg3 as the active user message prompt. + expect(threadSession?.leafId).toBe(msg2.id) + + const storage = new DatabaseSessionStorage(sessionId) + const pathEntries = await storage.getPathToRoot(threadSession!.leafId) + const pathIds = pathEntries.map((e) => e.id) + + // Context history before prompt runs contains msg1 and msg2 + expect(pathIds).toContain(msg1.id) + expect(pathIds).toContain(msg2.id) + // msg3 is not pre-inserted in the session history prior to piAgent.prompt running + expect(pathIds).not.toContain(msg3.id) + }) + 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 c7545c99..2f49145e 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -547,23 +547,25 @@ export async function initializeAgentSessionActivity(params: { }) } - // 1. Fetch top-level comments up to rootComment.createdAt + // 1. Fetch top-level comments up to rootComment.createdAt excluding userComment itself const topLevelComments = await prisma.assetComment.findMany({ where: { assetId: userComment.assetId, replyToId: null, createdAt: { lte: rootComment.createdAt }, + id: { not: userComment.id }, }, orderBy: { createdAt: 'asc' }, include: { creator: true }, }) - // 2. Fetch thread replies up to userComment.createdAt if userComment is in a thread + // 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: { createdAt: 'asc' }, include: { creator: true }, @@ -673,7 +675,7 @@ export async function initializeAgentSessionActivity(params: { } // 4. Sync thread replies and set Thread Session leafId - let threadLeafId: string = rootCommentId + let threadLeafId: string | null = userComment.replyToId ? rootCommentId : mainPrevId if (threadReplies.length > 0) { let lastReplyParentId: string = rootCommentId diff --git a/packages/agent/src/database-session-storage.ts b/packages/agent/src/database-session-storage.ts index b02fa7d7..53fce83b 100644 --- a/packages/agent/src/database-session-storage.ts +++ b/packages/agent/src/database-session-storage.ts @@ -71,7 +71,14 @@ export class DatabaseSessionStorage implements SessionStorage { + if (this.nextEntryId) { + const id = this.nextEntryId + this.nextEntryId = null + return id + } return ulid() } diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index 4740676e..9046c26a 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -135,6 +135,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) { sessionId, cwd: process.cwd(), }) + if (passedUserCommentId) { + storage.nextEntryId = passedUserCommentId + } const session = new Session(storage) const agentDir = path.join(process.cwd(), '.pi', 'agents', agentId) From 952323decaca81239cb047a0f370fb42345956a0 Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 29 Jul 2026 11:52:18 +0800 Subject: [PATCH 4/9] fix(agent): include top-level comment entries in Main Session DAG timeline --- packages/agent/src/activities/agent.test.ts | 59 +++++++++++++++++---- packages/agent/src/activities/agent.ts | 5 +- 2 files changed, 50 insertions(+), 14 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index a9997d19..eff3ade1 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -546,7 +546,7 @@ describe('Agent Database Activities Integration', () => { // 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(1) + 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 = pathEntries[0] as any @@ -594,15 +594,16 @@ describe('Agent Database Activities Integration', () => { expect(mainSession).toBeDefined() expect(mainSession?.userCommentId).toBeNull() - // Retrieve main session entries (contains top-level comments prior to mainComment2) + // Retrieve main session entries (contains top-level comments mainComment1 and mainComment2) const mainEntries = await prisma.agentSessionEntry.findMany({ where: { sessionId: mainSession!.id }, orderBy: { createdAt: 'asc' }, }) - // Main session contains mainComment1, but NOT threadReply1 or mainComment2 (which is appended by piAgent.prompt) - expect(mainEntries.length).toBe(1) + // 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) // 4. Initialize session for mention on threadReply1 (Thread Session for mainComment1) const threadSession1Id = await initializeAgentSessionActivity({ @@ -767,7 +768,7 @@ describe('Agent Database Activities Integration', () => { expect(path5Ids).not.toContain(msg4.id) }) - it('should set thread session leafId to preceding comment so userComment is not pre-inserted before piAgent.prompt runs', async () => { + it('should set thread session leafId to rootComment.id including preceding top-level comments', async () => { // msg1 (top level) const msg1 = await prisma.assetComment.create({ data: { assetId: asset.id, message: 'msg1', creatorId: user.id }, @@ -792,19 +793,55 @@ describe('Agent Database Activities Integration', () => { where: { id: sessionId }, }) - // The leafId for the thread session MUST be msg2.id (preceding comment), NOT msg3.id, - // because piAgent.prompt(msg3.message) will append msg3 as the active user message prompt. - expect(threadSession?.leafId).toBe(msg2.id) + // The leafId for the thread session is msg3.id + expect(threadSession?.leafId).toBe(msg3.id) const storage = new DatabaseSessionStorage(sessionId) const pathEntries = await storage.getPathToRoot(threadSession!.leafId) const pathIds = pathEntries.map((e) => e.id) - // Context history before prompt runs contains msg1 and msg2 + // Context history contains msg1, msg2, and msg3 expect(pathIds).toContain(msg1.id) expect(pathIds).toContain(msg2.id) - // msg3 is not pre-inserted in the session history prior to piAgent.prompt running - expect(pathIds).not.toContain(msg3.id) + expect(pathIds).toContain(msg3.id) + }) + + it('should include top-level agent mention comment in Main Session top-level DAG timeline', async () => { + // msg1 (top level) + const msg1 = await prisma.assetComment.create({ + data: { assetId: asset.id, message: 'msg1', creatorId: user.id }, + }) + // msg2 (top level) + const msg2 = 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: '<@shumai-x1> what did i say', creatorId: user.id }, + }) + + await initializeAgentSessionActivity({ + teamId: team.id, + agentId: 'test-agent-id', + userCommentId: msg3.id, + userId: user.id, + }) + + const mainSession = await prisma.agentSession.findFirst({ + where: { assetId: asset.id, type: 'comment', userCommentId: null }, + }) + expect(mainSession).toBeDefined() + // Main session leafId MUST be msg3.id (top-level comment asking agent) + expect(mainSession?.leafId).toBe(msg3.id) + + const storage = new DatabaseSessionStorage(mainSession!.id) + const mainPath = await storage.getPathToRoot(mainSession!.leafId) + const mainPathIds = mainPath.map((e) => e.id) + + // Main session contains all top-level comments including msg3 + expect(mainPathIds).toContain(msg1.id) + expect(mainPathIds).toContain(msg2.id) + expect(mainPathIds).toContain(msg3.id) }) it('should return user name and role for team member', async () => { diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index 2f49145e..344c8f63 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -547,13 +547,12 @@ export async function initializeAgentSessionActivity(params: { }) } - // 1. Fetch top-level comments up to rootComment.createdAt excluding userComment itself + // 1. Fetch top-level comments up to rootComment.createdAt const topLevelComments = await prisma.assetComment.findMany({ where: { assetId: userComment.assetId, replyToId: null, createdAt: { lte: rootComment.createdAt }, - id: { not: userComment.id }, }, orderBy: { createdAt: 'asc' }, include: { creator: true }, @@ -675,7 +674,7 @@ export async function initializeAgentSessionActivity(params: { } // 4. Sync thread replies and set Thread Session leafId - let threadLeafId: string | null = userComment.replyToId ? rootCommentId : mainPrevId + let threadLeafId: string = rootCommentId if (threadReplies.length > 0) { let lastReplyParentId: string = rootCommentId From 41622f45b4854db1c8f483560a0d2a34941dc5eb Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 29 Jul 2026 11:56:11 +0800 Subject: [PATCH 5/9] fix(agent): use upsert in DatabaseSessionStorage appendEntry to handle existing entry IDs --- packages/agent/src/activities/agent.test.ts | 34 +++++++++++++++++++ .../agent/src/database-session-storage.ts | 8 +++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index eff3ade1..11f44904 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -844,6 +844,40 @@ describe('Agent Database Activities Integration', () => { expect(mainPathIds).toContain(msg3.id) }) + it('should safely upsert entry without unique constraint error when appendEntry is called for pre-existing userComment.id', async () => { + const msg3 = await prisma.assetComment.create({ + data: { assetId: asset.id, message: '<@shumai-x1> what did i say', creatorId: user.id }, + }) + + const sessionId = await initializeAgentSessionActivity({ + teamId: team.id, + agentId: 'test-agent-id', + userCommentId: msg3.id, + userId: user.id, + }) + + const storage = new DatabaseSessionStorage(sessionId) + storage.nextEntryId = msg3.id + + const entryId = await storage.createEntryId() + expect(entryId).toBe(msg3.id) + + // appendEntry should upsert msg3.id without throwing unique constraint error + await expect( + storage.appendEntry({ + id: entryId, + type: 'message', + parentId: null, + timestamp: new Date().toISOString(), + message: { + role: 'user', + content: [{ type: 'text', text: 'Updated content' }], + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- testing mock entry casting + } as any), + ).resolves.not.toThrow() + }) + it('should return user name and role for team member', async () => { const info = await getUserTeamInfoActivity({ userId: user.id, diff --git a/packages/agent/src/database-session-storage.ts b/packages/agent/src/database-session-storage.ts index 53fce83b..a60ddeda 100644 --- a/packages/agent/src/database-session-storage.ts +++ b/packages/agent/src/database-session-storage.ts @@ -154,8 +154,9 @@ export class DatabaseSessionStorage implements SessionStorage Date: Wed, 29 Jul 2026 12:05:46 +0800 Subject: [PATCH 6/9] feat(webui): display session entry ID in Agent Session Logs dialog --- .../agent/agent-session-logs-dialog.tsx | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/packages/webui/components/agent/agent-session-logs-dialog.tsx b/packages/webui/components/agent/agent-session-logs-dialog.tsx index 18df764a..2a720da4 100644 --- a/packages/webui/components/agent/agent-session-logs-dialog.tsx +++ b/packages/webui/components/agent/agent-session-logs-dialog.tsx @@ -296,12 +296,20 @@ export function AgentSessionLogsDialog({
- - {roleName} - - +
+ + {roleName} + + + ID: {entry.id} + +
+ {timestamp}
@@ -319,7 +327,15 @@ export function AgentSessionLogsDialog({
-
{timestamp}
+
+ + ID: {entry.id} + +
{timestamp}
+
                         {JSON.stringify(entry.entry, null, 2)}
                       
From 1c7a87488bd19be4b8dfabc1f4221ad1af823a7e Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 29 Jul 2026 14:59:48 +0800 Subject: [PATCH 7/9] refactor(agent): optimize ULID id sorting and exclude __CHAT__ placeholder comments --- packages/agent/src/activities/agent.test.ts | 33 ++++++++++++++++++- packages/agent/src/activities/agent.ts | 6 ++-- .../agent/src/database-session-storage.ts | 1 + packages/agent/src/tools/read-thread.ts | 7 ++-- 4 files changed, 41 insertions(+), 6 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index 11f44904..55ed2716 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -597,7 +597,7 @@ describe('Agent Database Activities Integration', () => { // Retrieve main session entries (contains top-level comments mainComment1 and mainComment2) const mainEntries = await prisma.agentSessionEntry.findMany({ where: { sessionId: mainSession!.id }, - orderBy: { createdAt: 'asc' }, + orderBy: { id: 'asc' }, }) // Main session contains mainComment1 and mainComment2, but NOT threadReply1 @@ -878,6 +878,37 @@ describe('Agent Database Activities Integration', () => { ).resolves.not.toThrow() }) + it('should not tag Thread ID when only __CHAT__ placeholder comment exists under root comment', async () => { + const rootComment = await prisma.assetComment.create({ + data: { assetId: asset.id, message: 'Root comment asking agent', creatorId: user.id }, + }) + // Create placeholder comment under rootComment + await prisma.assetComment.create({ + data: { + assetId: asset.id, + message: '__CHAT__', + creatorId: user.id, + replyToId: rootComment.id, + }, + }) + + const sessionId = await initializeAgentSessionActivity({ + teamId: team.id, + agentId: 'test-agent-id', + userCommentId: rootComment.id, + userId: user.id, + }) + + const storage = new DatabaseSessionStorage(sessionId) + const pathEntries = await storage.getPathToRoot(rootComment.id) + const rootEntry = pathEntries.find((e) => e.id === rootComment.id) + + expect(rootEntry).toBeDefined() + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- entry data structure parsing + const content = (rootEntry as any)?.message?.content?.[0]?.text || '' + expect(content).not.toContain(`[Thread ID: ${rootComment.id}]`) + }) + 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 344c8f63..decc7675 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -547,14 +547,14 @@ export async function initializeAgentSessionActivity(params: { }) } - // 1. Fetch top-level comments up to rootComment.createdAt + // 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: { createdAt: 'asc' }, + orderBy: { id: 'asc' }, include: { creator: true }, }) @@ -566,7 +566,7 @@ export async function initializeAgentSessionActivity(params: { createdAt: { lte: userComment.createdAt }, id: { not: userComment.id }, }, - orderBy: { createdAt: 'asc' }, + orderBy: { id: 'asc' }, include: { creator: true }, }) : [] diff --git a/packages/agent/src/database-session-storage.ts b/packages/agent/src/database-session-storage.ts index a60ddeda..ac131168 100644 --- a/packages/agent/src/database-session-storage.ts +++ b/packages/agent/src/database-session-storage.ts @@ -265,6 +265,7 @@ export class DatabaseSessionStorage implements SessionStorage() diff --git a/packages/agent/src/tools/read-thread.ts b/packages/agent/src/tools/read-thread.ts index 98438c57..eec963e9 100644 --- a/packages/agent/src/tools/read-thread.ts +++ b/packages/agent/src/tools/read-thread.ts @@ -28,8 +28,11 @@ export const createReadThreadTool = (): AgentTool< } const replies = await prisma.assetComment.findMany({ - where: { replyToId: rootComment.id }, - orderBy: { createdAt: 'asc' }, + where: { + replyToId: rootComment.id, + message: { not: '__CHAT__' }, + }, + orderBy: { id: 'asc' }, include: { creator: true }, }) From d267c7de987e5c1f3489b310396344309deb2549 Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 29 Jul 2026 15:18:30 +0800 Subject: [PATCH 8/9] fix(agent): prevent passing asset IDs to read_thread and improve tool error messages --- packages/agent/src/tools/read-thread.test.ts | 16 ++++++++++++++++ packages/agent/src/tools/read-thread.ts | 15 +++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/packages/agent/src/tools/read-thread.test.ts b/packages/agent/src/tools/read-thread.test.ts index 304d8c60..14c82c9f 100644 --- a/packages/agent/src/tools/read-thread.test.ts +++ b/packages/agent/src/tools/read-thread.test.ts @@ -11,6 +11,9 @@ vi.mock('@shumai/db', async (importOriginal) => { findUnique: vi.fn(), findMany: vi.fn(), }, + asset: { + findUnique: vi.fn(), + }, }, } }) @@ -22,6 +25,7 @@ describe('createReadThreadTool', () => { it('should return error text when thread root comment is not found', async () => { vi.mocked(prisma.assetComment.findUnique).mockResolvedValue(null) + vi.mocked(prisma.asset.findUnique).mockResolvedValue(null) const tool = createReadThreadTool() const result = await tool.execute('call-1', { threadId: 'non-existent' }) @@ -30,6 +34,18 @@ describe('createReadThreadTool', () => { expect(textContent).toContain('Comment thread with ID "non-existent" not found.') }) + it('should return specific error text when threadId is an asset ID', async () => { + vi.mocked(prisma.assetComment.findUnique).mockResolvedValue(null) + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock return + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ id: 'asset-1' } as any) + + const tool = createReadThreadTool() + const result = await tool.execute('call-asset', { threadId: 'asset-1' }) + const textContent = (result.content[0] as { text: string }).text + + expect(textContent).toContain('ID "asset-1" is an Asset ID, not a Comment Thread ID') + }) + it('should return thread root message and notice when there are no replies', async () => { vi.mocked(prisma.assetComment.findUnique).mockResolvedValue({ id: 'root-1', diff --git a/packages/agent/src/tools/read-thread.ts b/packages/agent/src/tools/read-thread.ts index eec963e9..f1683f24 100644 --- a/packages/agent/src/tools/read-thread.ts +++ b/packages/agent/src/tools/read-thread.ts @@ -3,7 +3,10 @@ import { Type } from '@sinclair/typebox' import { type AgentTool } from '@earendil-works/pi-agent-core' const readThreadSchema = Type.Object({ - threadId: Type.String({ description: 'The comment ID of the thread root' }), + threadId: Type.String({ + description: + 'The root comment ID of a thread (e.g. from [Thread ID: ...]). Do NOT pass an asset ID or project ID.', + }), }) export const createReadThreadTool = (): AgentTool< @@ -21,8 +24,16 @@ export const createReadThreadTool = (): AgentTool< }) if (!rootComment) { + const isAsset = await prisma.asset.findUnique({ + where: { id: params.threadId }, + select: { id: true }, + }) + const errorText = isAsset + ? `ID "${params.threadId}" is an Asset ID, not a Comment Thread ID. Do not pass asset IDs to read_thread.` + : `Comment thread with ID "${params.threadId}" not found.` + return { - content: [{ type: 'text', text: `Comment thread with ID "${params.threadId}" not found.` }], + content: [{ type: 'text', text: errorText }], details: { threadId: params.threadId }, } } From bb789a9557c1a3fc3e6322299d907460f42c4c51 Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 29 Jul 2026 15:24:55 +0800 Subject: [PATCH 9/9] feat(agent): inject reply count alongside Thread ID tag in getPathToRoot --- packages/agent/src/activities/agent.test.ts | 2 +- .../agent/src/database-session-storage.ts | 19 +++++++++++++------ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index 55ed2716..b6f3db65 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -665,7 +665,7 @@ describe('Agent Database Activities Integration', () => { 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}]`) + expect(text).toContain(`[Thread ID: ${msg3.id}] [Replies: 1]`) }) it('should create separate thread sessions when agent is mentioned in top-level comments (msg3 & msg5) sharing DAG entries without duplication', async () => { diff --git a/packages/agent/src/database-session-storage.ts b/packages/agent/src/database-session-storage.ts index ac131168..17528cb4 100644 --- a/packages/agent/src/database-session-storage.ts +++ b/packages/agent/src/database-session-storage.ts @@ -267,23 +267,30 @@ export class DatabaseSessionStorage implements SessionStorage() + const threadReplyCountMap = new Map() for (const tc of threadCounts) { - if (tc.replyToId) commentIdsWithThreads.add(tc.replyToId) + if (tc.replyToId) { + threadReplyCountMap.set(tc.replyToId, tc._count.id) + } } - if (commentIdsWithThreads.size > 0) { + if (threadReplyCountMap.size > 0) { for (let i = 0; i < pathEntries.length; i++) { const entry = pathEntries[i] - if (commentIdsWithThreads.has(entry.id) && entry.type === 'message') { + const count = threadReplyCountMap.get(entry.id) + if (count !== undefined && count > 0 && 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}` + const threadTag = `[Thread ID: ${entry.id}] [Replies: ${count}]` + if (!msg.content[0].text.includes(`[Thread ID: ${entry.id}]`)) { + msg.content[0].text = `${threadTag} ${msg.content[0].text}` } } pathEntries[i] = cloned