feat(agent): add agent chat context session routing and thread support

This commit is contained in:
yiling
2026-05-21 22:51:40 +08:00
parent 1fbd0bdfaf
commit 979e4711c5
6 changed files with 548 additions and 17 deletions
+110 -1
View File
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { setupTestDbHooks } from '@/db-test-hooks'
import { prisma } from '@/db'
import { aiChatActivity } from './agent'
import { agentService } from '@/services/agent/agent'
@@ -30,6 +31,7 @@ describe('Agent Activities', () => {
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
sessionId: 'mock-session-id',
})
expect(agentService.chatWithAgent).toHaveBeenCalledWith(
@@ -38,8 +40,115 @@ describe('Agent Activities', () => {
'Hi',
[],
'',
undefined,
'mock-session-id',
undefined,
)
})
it('should initialize a new session with chronological context (Rule 1 and Rule 2) and prefix username', async () => {
const team = await prisma.team.create({ data: { name: 't1' } })
const user1 = await prisma.user.create({
data: { name: 'User One', email: 'user1@example.com' },
})
const project = await prisma.project.create({
data: { name: 'p1', teamId: team.id },
})
const file = await prisma.asset.create({
data: {
name: 'test-file',
type: 'file',
projectId: project.id,
creatorId: user1.id,
status: 'uploaded',
},
})
// Create existing comment 1
const comment1 = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: user1.id,
message: 'First comment message',
},
})
// Create triggering comment 2 (Rule 1: no reply, mentions agent)
const comment2 = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: user1.id,
message: 'Hello <@agent-id>',
},
})
vi.mocked(agentService.chatWithAgent).mockResolvedValue({
text: 'AI response',
usage: { inputTokens: 1, outputTokens: 1, model: 'gpt-4' },
sessionId: 'generated-session-id',
})
await aiChatActivity({
teamId: team.id,
agentId: 'agent-id',
message: 'Hello <@agent-id>',
imageUrls: [],
projectId: project.id,
folderId: file.id,
userCommentId: comment2.id,
})
// Verify chatWithAgent was called with a brand new sessionId (a ULID)
expect(agentService.chatWithAgent).toHaveBeenCalled()
const callArgs = vi.mocked(agentService.chatWithAgent).mock.calls[0]
const createdSessionId = callArgs[5]
expect(createdSessionId).toBeDefined()
expect(createdSessionId).not.toBe('generated-session-id')
// Verify session entries were populated with comment1 as context
const entries = await prisma.agentSessionEntry.findMany({
where: { sessionId: createdSessionId },
orderBy: { id: 'asc' },
})
expect(entries.length).toBe(1)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const entryData = entries[0].entry as any
expect(entryData.id).toBe(comment1.id)
expect(entryData.message.content[0].text).toBe('[User One]: First comment message')
expect(entryData.message.role).toBe('user')
})
it('should support deleteCommentActivity', async () => {
const team = await prisma.team.create({ data: { name: 't1' } })
const user1 = await prisma.user.create({
data: { name: 'User One', email: 'user1-delete@example.com' },
})
const project = await prisma.project.create({
data: { name: 'p1', teamId: team.id },
})
const file = await prisma.asset.create({
data: {
name: 'test-file',
type: 'file',
projectId: project.id,
creatorId: user1.id,
status: 'uploaded',
},
})
const comment = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: user1.id,
message: 'To be deleted',
},
})
const { deleteCommentActivity } = await import('./agent')
await deleteCommentActivity(comment.id)
const found = await prisma.assetComment.findUnique({
where: { id: comment.id },
})
expect(found).toBeNull()
})
})
+146 -1
View File
@@ -23,21 +23,166 @@ export interface AiChatParams {
agentsInstruction?: string
sessionId?: string
userId?: string
userCommentId?: string
explicitMention?: boolean
}
export async function aiChatActivity(params: AiChatParams) {
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
let sessionId = params.sessionId
if (!sessionId) {
const agentId = params.agentId === 'default' ? 'default' : params.agentId
// Ensure user exists for agent
const userExists = await prisma.user.findUnique({ where: { id: agentId } })
if (!userExists) {
await prisma.user.create({
data: {
id: agentId,
name: 'Ai Agent',
email: `${agentId}@shumai.ai`,
type: 'agent',
},
})
}
// Ensure agent exists
const agentExists = await prisma.agent.findUnique({ where: { id: agentId } })
if (!agentExists) {
await prisma.agent.create({
data: {
id: agentId,
teamId: params.teamId,
type: 'chat',
config: {
provider: 'openai',
model: 'gpt-4',
},
},
})
}
// Create a new AgentSession
const newSession = await prisma.agentSession.create({
data: {
agentId,
userId: params.userId || null,
cwd: process.cwd(),
},
})
sessionId = newSession.id
// Fetch existing comments as context
let existingComments: Array<{
id: string
message: string | null
createdAt: Date
creatorId: string | null
creator: { type: string; name: string } | null
sessionId: string | null
}> = []
if (params.userCommentId) {
const userComment = await prisma.assetComment.findUnique({
where: { id: params.userCommentId },
include: { creator: true },
})
if (userComment) {
if (!userComment.replyToId) {
// Rule 1: outside of a reply, add all other comments on that asset
existingComments = await prisma.assetComment.findMany({
where: {
assetId: userComment.assetId,
id: { not: userComment.id },
},
orderBy: { id: 'asc' },
include: { creator: true },
})
} else {
// Rule 2: in a reply, add root comment + all other replies to it
const rootComment = await prisma.assetComment.findUnique({
where: { id: userComment.replyToId },
include: { creator: true },
})
if (rootComment) {
const replies = await prisma.assetComment.findMany({
where: {
replyToId: rootComment.id,
id: { not: userComment.id },
},
orderBy: { id: 'asc' },
include: { creator: true },
})
existingComments = [rootComment, ...replies]
}
}
}
}
// Save context as AgentSessionEntry records
let prevId: string | null = null
for (const c of existingComments) {
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null
const role = isAgent ? 'assistant' : 'user'
let messageContent = c.message || ''
// Prepend user name to user messages to ensure agent knows who sent what
if (!isAgent && c.creator?.name) {
messageContent = `[${c.creator.name}]: ${messageContent}`
}
const entryId = c.id
const entryJson = {
type: 'message',
id: entryId,
parentId: prevId,
timestamp: c.createdAt.toISOString(),
message: {
role,
content: [{ type: 'text', text: messageContent }],
timestamp: c.createdAt.getTime(),
},
}
await prisma.agentSessionEntry.create({
data: {
id: entryId,
sessionId,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- entryJson conforms to the internal PiSessionEntry/SessionTreeEntry JSON schema which uses generic json types
entry: entryJson as any,
},
})
prevId = entryId
}
// Update leafId of the session
if (prevId) {
await prisma.agentSession.update({
where: { id: sessionId },
data: { leafId: prevId },
})
}
}
return agentService.chatWithAgent(
params.teamId,
params.agentId,
cleanMessage,
params.imageUrls,
params.agentsInstruction || '',
params.sessionId,
sessionId,
params.userId,
)
}
export async function deleteCommentActivity(commentId: string) {
return prisma.assetComment.delete({
where: { id: commentId },
})
}
export interface CreateCommentParams {
assetId: string
message: string