From b8eddcd85487521fe5f970a0e9d9bfe4af3bf201 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 12:25:32 +0800 Subject: [PATCH] feat(chatbot): return rich AgentMessage structure directly from listMessages API --- packages/core/src/chat/chat.test.ts | 73 +++++++++++- packages/core/src/chat/chat.ts | 169 +++++++++++++++++++--------- packages/dtos/src/chat.ts | 21 ++-- 3 files changed, 202 insertions(+), 61 deletions(-) diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts index b0d05d22..eaca5071 100644 --- a/packages/core/src/chat/chat.test.ts +++ b/packages/core/src/chat/chat.test.ts @@ -1,6 +1,6 @@ import { prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' -import { chatService } from '@shumai/core/src/chat/chat' +import { chatService, buildSessionMessages } from './chat' import { describe, expect, it } from 'vitest' describe('ChatService', () => { @@ -256,7 +256,7 @@ describe('ChatService', () => { const messages = await chatService.listMessages(user.id, sessionId) expect(messages).toHaveLength(1) expect(messages[0].role).toBe('user') - expect(messages[0].content).toBe('hello') + expect(messages[0].content).toEqual([{ type: 'text', text: 'hello' }]) }) it('should delete session and cascade', async () => { @@ -280,4 +280,73 @@ describe('ChatService', () => { }) expect(entries).toHaveLength(0) }) + + it('should build session messages correctly handling compaction and custom messages', () => { + const pathEntries = [ + { + id: 'entry-1', + type: 'message', + timestamp: '2026-07-07T00:00:00.000Z', + message: { + role: 'user', + content: 'first message', + }, + }, + { + id: 'entry-compaction', + type: 'compaction', + timestamp: '2026-07-07T00:01:00.000Z', + summary: 'Compacted conversation history', + tokensBefore: 200, + firstKeptEntryId: 'entry-2', + }, + { + id: 'entry-2', + type: 'message', + timestamp: '2026-07-07T00:02:00.000Z', + message: { + role: 'assistant', + content: 'kept message', + }, + }, + { + id: 'entry-3', + type: 'thinking_level_change', + timestamp: '2026-07-07T00:03:00.000Z', + thinkingLevel: 'high', + }, + { + id: 'entry-4', + type: 'branch_summary', + timestamp: '2026-07-07T00:04:00.000Z', + summary: 'Branch summary details', + fromId: 'entry-old', + }, + ] + + const messages = buildSessionMessages(pathEntries) + + expect(messages).toHaveLength(4) + + // 1. Compaction summary message + expect(messages[0].role).toBe('custom') + expect(messages[0].customType).toBe('compaction-summary') + expect(messages[0].content).toBe('Compacted conversation history') + expect((messages[0].details as Record).tokensBefore).toBe(200) + + // 2. Kept entry (entry-2) + expect(messages[1].id).toBe('entry-2') + expect(messages[1].role).toBe('assistant') + expect(messages[1].content).toBe('kept message') + + // 3. Thinking level change (entry-3) + expect(messages[2].role).toBe('thinking_level_change') + expect(messages[2].content).toContain('Thinking level changed to high') + + // 4. Branch summary (entry-4) + expect(messages[3].role).toBe('custom') + expect(messages[3].customType).toBe('branch-summary') + expect(messages[3].content).toBe('Branch summary details') + expect((messages[3].details as Record).fromId).toBe('entry-old') + }) }) diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index 59fdcb06..79a5b895 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -6,61 +6,120 @@ import type { ChatRequest, ChatSessionInfo, ChatMessage } from '@shumai/dtos' type User = Prisma.UserGetPayload> +interface SimpleMessageEntry { + type: string + id?: string + timestamp?: string + thinkingLevel?: string + customType?: string + content?: unknown + display?: string + details?: unknown + summary?: string + fromId?: string + tokensBefore?: number + firstKeptEntryId?: string + message?: { + role: string + content: unknown + timestamp?: number + [key: string]: unknown + } +} + +export function buildSessionMessages(pathEntries: SimpleMessageEntry[]): ChatMessage[] { + let compaction: SimpleMessageEntry | null = null + + for (const entry of pathEntries) { + if (entry.type === 'compaction') { + compaction = entry + } + } + + const messages: ChatMessage[] = [] + const appendMessage = (entry: SimpleMessageEntry) => { + const timestampMs = entry.timestamp ? new Date(entry.timestamp).getTime() : Date.now() + if (entry.type === 'message' && entry.message) { + messages.push({ + ...(entry.message as Record), + id: entry.id || 'unknown-id', + role: entry.message.role, + content: entry.message.content as string | unknown[], + timestamp: entry.message.timestamp || timestampMs, + }) + } else if (entry.type === 'custom_message') { + messages.push({ + id: entry.id || 'unknown-id', + role: 'custom', + customType: entry.customType || '', + content: (entry.content as string | unknown[]) || '', + display: entry.display, + details: entry.details, + timestamp: timestampMs, + }) + } else if (entry.type === 'branch_summary' && entry.summary) { + messages.push({ + id: entry.id || 'unknown-id', + role: 'custom', + customType: 'branch-summary', + content: entry.summary, + details: { fromId: entry.fromId }, + timestamp: timestampMs, + }) + } else if (entry.type === 'thinking_level_change' && entry.thinkingLevel) { + messages.push({ + id: entry.id || 'unknown-id', + role: 'thinking_level_change', + content: `Thinking level changed to ${entry.thinkingLevel}`, + timestamp: timestampMs, + }) + } + } + + if (compaction) { + const compactionTimestamp = compaction.timestamp ? new Date(compaction.timestamp).getTime() : Date.now() + messages.push({ + id: compaction.id || 'unknown-id', + role: 'custom', + customType: 'compaction-summary', + content: compaction.summary || '', + details: { tokensBefore: compaction.tokensBefore }, + timestamp: compactionTimestamp, + }) + const compactionIdx = pathEntries.findIndex( + (e) => e.type === 'compaction' && e.id === compaction?.id, + ) + let foundFirstKept = false + for (let i = 0; i < compactionIdx; i++) { + const entry = pathEntries[i] + if (entry.id === compaction.firstKeptEntryId) foundFirstKept = true + if (foundFirstKept) appendMessage(entry) + } + for (let i = compactionIdx + 1; i < pathEntries.length; i++) { + appendMessage(pathEntries[i]) + } + } else { + for (const entry of pathEntries) { + appendMessage(entry) + } + } + + return messages +} + export function mapEntryToMessage( entryRecord: Prisma.AgentSessionEntryGetPayload>, ): ChatMessage { - interface SimpleMessageEntry { - type: 'message' | 'thinking_level_change' - timestamp?: string - thinkingLevel?: string - message?: { - role?: string - content?: string | Array<{ type: string; text?: string; data?: string }> - } + const entryObj = entryRecord.entry as unknown as SimpleMessageEntry + const pathEntries = [{ ...entryObj, id: entryRecord.id }] + const messages = buildSessionMessages(pathEntries) + if (messages.length > 0) { + return messages[0] } - - const entry = entryRecord.entry as unknown as SimpleMessageEntry - const id = entryRecord.id - const timestamp = entry.timestamp || new Date().toISOString() - - let role: ChatMessage['role'] - let content = '' - - if (entry.type === 'message') { - const rawRole = entry.message?.role - if ( - rawRole === 'user' || - rawRole === 'assistant' || - rawRole === 'toolCall' || - rawRole === 'toolResult' - ) { - role = rawRole - } else { - role = 'user' - } - - if (Array.isArray(entry.message?.content)) { - content = entry.message.content - .filter((c) => c.type === 'text') - .map((c) => c.text || '') - .join('\n') - } else if (typeof entry.message?.content === 'string') { - content = entry.message.content - } - } else if (entry.type === 'thinking_level_change') { - role = 'thinking_level_change' - content = `Thinking level changed to ${entry.thinkingLevel}` - } else { - role = 'toolCall' - content = JSON.stringify(entry) - } - return { - id, - role, - content, - timestamp, - entry: entry as unknown as PrismaJson.PiSessionEntry, + id: entryRecord.id, + role: 'unknown', + content: '', } } @@ -296,7 +355,15 @@ export class ChatService { orderBy: { id: 'asc' }, }) - return entries.map(mapEntryToMessage) + const pathEntries = entries.map((e) => { + const entryObj = e.entry as unknown as SimpleMessageEntry + return { + ...entryObj, + id: e.id, + } + }) + + return buildSessionMessages(pathEntries) } async deleteSession(userId: string, sessionId: string): Promise { diff --git a/packages/dtos/src/chat.ts b/packages/dtos/src/chat.ts index bcdf4c55..a40b06e3 100644 --- a/packages/dtos/src/chat.ts +++ b/packages/dtos/src/chat.ts @@ -37,12 +37,17 @@ export const chatSessionInfoSchema = z.object({ export type ChatSessionInfo = z.infer -export const chatMessageSchema = z.object({ - id: z.string(), - role: z.enum(['user', 'assistant', 'toolCall', 'toolResult', 'thinking_level_change']), - content: z.string(), - timestamp: z.string(), - entry: z.unknown(), // Raw session entry data -}) +export const chatMessageSchema = z.intersection( + z.object({ + id: z.string(), + }), + z.record(z.string(), z.unknown()), +) -export type ChatMessage = z.infer +export type ChatMessage = { + id: string + role: string + content: string | unknown[] + timestamp?: number + [key: string]: unknown +}