mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-02 14:04:50 +00:00
feat(agent): refactor message context into unified shumai_message (#365)
* feat(agent): refactor message context into unified shumai_message * fix(agent): persist custom_message entry type in DatabaseSessionStorage and handle message mapping defensively * fix(agent): pass clean prompt to harness and replace optimistic messages on shumai_message stream * fix(agent): align asset context DTO contract, sync comment attachments, and fix session stats
This commit is contained in:
@@ -14,6 +14,7 @@ import { formatTimeAgo } from '@/ui/lib/time'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { Terminal } from 'lucide-react'
|
||||
import Markdown from 'react-markdown'
|
||||
import { serializeContextToXml, type ShumaiMessageContext } from '@shumai/dtos'
|
||||
|
||||
interface AgentSessionLogsDialogProps {
|
||||
sessionId?: string | null
|
||||
@@ -87,14 +88,59 @@ export function AgentSessionLogsDialog({
|
||||
}
|
||||
|
||||
if (piEntry && typeof piEntry === 'object') {
|
||||
if (piEntry.type === 'custom_message') {
|
||||
if (piEntry.customType === 'context') return null
|
||||
if (piEntry.customType === 'shumai_message') {
|
||||
const xml = serializeContextToXml(piEntry.details as ShumaiMessageContext)
|
||||
const text = typeof piEntry.content === 'string' ? piEntry.content : ''
|
||||
const fullText = xml ? `${text}\n\n${xml}`.trim() : text
|
||||
const badgeColor = 'bg-primary/10 text-primary'
|
||||
const roleName = m.role_user()
|
||||
|
||||
return (
|
||||
<div key={entry.id} className="relative pl-6 pb-6 last:pb-0">
|
||||
{/* Timeline Line */}
|
||||
<div className="absolute left-[9px] top-2 bottom-0 w-0.5 bg-foreground/10 last:hidden" />
|
||||
|
||||
{/* Timeline Node */}
|
||||
<div className="absolute left-0 top-1.5 h-5 w-5 rounded-full border-4 border-background flex items-center justify-center bg-primary" />
|
||||
|
||||
<div className="flex flex-col gap-1.5 bg-muted/30 dark:bg-muted/10 p-3 rounded-lg border border-foreground/5 backdrop-blur-xs w-full">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span
|
||||
className={`text-[10px] px-2 py-0.5 rounded-full font-semibold uppercase tracking-wider ${badgeColor}`}
|
||||
>
|
||||
{roleName}
|
||||
</span>
|
||||
<span
|
||||
className="text-[10px] font-mono text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded border border-foreground/10 select-all"
|
||||
title={m.entry_id()}
|
||||
>
|
||||
{m.entry_id()}: {entry.id}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-[10px] text-muted-foreground/60 shrink-0">
|
||||
{timestamp}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-foreground/90 whitespace-pre-wrap leading-relaxed font-sans">
|
||||
{fullText}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (piEntry.type === 'message' && piEntry.message) {
|
||||
const msg = piEntry.message as Record<string, unknown>
|
||||
let badgeColor = 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200'
|
||||
let roleName: string = String(msg.role || '')
|
||||
|
||||
if (msg.role === 'user') {
|
||||
badgeColor =
|
||||
'bg-slate-100 text-slate-800 dark:bg-slate-900/30 dark:text-slate-300'
|
||||
badgeColor = 'bg-primary/10 text-primary'
|
||||
roleName = m.role_user()
|
||||
} else if (msg.role === 'assistant') {
|
||||
badgeColor =
|
||||
@@ -283,7 +329,7 @@ export function AgentSessionLogsDialog({
|
||||
<div
|
||||
className={`absolute left-0 top-1.5 h-5 w-5 rounded-full border-4 border-background flex items-center justify-center ${
|
||||
msg.role === 'user'
|
||||
? 'bg-slate-500'
|
||||
? 'bg-primary'
|
||||
: msg.role === 'assistant'
|
||||
? 'bg-violet-500'
|
||||
: msg.role === 'toolResult'
|
||||
@@ -304,9 +350,9 @@ export function AgentSessionLogsDialog({
|
||||
</span>
|
||||
<span
|
||||
className="text-[10px] font-mono text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded border border-foreground/10 select-all"
|
||||
title="Entry ID"
|
||||
title={m.entry_id()}
|
||||
>
|
||||
ID: {entry.id}
|
||||
{m.entry_id()}: {entry.id}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-[10px] text-muted-foreground/60 shrink-0">
|
||||
|
||||
@@ -12,7 +12,7 @@ import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useChatbotStore } from '@/ui/stores/chatbot'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
import { useDroppable } from '@dnd-kit/react'
|
||||
import type { ChatMessage } from '@shumai/dtos'
|
||||
import type { ChatMessage, ShumaiMessageContext } from '@shumai/dtos'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
ArrowLeft,
|
||||
@@ -401,6 +401,31 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
|
||||
case 'thinking_level_change':
|
||||
case 'custom': {
|
||||
const msgObj = msg as unknown as Record<string, unknown>
|
||||
if (msgObj.customType === 'shumai_message') {
|
||||
const details = msgObj.details as ShumaiMessageContext | undefined
|
||||
const referencedAssets = details?.referencedAssets || []
|
||||
return (
|
||||
<div key={msg.id} className="flex flex-col items-end w-full space-y-1">
|
||||
{referencedAssets.length > 0 && (
|
||||
<div className="text-xs text-muted-foreground bg-muted/40 p-2.5 rounded-lg border border-border/50 space-y-1 my-1 w-full">
|
||||
<div className="font-semibold">{m.assets_added_to_context()}</div>
|
||||
<ul className="list-disc list-inside space-y-0.5">
|
||||
{referencedAssets.map((asset) => (
|
||||
<li key={asset.id} className="truncate">
|
||||
{asset.name}{' '}
|
||||
<span className="text-muted-foreground/70">({asset.type})</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
<div className="bg-primary text-primary-foreground rounded-lg px-3 py-2 max-w-[85%] text-sm whitespace-pre-wrap shadow-xs break-words">
|
||||
{getMessageText(msgObj.content)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (msgObj.customType === 'context_display_info') {
|
||||
const details = msgObj.details as
|
||||
| { assets?: Array<{ id: string; name: string; type: string }> }
|
||||
@@ -561,7 +586,12 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
|
||||
{messages.map(renderMessage)}
|
||||
{isStreaming &&
|
||||
messages.length > 0 &&
|
||||
messages[messages.length - 1].role === 'user' && (
|
||||
(messages[messages.length - 1].role === 'user' ||
|
||||
(
|
||||
messages[messages.length - 1] as unknown as {
|
||||
customType?: string
|
||||
}
|
||||
).customType === 'shumai_message') && (
|
||||
<div className="flex items-center gap-1.5 text-xs text-muted-foreground italic">
|
||||
<Loader2 className="h-3 w-3 animate-spin text-primary" />
|
||||
<span>Thinking...</span>
|
||||
|
||||
@@ -1312,5 +1312,6 @@
|
||||
"timecode": "Timecode",
|
||||
"playback_speed": "Playback Speed",
|
||||
"settings": "Settings",
|
||||
"failed_to_post_comment": "Failed to post comment"
|
||||
"failed_to_post_comment": "Failed to post comment",
|
||||
"entry_id": "Entry ID"
|
||||
}
|
||||
|
||||
@@ -1312,5 +1312,6 @@
|
||||
"timecode": "时间码",
|
||||
"playback_speed": "播放速度",
|
||||
"settings": "设置",
|
||||
"failed_to_post_comment": "发送评论失败"
|
||||
"failed_to_post_comment": "发送评论失败",
|
||||
"entry_id": "条目 ID"
|
||||
}
|
||||
|
||||
+1
@@ -1250,4 +1250,5 @@ export * from "./frames.js";
|
||||
export * from "./timecode.js";
|
||||
export * from "./playback_speed.js";
|
||||
export * from "./failed_to_post_comment.js";
|
||||
export * from "./entry_id.js";
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
|
||||
+2
-1
@@ -1251,4 +1251,5 @@ export * from './standard_time.js'
|
||||
export * from './frames.js'
|
||||
export * from './timecode.js'
|
||||
export * from './playback_speed.js'
|
||||
export * from './failed_to_post_comment.js'
|
||||
export * from './failed_to_post_comment.js'
|
||||
export * from './entry_id.js'
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Entry ID" |
|
||||
*
|
||||
* @param {Entry_IdInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const entry_id: ((inputs?: Entry_IdInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Entry_IdInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Entry_IdInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Entry_IdInputs */
|
||||
|
||||
const en_entry_id = /** @type {(inputs: Entry_IdInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Entry ID`)
|
||||
};
|
||||
|
||||
const zh_entry_id = /** @type {(inputs: Entry_IdInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`条目 ID`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Entry ID" |
|
||||
*
|
||||
* @param {Entry_IdInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const entry_id = /** @type {((inputs?: Entry_IdInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Entry_IdInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_entry_id(inputs)
|
||||
return zh_entry_id(inputs)
|
||||
});
|
||||
@@ -368,4 +368,54 @@ describe('useChatbotStore', () => {
|
||||
|
||||
expect(onAssetMutation).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should replace optimistic message when shumai_message entry streams back', async () => {
|
||||
const mockEvents = [
|
||||
'data: {"type":"session","sessionId":"sess-123"}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":"user-msg-ulid","role":"custom","customType":"shumai_message","content":"hello","details":{"user":{"id":"u1","name":"User 1"}},"timestamp":123}}\n\n',
|
||||
'data: {"type":"entry","entry":{"id":"assistant-msg-ulid","role":"assistant","content":[{"type":"text","text":"Hi!"}],"timestamp":124}}\n\n',
|
||||
'data: {"type":"done","status":"completed"}\n\n',
|
||||
]
|
||||
|
||||
let eventIdx = 0
|
||||
const mockReader = {
|
||||
read: vi.fn(async () => {
|
||||
if (eventIdx < mockEvents.length) {
|
||||
const value = new TextEncoder().encode(mockEvents[eventIdx++])
|
||||
return { done: false, value }
|
||||
}
|
||||
return { done: true, value: undefined }
|
||||
}),
|
||||
}
|
||||
|
||||
const mockResponse = {
|
||||
ok: true,
|
||||
headers: {
|
||||
get: vi.fn(() => 'sess-123'),
|
||||
},
|
||||
body: {
|
||||
getReader: () => mockReader,
|
||||
},
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(client.api.teams[':teamId'].chat.$post).mockResolvedValue(mockResponse as any)
|
||||
|
||||
const sendPromise = useChatbotStore.getState().sendMessage('team-123', 'hello', 'proj-123')
|
||||
|
||||
// Optimistic message should be present immediately
|
||||
const stateWithOptimistic = useChatbotStore.getState()
|
||||
expect(stateWithOptimistic.messages).toHaveLength(1)
|
||||
expect(stateWithOptimistic.messages[0].id).toContain('temp-')
|
||||
|
||||
await sendPromise
|
||||
|
||||
// Final state assertions: optimistic message must be replaced
|
||||
const finalState = useChatbotStore.getState()
|
||||
expect(finalState.messages).toHaveLength(2)
|
||||
expect(finalState.messages[0].id).toBe('user-msg-ulid')
|
||||
expect(finalState.messages[0].role).toBe('custom')
|
||||
expect((finalState.messages[0] as { customType?: string }).customType).toBe('shumai_message')
|
||||
expect(finalState.messages[1].id).toBe('assistant-msg-ulid')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -289,10 +289,14 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
|
||||
set((s) => {
|
||||
const isExisting = s.messages.some((m) => m.id === entry.id)
|
||||
const isUserMessage =
|
||||
(entry.role === 'user' ||
|
||||
(entry.role === 'custom' && entry.customType === 'shumai_message')) &&
|
||||
!isExisting
|
||||
// Replace temp/optimistic message when the real counterpart streams back
|
||||
const filtered = s.messages.filter((m) => {
|
||||
if (entry.role === 'user' && !isExisting) {
|
||||
return !(m.id.startsWith('temp-') && !m.id.startsWith('temp-context-'))
|
||||
if (isUserMessage) {
|
||||
return !m.id.startsWith('temp-')
|
||||
}
|
||||
if (
|
||||
entry.role === 'custom' &&
|
||||
|
||||
Reference in New Issue
Block a user