feat(agent): move thread metadata to structured context XML (#373)

* feat(agent): move thread metadata to structured context XML

* feat(core): dynamically inject thread metadata in getSessionEntries
This commit is contained in:
Yiling-J
2026-09-01 17:42:56 +08:00
committed by GitHub
parent c2f477a391
commit 64b68e7d63
11 changed files with 410 additions and 64 deletions
+81 -5
View File
@@ -711,7 +711,7 @@ describe('Agent Database Activities Integration', () => {
expect(threadSession1?.userCommentId).toBe(mainComment1.id) // Thread Session has userCommentId = rootComment.id
})
it('should dynamically tag top-level comments with [Thread ID: id] even if thread was created after initial sync', async () => {
it('should dynamically tag top-level comments with thread metadata in context 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 },
})
@@ -756,8 +756,13 @@ describe('Agent Database Activities Integration', () => {
const msg3Entry = pathEntries.find((e) => e.id.includes(msg3.id))
expect(msg3Entry).toBeDefined()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((msg3Entry as any).details?.thread).toEqual({
id: msg3.id,
replyCount: 1,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const text = (msg3Entry as any).content ?? (msg3Entry as any).message?.content[0]?.text
expect(text).toContain(`[Thread ID: ${msg3.id}] [Replies: 1]`)
expect(text).not.toContain(`[Thread ID: ${msg3.id}]`)
})
it('should create separate thread sessions when agent is mentioned in top-level comments (msg3 & msg5) sharing DAG entries without duplication', async () => {
@@ -979,7 +984,7 @@ describe('Agent Database Activities Integration', () => {
).resolves.not.toThrow()
})
it('should not tag Thread ID when only __CHAT__ placeholder comment exists under root comment', async () => {
it('should not tag thread 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 },
})
@@ -1006,8 +1011,7 @@ describe('Agent Database Activities Integration', () => {
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}]`)
expect((rootEntry as any)?.details?.thread).toBeUndefined()
})
it('should return user name and role for team member', async () => {
@@ -1696,5 +1700,77 @@ describe('Agent Database Activities Integration', () => {
'<project_instructions path="/subfolder/AGENTS.md">\n# Subfolder Policy\n</project_instructions>',
)
})
it('agentChatActivity injects # Comment Threads into systemPrompt when userCommentId is present', async () => {
const user = await prisma.user.create({
data: { name: 'User_Comment_Prompt', email: `comment-prompt-${Date.now()}@example.com` },
})
const team = await prisma.team.create({
data: { name: 'Team_Comment_Prompt_' + Date.now() },
})
const project = await prisma.project.create({
data: { name: 'Project_Comment_Prompt', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'Asset_1',
type: AssetType.file,
projectId: project.id,
status: AssetStatus.uploaded,
},
})
const comment = await prisma.assetComment.create({
data: {
assetId: asset.id,
message: 'Question',
creatorId: user.id,
},
})
const mockHarness = {
subscribe: vi.fn(),
prompt: vi.fn().mockResolvedValue({
content: [{ type: 'text', text: 'Chat reply' }],
usage: { input: 10, output: 20 },
}),
}
const mockSession = {
getEntries: vi.fn().mockResolvedValue([]),
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
}
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Mock AgentHarness instance for activity test
harness: mockHarness as unknown as AgentHarness<any, any, any, any>,
})
const context = {
agent: { id: 'agent-1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
dbProviders: [],
teamSkills: [],
allowedDomains: [],
} as unknown as AgentExecutionContext
await agentChatActivity({
teamId: team.id,
agentId: 'agent-1',
message: 'Hello',
imageUrls: [],
projectId: project.id,
folderId: asset.id,
assetId: asset.id,
sessionId: 'mock-session-id',
userCommentId: comment.id,
userId: user.id,
context,
})
const lastCall = vi.mocked(piAgent.createAgentSession).mock.calls.at(-1)
const systemPromptArg = lastCall?.[0].systemPrompt as string
expect(systemPromptArg).toContain('# Comment Threads')
expect(systemPromptArg).toContain('<thread id="..." reply_count="..." />')
expect(systemPromptArg).toContain('read_thread')
})
})
})
+15
View File
@@ -163,6 +163,21 @@ User messages may contain a <context> block detailing the user, active asset loc
systemPrompt += `\n\nYour current model supports the following input types: ${modelConfig.input.join(', ')}.`
}
const isCommentMode =
!!params.userCommentId ||
(params.sessionId
? (
await prisma.agentSession.findUnique({
where: { id: params.sessionId },
select: { type: true },
})
)?.type === 'comment'
: false)
if (isCommentMode) {
systemPrompt += `\n\n# Comment Threads\nWhen operating in comment mode, previous top-level messages in the conversation history may contain a <thread id="..." reply_count="..." /> tag indicating an earlier discussion thread with replies. If a user's question refers to or depends on earlier comments or discussions, you can use the 'read_thread' tool with the thread ID to inspect all replies in that thread.`
}
const agentConfig = agent.config as PrismaJson.AgentConfig | null | undefined
const thinkingLevel = agentConfig?.thinkingLevel || 'off'
@@ -31,6 +31,25 @@ describe('serializeContextToXml', () => {
)
})
it('serializes context with user and thread tag with reply_count', () => {
const context: ShumaiMessageContext = {
user: { id: 'usr_1', name: 'Alice', role: 'editor' },
thread: { id: 'th_01JXYZ', replyCount: 3 },
}
expect(serializeContextToXml(context)).toBe(
'<context>\n <user id="usr_1" name="Alice" role="editor" />\n <thread id="th_01JXYZ" reply_count="3" />\n</context>',
)
})
it('serializes context with thread tag without reply_count', () => {
const context: ShumaiMessageContext = {
thread: { id: 'th_01JXYZ' },
}
expect(serializeContextToXml(context)).toBe(
'<context>\n <thread id="th_01JXYZ" />\n</context>',
)
})
it('serializes minimal context with only currentAsset (without ancestors)', () => {
const context: ShumaiMessageContext = {
currentAsset: {
@@ -742,5 +742,78 @@ describe('DatabaseSessionStorage', () => {
const stats = await storage.getSessionStats()
expect(stats.messageCount).toBe(1)
})
it('should dynamically inject thread metadata into details.thread in getPathToRoot when replies exist', async () => {
const { agent, user } = await setupTestData()
const project = await prisma.project.create({
data: { name: 'Test Project', teamId: agent.teamId },
})
const asset = await prisma.asset.create({
data: {
name: 'Test Asset',
type: 'file',
status: 'uploaded',
projectId: project.id,
},
})
const storage = await DatabaseSessionStorage.create({ agentId: agent.id, assetId: asset.id })
const rootComment = await prisma.assetComment.create({
data: {
id: 'comment-root-1',
assetId: asset.id,
message: 'Top-level question',
creatorId: user.id,
},
})
// Add a reply
await prisma.assetComment.create({
data: {
id: 'comment-reply-1',
assetId: asset.id,
message: 'Reply 1',
creatorId: user.id,
replyToId: rootComment.id,
},
})
// Create session entry for root comment
await prisma.agentSessionEntry.create({
data: {
id: rootComment.id,
sessionId: storage.sessionId,
assetId: asset.id,
type: 'custom_message',
data: {
customType: 'shumai_message',
content: 'Top-level question',
display: true,
details: { user: { id: user.id, name: user.name } },
},
},
})
const path = await storage.getPathToRoot(rootComment.id)
expect(path).toHaveLength(1)
expect(path[0].type).toBe('custom_message')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const details = (path[0] as any).details
expect(details.thread).toEqual({
id: rootComment.id,
replyCount: 1,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((path[0] as any).content).toBe('Top-level question')
const entries = await storage.getEntries()
expect(entries).toHaveLength(1)
expect(entries[0].type).toBe('custom_message')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((entries[0] as any).details?.thread).toEqual({
id: rootComment.id,
replyCount: 1,
})
})
})
})
+52 -53
View File
@@ -8,6 +8,7 @@ import {
type SessionTreeEntry,
} from '@earendil-works/pi-agent-core'
import { agentService } from '@shumai/core/src/agent/agent'
import type { ShumaiMessageContext } from '@shumai/dtos'
export interface DatabaseSessionMetadata extends SessionMetadata {
agentId: string
@@ -366,59 +367,7 @@ 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 },
message: { not: '__CHAT__' },
},
_count: {
id: true,
},
})
const threadReplyCountMap = new Map<string, number>()
for (const tc of threadCounts) {
if (tc.replyToId) {
threadReplyCountMap.set(tc.replyToId, tc._count.id)
}
}
if (threadReplyCountMap.size > 0) {
for (let i = 0; i < pathEntries.length; i++) {
const entry = pathEntries[i]
const count = threadReplyCountMap.get(entry.id)
if (count !== undefined && count > 0) {
if (entry.type === 'message' && entry.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') {
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
} else if (entry.type === 'custom_message') {
const cloned = structuredClone(entry)
const threadTag = `[Thread ID: ${entry.id}] [Replies: ${count}]`
if (typeof cloned.content === 'string') {
if (!cloned.content.includes(`[Thread ID: ${entry.id}]`)) {
cloned.content = `${threadTag} ${cloned.content}`
}
}
pathEntries[i] = cloned
}
}
}
}
}
return pathEntries
return this.injectThreadMetadataAsync(pathEntries)
}
async getEntries(): Promise<SessionTreeEntry[]> {
@@ -431,6 +380,56 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
await this.reinjectImageDataAsync(entry)
await this.reinjectSkillContentAsync(entry)
}
return this.injectThreadMetadataAsync(entries)
}
private async injectThreadMetadataAsync(
entries: SessionTreeEntry[],
): Promise<SessionTreeEntry[]> {
const entryIds = entries.map((e) => e.id)
if (entryIds.length === 0) {
return entries
}
const threadCounts = await prisma.assetComment.groupBy({
by: ['replyToId'],
where: {
replyToId: { in: entryIds },
message: { not: '__CHAT__' },
},
_count: {
id: true,
},
})
const threadReplyCountMap = new Map<string, number>()
for (const tc of threadCounts) {
if (tc.replyToId) {
threadReplyCountMap.set(tc.replyToId, tc._count.id)
}
}
if (threadReplyCountMap.size > 0) {
for (let i = 0; i < entries.length; i++) {
const entry = entries[i]
const count = threadReplyCountMap.get(entry.id)
if (count !== undefined && count > 0) {
if (entry.type === 'custom_message') {
const cloned = structuredClone(entry)
const existingDetails = ((cloned as unknown as { details?: ShumaiMessageContext })
.details || {}) as ShumaiMessageContext
;(cloned as unknown as { details: ShumaiMessageContext }).details = {
...existingDetails,
thread: {
id: entry.id,
replyCount: count,
},
}
entries[i] = cloned
}
}
}
}
return entries
}
@@ -92,4 +92,35 @@ describe('createReadThreadTool', () => {
expect(textContent).toContain('- [Bob]: First reply to thread')
expect(textContent).toContain('- [Charlie]: Second reply to thread')
})
it('should label agent replies as [Ai Agent] when creator is null but sessionId exists', async () => {
vi.mocked(prisma.assetComment.findUnique).mockResolvedValue({
id: 'root-1',
message: 'Question to agent',
creator: { name: 'Alice' },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
vi.mocked(prisma.assetComment.findMany).mockResolvedValue([
{
id: 'reply-1',
message: 'Agent answer',
creator: null,
sessionId: 'session-123',
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
const tool = createReadThreadTool()
const result = await tool.execute('call-agent', { threadId: 'root-1' })
const textContent = (result.content[0] as { text: string }).text
expect(textContent).toContain('- [Ai Agent]: Agent answer')
})
it('should describe threadId parameter as referencing <thread id="..." /> in <context>', () => {
const tool = createReadThreadTool()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const description = (tool.parameters as any).properties.threadId.description
expect(description).toContain('<thread id="..." />')
})
})
+5 -3
View File
@@ -5,7 +5,7 @@ import { type AgentTool } from '@earendil-works/pi-agent-core'
const readThreadSchema = Type.Object({
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.',
'The root comment ID of a thread (from <thread id="..." /> in the <context> block). Do NOT pass an asset ID or project ID.',
}),
})
@@ -47,14 +47,16 @@ export const createReadThreadTool = (): AgentTool<
include: { creator: true },
})
const rootAuthor = rootComment.creator?.name || 'User'
const isRootAgent = rootComment.creator?.type === 'agent' || rootComment.sessionId !== null
const rootAuthor = rootComment.creator?.name || (isRootAgent ? 'Ai Agent' : 'User')
let output = `Thread Root [${rootAuthor}] (${rootComment.id}): ${rootComment.message || ''}\n\nReplies (${replies.length}):`
if (replies.length === 0) {
output += '\n(No replies in this thread yet)'
} else {
for (const reply of replies) {
const author = reply.creator?.name || 'User'
const isAgent = reply.creator?.type === 'agent' || reply.sessionId !== null
const author = reply.creator?.name || (isAgent ? 'Ai Agent' : 'User')
output += `\n- [${author}]: ${reply.message || ''}`
}
}
+79
View File
@@ -338,6 +338,85 @@ describe('AgentService', () => {
expect(entries[0].id).toBe(entry1.id)
expect(entries[1].id).toBe(entry2.id)
})
test('getSessionEntries dynamically attaches details.thread on custom_message entries with replies', async () => {
const db = prisma
const svc = new AgentService()
const { agent, team } = await setupTestData(db)
const project = await db.project.create({
data: { name: 'Test Project', teamId: team.id },
})
const asset = await db.asset.create({
data: {
name: 'video.mp4',
type: 'file',
status: 'uploaded',
projectId: project.id,
},
})
const user = await db.user.create({
data: { name: 'Alice', email: `alice-${Date.now()}@example.com` },
})
const rootComment = await db.assetComment.create({
data: {
id: 'comment-root-entries',
assetId: asset.id,
message: 'Top-level comment',
creatorId: user.id,
},
})
// Add a reply
await db.assetComment.create({
data: {
id: 'comment-reply-entries',
assetId: asset.id,
message: 'Reply to root',
creatorId: user.id,
replyToId: rootComment.id,
},
})
const session = await db.agentSession.create({
data: {
agentId: agent.id,
type: 'comment',
cwd: '/tmp',
},
})
const entry = await db.agentSessionEntry.create({
data: {
id: rootComment.id,
sessionId: session.id,
type: 'custom_message',
parentId: null,
data: {
customType: 'shumai_message',
content: 'Top-level comment',
display: true,
details: { user: { id: user.id, name: user.name } },
},
},
})
await db.agentSession.update({
where: { id: session.id },
data: { leafId: entry.id },
})
const entries = await svc.getSessionEntries({ sessionId: session.id })
expect(entries).toHaveLength(1)
expect(entries[0].id).toBe(rootComment.id)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const entryDetails = (entries[0].entry as any).details
expect(entryDetails?.thread).toEqual({
id: rootComment.id,
replyCount: 1,
})
})
})
describe('listSessions', () => {
+33 -1
View File
@@ -549,21 +549,53 @@ export class AgentService {
ORDER BY depth DESC;
`
const entryIds = rows.map((r) => r.id)
const threadReplyCountMap = new Map<string, number>()
if (entryIds.length > 0) {
const threadCounts = await this.prismaClient.assetComment.groupBy({
by: ['replyToId'],
where: {
replyToId: { in: entryIds },
message: { not: '__CHAT__' },
},
_count: {
id: true,
},
})
for (const tc of threadCounts) {
if (tc.replyToId) {
threadReplyCountMap.set(tc.replyToId, tc._count.id)
}
}
}
return rows.map((r) => {
const payload = (r.data as Record<string, unknown>) || {}
const count = threadReplyCountMap.get(r.id)
let details = payload.details as Record<string, unknown> | undefined
if (count !== undefined && count > 0 && r.type === 'custom_message') {
details = {
...details,
thread: {
id: r.id,
replyCount: count,
},
}
}
const entryObj = {
id: r.id,
type: r.type || 'message',
parentId: r.parent_id,
timestamp: r.created_at.toISOString(),
...payload,
...(details ? { details } : {}),
}
return {
id: r.id,
sessionId: r.session_id || params.sessionId,
type: r.type,
parentId: r.parent_id,
data: r.data,
data: details !== payload.details ? { ...payload, details } : r.data,
createdAt: r.created_at,
entry: entryObj,
}
+8
View File
@@ -79,6 +79,13 @@ export const shumaiMediaPositionSchema = z.discriminatedUnion('type', [
export type ShumaiMediaPosition = z.infer<typeof shumaiMediaPositionSchema>
export const shumaiThreadContextSchema = z.object({
id: z.string(),
replyCount: z.number().optional(),
})
export type ShumaiThreadContext = z.infer<typeof shumaiThreadContextSchema>
export const shumaiMessageContextSchema = z.object({
user: z
.object({
@@ -87,6 +94,7 @@ export const shumaiMessageContextSchema = z.object({
role: z.string(),
})
.optional(),
thread: shumaiThreadContextSchema.optional(),
currentAsset: shumaiAssetContextSchema.optional(),
position: shumaiMediaPositionSchema.optional(),
annotation: z.boolean().optional(),
+14 -2
View File
@@ -23,7 +23,7 @@ function formatAttr(name: string, value: string | undefined): string {
* object into a standardized, order-stable <context> XML block.
*
* Adheres strictly to the following invariants:
* 1. Tag sequence: <user>, <current_asset>, <position>, <annotation>, <attached_files>, <referenced_assets>
* 1. Tag sequence: <user>, <thread>, <current_asset>, <position>, <annotation>, <attached_files>, <referenced_assets>
* 2. Attribute sequence on every tag follows fixed, invariant order.
* 3. Arrays (attachedFiles, referencedAssets) sorted by id ascending.
* 4. Floats formatted with .toFixed(2), integers rounded.
@@ -46,7 +46,19 @@ export function serializeContextToXml(context?: ShumaiMessageContext | null): st
}
}
// 2. <current_asset ...> ... </current_asset>
// 2. <thread ... />
if (context.thread) {
let threadAttrs = ''
if (context.thread.id !== undefined) threadAttrs += formatAttr('id', context.thread.id)
if (context.thread.replyCount !== undefined) {
threadAttrs += ` reply_count="${Math.round(context.thread.replyCount)}"`
}
if (threadAttrs) {
lines.push(` <thread${threadAttrs} />`)
}
}
// 3. <current_asset ...> ... </current_asset>
if (context.currentAsset) {
const ca = context.currentAsset
let assetAttrs = ''