import { client } from '@/ui/api/client' import { Button } from '@/ui/components/ui/button' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from '@/ui/components/ui/dialog' import { Separator } from '@/ui/components/ui/separator' import { formatTimeAgo } from '@/ui/lib/time' import type { AttachmentInfo, CommentInfo, UserInfo } from '@shumai/dtos' import { useQuery } from '@tanstack/react-query' import { Download, File, Terminal } from 'lucide-react' import React from 'react' import Markdown from 'react-markdown' import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar' import { DrawAnnotation } from '../ui/icons' import { Skeleton } from '../ui/skeleton' import { formatTimestamp } from '../viewers/utils' interface MessageCardProps { teamId?: string message: CommentInfo isReply?: boolean hasReplies?: boolean isLastReply?: boolean getUser: (id: string) => UserInfo onReply: (message: CommentInfo) => void onViewAttachment: (attachment: AttachmentInfo) => void isSelected?: boolean onSelect?: () => void frameRate?: number rootParentId?: string } /* eslint-disable @typescript-eslint/naming-convention */ const AI_PLACEHOLDERS: Record = { __CHAT__: 'Generating...', __AUTOFILL__: 'Autofilling metadata...', __EMBEDDING__: 'Generating embeddings...', __RUNNING__: 'Generating...', } export const MessageCard: React.FC = ({ teamId, message: initialMessage, isReply, hasReplies, isLastReply, getUser, onReply, onViewAttachment, isSelected, onSelect, frameRate, }) => { const message = initialMessage const hasDrawInfo = !!message.annotations && Array.isArray(message.annotations) && message.annotations.length > 0 const creator = message.creator const showSkeleton = !!message.sessionId && !!message.message && message.message in AI_PLACEHOLDERS const loadingText = (message.message && AI_PLACEHOLDERS[message.message]) || 'Generating...' const [isLogsOpen, setIsLogsOpen] = React.useState(false) const { data: me } = useQuery({ queryKey: ['teams', teamId, 'me'], queryFn: async () => { const res = await client.api.teams[':teamId'].me.$get({ param: { teamId: teamId! }, }) if (!res.ok) throw new Error('Failed to fetch current member info') return await res.json() }, enabled: !!teamId, staleTime: 300000, }) const isAdmin = me?.role === 'owner' const { data: logs, isLoading: isLogsLoading } = useQuery({ queryKey: ['agent-sessions', message.sessionId, 'entries'], queryFn: async () => { const res = await client.api['agent-sessions'][':sessionId'].entries.$get({ param: { sessionId: message.sessionId! }, }) if (!res.ok) throw new Error('Failed to fetch session logs') return await res.json() }, enabled: isLogsOpen && !!message.sessionId, }) const renderFormattedMessage = (text: string) => { const parts = text.split(/(<@[a-zA-Z0-9_-]+>)/g) return parts.map((part, index) => { if (part.match(/^<@[a-zA-Z0-9_-]+>$/)) { const userId = part.slice(2, -1) const mentionedUser = message.mentions?.find((m) => m.id === userId) || getUser(userId) return ( @{mentionedUser?.name || 'Unknown'} ) } return {part} }) } const preprocessMarkdown = (text: string): string => { return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:') } const handleReply = () => { onReply(message) } return (
{/* Left Column: Avatar & Thread Lines */}
{/* Thread line above avatar (for replies) */} {isReply && (
)} {/* Thread line under avatar (for parent comments with replies, or intermediate replies) */} {((hasReplies && !isReply) || (isReply && !isLastReply)) && (
)} {creator?.image && ( )} {creator?.name?.[0]?.toUpperCase() || 'U'}
{/* Content */}
{creator?.name || 'Unknown'} {new Date(message.createdAt!).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', })}
{message.second !== null && message.second !== undefined && frameRate && (
{formatTimestamp(message.second, frameRate)}
)} {hasDrawInfo && (
)} {showSkeleton ? (
{loadingText}
) : message.sessionId ? (
{preprocessMarkdown(message.message!)}
) : (
{renderFormattedMessage(message.message!)}
)}
{/* Attachments */} {message.attachments && message.attachments.length > 0 && (
{message.attachments.map((att) => { const isImage = att.mediaType?.startsWith('image/') const name = att.url?.split('/').pop()?.split('?')[0] || 'file' return (
isImage && onViewAttachment(att)} > {isImage ? ( {name} ) : (
{name}
)} e.stopPropagation()} >
) })}
)} {/* Agent Footer */} {message.sessionId && (
Created by Agent {isAdmin && ( )}
)} {/* Actions */}
{/* Logs Dialog */} Agent Session Logs Step-by-step execution trace of the agent's background tasks and tool calls.
{isLogsLoading ? (
) : logs && logs.length > 0 ? (
{logs.map((entry) => { const piEntry = entry.entry as Record | null const timestampStr = piEntry?.timestamp || (entry as Record).timestamp let timestamp = '' if (typeof timestampStr === 'string' || typeof timestampStr === 'number') { const dateObj = new Date(timestampStr) if (!isNaN(dateObj.getTime())) { timestamp = formatTimeAgo(dateObj.toISOString()) } } if (piEntry && typeof piEntry === 'object') { if (piEntry.type === 'message' && piEntry.message) { const msg = piEntry.message as Record 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' roleName = 'User' } else if (msg.role === 'assistant') { badgeColor = 'bg-violet-100 text-violet-800 dark:bg-violet-900/30 dark:text-violet-300' roleName = 'Agent' } else if (msg.role === 'toolResult') { badgeColor = msg.isError ? 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300' : 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300' roleName = `Tool Result: ${String(msg.toolName || 'Unknown')}` } else if (msg.role === 'thought') { badgeColor = 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300' roleName = 'Thinking' } const renderToolCallArguments = (args: unknown) => { let parsedArgs: unknown = args if (typeof args === 'string') { try { parsedArgs = JSON.parse(args) } catch { // ignore } } if ( parsedArgs && typeof parsedArgs === 'object' && !Array.isArray(parsedArgs) ) { const obj = parsedArgs as Record return (
{Object.entries(obj).map(([key, value]) => { const valueStr = value && typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value) return (
{key}: {' '} {valueStr}
) })}
) } return (
{String(args)}
) } const renderMessageContent = () => { const content = msg.content if (!content) return null if (typeof content === 'string') { if (!content.trim()) return null return (
{preprocessMarkdown(content)}
) } if (Array.isArray(content)) { const renderedBlocks: React.ReactNode[] = [] content.forEach((item, idx) => { if (!item) return if (typeof item === 'string') { if (!item.trim()) return renderedBlocks.push(
{preprocessMarkdown(item)}
, ) return } if (typeof item === 'object') { const itemObj = item as Record const type = itemObj.type if (type === 'text') { const text = itemObj.text if (typeof text !== 'string' || !text.trim()) return renderedBlocks.push(
{preprocessMarkdown(text)}
, ) return } if (type === 'toolCall') { const toolName = String( itemObj.name || itemObj.toolName || 'Unknown', ) const toolArgs = itemObj.arguments || itemObj.args renderedBlocks.push(
Calling Tool:{' '} {toolName}
{!!toolArgs && (
Arguments
{renderToolCallArguments(toolArgs)}
)}
, ) return } if (type === 'image') { renderedBlocks.push(
[Image Object]
, ) return } // Fallback for other object types const stringified = JSON.stringify(item, null, 2) if (stringified === '{}') return renderedBlocks.push(
                                  {stringified}
                                
, ) } }) if (renderedBlocks.length === 0) return null return (
{renderedBlocks.map((block, index) => ( {index > 0 && } {block} ))}
) } return null } return (
{/* Timeline Line */}
{/* Timeline Node */}
{roleName} {timestamp}
{renderMessageContent()}
) } } // Fallback for non-message entries or arbitrary entries return (
{timestamp}
                          {JSON.stringify(entry.entry, null, 2)}
                        
) })}
) : (

No logs found for this session.

The session might have been initialized but has not produced any entries yet.

)}
) }