From 64b68e7d632be3082170387df38d49defeb18b57 Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Tue, 1 Sep 2026 17:42:56 +0800 Subject: [PATCH] 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 --- packages/agent/src/activities/agent.test.ts | 86 +++++++++++++- packages/agent/src/activities/agent.ts | 15 +++ .../src/context/serialize-context.test.ts | 19 ++++ .../src/database-session-storage.test.ts | 73 ++++++++++++ .../agent/src/database-session-storage.ts | 105 +++++++++--------- packages/agent/src/tools/read-thread.test.ts | 31 ++++++ packages/agent/src/tools/read-thread.ts | 8 +- packages/core/src/agent/agent.test.ts | 79 +++++++++++++ packages/core/src/agent/agent.ts | 34 +++++- packages/dtos/src/chat.ts | 8 ++ packages/dtos/src/context.ts | 16 ++- 11 files changed, 410 insertions(+), 64 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index d3db9865..b836f0bd 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -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', () => { '\n# Subfolder Policy\n', ) }) + + 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, + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Mock AgentHarness instance for activity test + harness: mockHarness as unknown as AgentHarness, + }) + + 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('') + expect(systemPromptArg).toContain('read_thread') + }) }) }) diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index a7dfce14..451a76c6 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -163,6 +163,21 @@ User messages may contain a 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 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' diff --git a/packages/agent/src/context/serialize-context.test.ts b/packages/agent/src/context/serialize-context.test.ts index 11f1b52a..eccb16b1 100644 --- a/packages/agent/src/context/serialize-context.test.ts +++ b/packages/agent/src/context/serialize-context.test.ts @@ -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( + '\n \n \n', + ) + }) + + it('serializes context with thread tag without reply_count', () => { + const context: ShumaiMessageContext = { + thread: { id: 'th_01JXYZ' }, + } + expect(serializeContextToXml(context)).toBe( + '\n \n', + ) + }) + it('serializes minimal context with only currentAsset (without ancestors)', () => { const context: ShumaiMessageContext = { currentAsset: { diff --git a/packages/agent/src/database-session-storage.test.ts b/packages/agent/src/database-session-storage.test.ts index e7fdd3ba..7967f61a 100644 --- a/packages/agent/src/database-session-storage.test.ts +++ b/packages/agent/src/database-session-storage.test.ts @@ -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, + }) + }) }) }) diff --git a/packages/agent/src/database-session-storage.ts b/packages/agent/src/database-session-storage.ts index 6633c110..26880b79 100644 --- a/packages/agent/src/database-session-storage.ts +++ b/packages/agent/src/database-session-storage.ts @@ -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 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() - 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 { @@ -431,6 +380,56 @@ export class DatabaseSessionStorage implements SessionStorage { + 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() + 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 } diff --git a/packages/agent/src/tools/read-thread.test.ts b/packages/agent/src/tools/read-thread.test.ts index 14c82c9f..6dd3ed91 100644 --- a/packages/agent/src/tools/read-thread.test.ts +++ b/packages/agent/src/tools/read-thread.test.ts @@ -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 in ', () => { + const tool = createReadThreadTool() + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const description = (tool.parameters as any).properties.threadId.description + expect(description).toContain('') + }) }) diff --git a/packages/agent/src/tools/read-thread.ts b/packages/agent/src/tools/read-thread.ts index 50855308..c4dafba2 100644 --- a/packages/agent/src/tools/read-thread.ts +++ b/packages/agent/src/tools/read-thread.ts @@ -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 in the 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 || ''}` } } diff --git a/packages/core/src/agent/agent.test.ts b/packages/core/src/agent/agent.test.ts index 19617a08..25de4f58 100644 --- a/packages/core/src/agent/agent.test.ts +++ b/packages/core/src/agent/agent.test.ts @@ -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', () => { diff --git a/packages/core/src/agent/agent.ts b/packages/core/src/agent/agent.ts index c4b6c699..f6fc4e4a 100644 --- a/packages/core/src/agent/agent.ts +++ b/packages/core/src/agent/agent.ts @@ -549,21 +549,53 @@ export class AgentService { ORDER BY depth DESC; ` + const entryIds = rows.map((r) => r.id) + const threadReplyCountMap = new Map() + 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) || {} + const count = threadReplyCountMap.get(r.id) + let details = payload.details as Record | 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, } diff --git a/packages/dtos/src/chat.ts b/packages/dtos/src/chat.ts index c1a912e3..7ef50f03 100644 --- a/packages/dtos/src/chat.ts +++ b/packages/dtos/src/chat.ts @@ -79,6 +79,13 @@ export const shumaiMediaPositionSchema = z.discriminatedUnion('type', [ export type ShumaiMediaPosition = z.infer +export const shumaiThreadContextSchema = z.object({ + id: z.string(), + replyCount: z.number().optional(), +}) + +export type ShumaiThreadContext = z.infer + 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(), diff --git a/packages/dtos/src/context.ts b/packages/dtos/src/context.ts index 5081c5c2..a37b3844 100644 --- a/packages/dtos/src/context.ts +++ b/packages/dtos/src/context.ts @@ -23,7 +23,7 @@ function formatAttr(name: string, value: string | undefined): string { * object into a standardized, order-stable XML block. * * Adheres strictly to the following invariants: - * 1. Tag sequence: , , , , , + * 1. Tag sequence: , , , , , , * 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. ... + // 2. + 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(` `) + } + } + + // 3. ... if (context.currentAsset) { const ca = context.currentAsset let assetAttrs = ''