feat(agent): refactor database session storage to normalized DAG entries and lazy thread sync

This commit is contained in:
yiling
2026-07-28 11:21:31 +08:00
parent b876af464e
commit 4e2694e2d9
21 changed files with 930 additions and 252 deletions
+169 -46
View File
@@ -490,19 +490,117 @@ export async function initializeAgentSessionActivity(params: {
include: { creator: true },
})
// Create a new AgentSession
const newSession = await prisma.agentSession.create({
data: {
agentId,
userId: params.userId || null,
cwd: process.cwd(),
assetId: userComment ? userComment.assetId : null,
userCommentId: params.userCommentId,
if (!userComment) {
throw new Error(`User comment ${params.userCommentId} not found`)
}
const isThread = !!userComment.replyToId
const rootCommentId = userComment.replyToId || userComment.id
const targetUserCommentId = isThread ? rootCommentId : null
let session = await prisma.agentSession.findFirst({
where: {
assetId: userComment.assetId,
type: 'comment',
userCommentId: targetUserCommentId,
},
})
const sessionId = newSession.id
// Fetch existing comments as context
if (!session) {
session = await prisma.agentSession.create({
data: {
agentId,
userId: params.userId || null,
cwd: process.cwd(),
assetId: userComment.assetId,
userCommentId: targetUserCommentId,
type: 'comment',
},
})
}
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 } as unknown as PrismaJson.PiSessionEntryData,
},
})
mainPrevId = entryId
}
if (mainPrevId && mainPrevId !== mainSession.leafId) {
await prisma.agentSession.update({
where: { id: mainSession.id },
data: { leafId: mainPrevId },
})
}
}
// Fetch existing comments as context for current session
let existingComments: Array<{
id: string
message: string | null
@@ -510,36 +608,51 @@ export async function initializeAgentSessionActivity(params: {
creatorId: string | null
creator: { type: string; name: string } | null
sessionId: string | null
replyToId: string | null
}> = []
if (userComment) {
if (!userComment.replyToId) {
// Rule 1: outside of a reply, add all other comments on that asset
existingComments = await prisma.assetComment.findMany({
if (!isThread) {
// Main Session: Only fetch top-level comments (replyToId: null)
existingComments = await prisma.assetComment.findMany({
where: {
assetId: userComment.assetId,
replyToId: null,
id: { not: userComment.id },
},
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({
where: {
assetId: userComment.assetId,
replyToId: rootCommentId,
id: { not: userComment.id },
},
orderBy: { id: 'asc' },
orderBy: { createdAt: '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]
}
existingComments = [rootComment, ...replies]
}
}
// 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)
}
}
@@ -594,9 +707,19 @@ export async function initializeAgentSessionActivity(params: {
}
}
// Save context as AgentSessionEntry records
let prevId: string | null = null
// 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
}
const isAgent = c.creator?.type === 'agent' || c.sessionId !== null
let messageContent = c.message || ''
@@ -614,33 +737,33 @@ export async function initializeAgentSessionActivity(params: {
messageContent = `[${c.creator.name} (${role})]: ${messageContent}`
}
const entryId = ulid()
if (commentIdsWithThreads.has(c.id)) {
messageContent = `[Thread ID: ${c.id}] ${messageContent}`
}
const entryId = c.id
const message: AgentMessage = {
role: 'user',
content: [{ type: 'text', text: messageContent }],
timestamp: c.createdAt.getTime(),
}
const entryJson: SessionTreeEntry = {
type: 'message',
id: entryId,
parentId: prevId,
timestamp: c.createdAt.toISOString(),
message,
}
await prisma.agentSessionEntry.create({
data: {
id: entryId,
sessionId,
entry: entryJson as unknown as PrismaJson.PiSessionEntry,
assetId: userComment.assetId,
type: 'message',
parentId: prevId,
createdAt: c.createdAt,
data: { message } as unknown as PrismaJson.PiSessionEntryData,
},
})
prevId = entryId
}
// Update leafId of the session
if (prevId) {
if (prevId && prevId !== session.leafId) {
await prisma.agentSession.update({
where: { id: sessionId },
data: { leafId: prevId },