Merge pull request #239 from shumaiOne/fix/agent-comment-thread-session

fix(agent): scope agent comment sessions to thread sessions anchored at root comments
This commit is contained in:
Yiling-J
2026-07-29 15:33:39 +08:00
committed by GitHub
7 changed files with 503 additions and 224 deletions
+281 -31
View File
@@ -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`,
)
@@ -572,48 +574,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)
// Retrieve main session entries
// 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 (contains top-level comments mainComment1 and mainComment2)
const mainEntries = await prisma.agentSessionEntry.findMany({
where: { sessionId: mainSessionId },
orderBy: { createdAt: 'asc' },
where: { sessionId: mainSession!.id },
orderBy: { id: '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 +624,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,15 +651,262 @@ 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}]`)
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 () => {
// 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: '[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
const 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)
// 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 } })
expect(msg1Entries.length).toBe(1)
expect(msg2Entries.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(msg4.id)
expect(path3Ids).not.toContain(msg5.id)
const storage5 = new DatabaseSessionStorage(session5Id)
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).not.toContain(msg4.id)
})
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 },
})
// 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 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 contains msg1, msg2, and msg3
expect(pathIds).toContain(msg1.id)
expect(pathIds).toContain(msg2.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 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 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 () => {
+135 -174
View File
@@ -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: {
@@ -518,134 +517,66 @@ 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: {
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,
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 },
})
}
const rootComment = await prisma.assetComment.findUnique({
where: { id: rootCommentId },
include: { creator: true },
})
if (!rootComment) {
throw new Error(`Root comment ${rootCommentId} not found`)
}
// 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
}> = []
if (!isThread) {
// Main Session: Only fetch top-level comments (replyToId: null)
existingComments = await prisma.assetComment.findMany({
where: {
// 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,
replyToId: null,
id: { not: userComment.id },
userCommentId: null,
type: 'comment',
},
orderBy: { createdAt: 'asc' },
include: { creator: 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({
}
// 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: { id: 'asc' },
include: { creator: true },
})
// 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' },
orderBy: { id: 'asc' },
include: { creator: true },
})
existingComments = [rootComment, ...replies]
}
}
: []
// Check which top-level comments have reply threads (for prompt tagging)
// Resolve user mentions from IDs to names
const allCommentsToSync = [...topLevelComments, ...threadReplies]
// Resolve user mentions from IDs to names and roles
const mentionRegex = /<@([^>]+)>/g
const mentionedUserIds = new Set<string>()
for (const c of existingComments) {
for (const c of allCommentsToSync) {
if (c.message) {
const matches = [...c.message.matchAll(mentionRegex)]
for (const match of matches) {
@@ -657,25 +588,18 @@ export async function initializeAgentSessionActivity(params: {
const userIdToNameMap = new Map<string, string>()
if (mentionedUserIds.size > 0) {
const resolvedUsers = await prisma.user.findMany({
where: {
id: { in: Array.from(mentionedUserIds) },
},
select: {
id: true,
name: true,
},
where: { id: { in: Array.from(mentionedUserIds) } },
select: { id: true, name: true },
})
for (const u of resolvedUsers) {
if (u.name) {
userIdToNameMap.set(u.id, u.name)
}
if (u.name) userIdToNameMap.set(u.id, u.name)
}
}
const userRoleMap = new Map<string, string>()
const humanCreatorIds = Array.from(
new Set(
existingComments
allCommentsToSync
.filter((c) => c.creator?.type !== 'agent' && c.creatorId)
.map((c) => c.creatorId!),
),
@@ -693,23 +617,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 existingEntry = await prisma.agentSessionEntry.findUnique({
where: { id: c.id },
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
@@ -717,42 +628,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 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,
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) {
+27 -8
View File
@@ -71,7 +71,14 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
await this.appendEntry(leafEntry)
}
nextEntryId?: string | null
async createEntryId(): Promise<string> {
if (this.nextEntryId) {
const id = this.nextEntryId
this.nextEntryId = null
return id
}
return ulid()
}
@@ -147,8 +154,9 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
})
await prisma.$transaction([
prisma.agentSessionEntry.create({
data: {
prisma.agentSessionEntry.upsert({
where: { id: entry.id },
create: {
id: entry.id,
sessionId: this.sessionId,
assetId: session?.assetId || null,
@@ -157,6 +165,9 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
createdAt: entry.timestamp ? new Date(entry.timestamp) : new Date(),
data: payload as PrismaJson.PiSessionEntryData,
},
update: {
data: payload as PrismaJson.PiSessionEntryData,
},
}),
prisma.agentSession.update({
where: { id: this.sessionId },
@@ -254,24 +265,32 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
by: ['replyToId'],
where: {
replyToId: { in: entryIds },
message: { not: '__CHAT__' },
},
_count: {
id: true,
},
})
const commentIdsWithThreads = new Set<string>()
const threadReplyCountMap = new Map<string, number>()
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
+3
View File
@@ -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)
@@ -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',
+18 -4
View File
@@ -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,15 +24,26 @@ 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 },
}
}
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 },
})
@@ -296,12 +296,20 @@ export function AgentSessionLogsDialog({
<div className="flex flex-col gap-1.5 bg-muted/30 dark:bg-muted/10 p-3 rounded-lg border border-foreground/5 backdrop-blur-xs w-full">
<div className="flex items-center justify-between gap-2">
<span
className={`text-[10px] px-2 py-0.5 rounded-full font-semibold uppercase tracking-wider ${badgeColor}`}
>
{roleName}
</span>
<span className="text-[10px] text-muted-foreground/60">
<div className="flex items-center gap-2 flex-wrap">
<span
className={`text-[10px] px-2 py-0.5 rounded-full font-semibold uppercase tracking-wider ${badgeColor}`}
>
{roleName}
</span>
<span
className="text-[10px] font-mono text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded border border-foreground/10 select-all"
title="Entry ID"
>
ID: {entry.id}
</span>
</div>
<span className="text-[10px] text-muted-foreground/60 shrink-0">
{timestamp}
</span>
</div>
@@ -319,7 +327,15 @@ export function AgentSessionLogsDialog({
<div className="absolute left-[9px] top-2 bottom-0 w-0.5 bg-foreground/10 last:hidden" />
<div className="absolute left-0 top-1.5 h-5 w-5 rounded-full border-4 border-background bg-gray-400" />
<div className="bg-muted/30 p-3 rounded-lg border border-foreground/5">
<div className="text-[10px] text-muted-foreground/60">{timestamp}</div>
<div className="flex items-center justify-between gap-2 mb-1.5 flex-wrap">
<span
className="text-[10px] font-mono text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded border border-foreground/10 select-all"
title="Entry ID"
>
ID: {entry.id}
</span>
<div className="text-[10px] text-muted-foreground/60">{timestamp}</div>
</div>
<pre className="text-xs text-foreground/80 font-mono whitespace-pre-wrap break-words">
{JSON.stringify(entry.entry, null, 2)}
</pre>