feat(agent): implement dynamic in-memory thread tagging for session context entries

This commit is contained in:
yiling
2026-07-28 11:51:25 +08:00
parent 4e2694e2d9
commit 56421cd562
3 changed files with 84 additions and 22 deletions
+51 -4
View File
@@ -21,7 +21,7 @@ import {
} from './agent'
import * as piAgent from '../index'
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
import { type DatabaseSessionMetadata } from '../database-session-storage'
import { DatabaseSessionStorage, type DatabaseSessionMetadata } from '../database-session-storage'
import { triggerLocalCancel } from '@shumai/workflow-core'
import { Context } from '@temporalio/activity'
@@ -591,12 +591,16 @@ describe('Agent Database Activities Integration', () => {
orderBy: { createdAt: 'asc' },
})
// Main session contains mainComment1 (with [Thread ID: <id>] tag), but NOT threadReply1
// Main session contains mainComment1, but NOT threadReply1
expect(mainEntries.length).toBe(1)
expect(mainEntries[0].id).toBe(mainComment1.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 mainEntryJson = mainEntries[0].data as any
expect(mainEntryJson.message.content[0].text).toContain(`[Thread ID: ${mainComment1.id}]`)
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({
@@ -612,6 +616,49 @@ describe('Agent Database Activities Integration', () => {
expect(threadSession?.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 () => {
const msg3 = await prisma.assetComment.create({
data: { assetId: asset.id, message: 'Question in msg3', creatorId: user.id },
})
const session1Id = await initializeAgentSessionActivity({
teamId: team.id,
agentId: 'test-agent-id',
userCommentId: msg3.id,
userId: user.id,
})
await prisma.assetComment.create({
data: {
assetId: asset.id,
message: 'Reply msg4',
creatorId: user.id,
replyToId: msg3.id,
},
})
const msg6 = await prisma.assetComment.create({
data: { assetId: asset.id, message: 'Question in msg6', creatorId: user.id },
})
await initializeAgentSessionActivity({
teamId: team.id,
agentId: 'test-agent-id',
userCommentId: msg6.id,
userId: user.id,
})
const storage = new DatabaseSessionStorage(session1Id)
const leafId = await storage.getLeafId()
const pathEntries = await storage.getPathToRoot(leafId)
const msg3Entry = pathEntries.find((e) => e.id === 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 return user name and role for team member', async () => {
const info = await getUserTeamInfoActivity({
userId: user.id,
-18
View File
@@ -642,20 +642,6 @@ export async function initializeAgentSessionActivity(params: {
}
// Check which top-level comments have reply threads (for prompt tagging)
const commentIdsWithThreads = new Set<string>()
if (!isThread && existingComments.length > 0) {
const threadCounts = await prisma.assetComment.groupBy({
by: ['replyToId'],
where: {
assetId: userComment.assetId,
replyToId: { in: existingComments.map((c) => c.id) },
},
})
for (const tc of threadCounts) {
if (tc.replyToId) commentIdsWithThreads.add(tc.replyToId)
}
}
// Resolve user mentions from IDs to names
const mentionRegex = /<@([^>]+)>/g
const mentionedUserIds = new Set<string>()
@@ -737,10 +723,6 @@ export async function initializeAgentSessionActivity(params: {
messageContent = `[${c.creator.name} (${role})]: ${messageContent}`
}
if (commentIdsWithThreads.has(c.id)) {
messageContent = `[Thread ID: ${c.id}] ${messageContent}`
}
const entryId = c.id
const message: AgentMessage = {
role: 'user',
@@ -247,6 +247,39 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
await this.reinjectSkillContentAsync(entry)
}
// Dynamically tag comments that currently have reply threads
const entryIds = pathEntries.map((e) => e.id)
if (entryIds.length > 0) {
const threadCounts = await prisma.assetComment.groupBy({
by: ['replyToId'],
where: {
replyToId: { in: entryIds },
},
})
const commentIdsWithThreads = new Set<string>()
for (const tc of threadCounts) {
if (tc.replyToId) commentIdsWithThreads.add(tc.replyToId)
}
if (commentIdsWithThreads.size > 0) {
for (let i = 0; i < pathEntries.length; i++) {
const entry = pathEntries[i]
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: ${entry.id}]`)) {
msg.content[0].text = `[Thread ID: ${entry.id}] ${msg.content[0].text}`
}
}
pathEntries[i] = cloned
}
}
}
}
return pathEntries
}