import * as React from "react"; import { AlertTriangle, Bot, Brain, CheckCircle2, ChevronDown, Circle, ClipboardList, Clock3, FileText, PlayCircle, ShieldQuestion, } from "lucide-react"; import type { TranscriptDisplayBlock, TranscriptSameKindSummary, TranscriptTurnSegment, } from "@/features/agents/ui/agentSessionTranscriptGrouping"; import type { PromptSection, TranscriptItem, } from "@/features/agents/ui/agentSessionTypes"; import { getBuzzToolInfo } from "@/features/agents/ui/agentSessionToolCatalog"; import { buildCompactToolSummary } from "@/features/agents/ui/agentSessionToolSummary"; import { getToolDurationDisplay } from "@/features/agents/ui/agentSessionUtils"; import { RawEventRail } from "@/features/agents/ui/RawEventRail"; import { useObserverEvents } from "@/features/agents/ui/useObserverEvents"; import { ToolDetailBlocks } from "@/features/agents/ui/AgentSessionToolItem/ToolDetailBlocks"; import { resolveUserLabel, type UserProfileLookup, } from "@/features/profile/lib/identity"; import type { ChatActivityRenderBlock } from "@/features/chats/lib/chatActivity"; import { ActivityMarkerRow, InlineActivityMarkerRow, } from "@/features/chats/ui/ChatActivityMarkerRow"; import { activityItemLabel, activityItemTone, cleanChatMessageText, completedWorkLabel, isHumanFacingAssistantMessage, toolLabel, } from "@/features/chats/ui/chatActivityText"; import { activityItemIcon as toolActivityItemIcon, getShellCommand, summaryIcon, toolCategoryIcon, toolIcon, } from "@/features/chats/ui/chatActivityIcons"; import { isEntranceRecent } from "@/features/chats/ui/messageEntrance"; import type { ManagedAgent } from "@/shared/api/types"; import { cn } from "@/shared/lib/cn"; import { normalizePubkey } from "@/shared/lib/pubkey"; import { Bubble } from "@/shared/ui/bubble"; import { Markdown } from "@/shared/ui/markdown"; import { Message, MessageAvatar, MessageContent, MessageHeader, } from "@/shared/ui/message"; import { UserAvatar } from "@/shared/ui/UserAvatar"; function hasRecentEntrance(timestamp?: string | null) { return Boolean(timestamp) && isEntranceRecent(Date.parse(timestamp ?? "")); } // "Turn started" / "Session ready" plumbing rows. Hidden from the chat // timeline (they add noise to every turn); their timestamps still feed the // completed-turn duration. function isSetupLifecycleItem(item: TranscriptItem) { if (item.type !== "lifecycle") { return false; } const source = item.acpSource ?? ""; const title = item.title.toLowerCase(); return ( source === "turn_started" || source === "session_resolved" || title.includes("turn started") || title.includes("session ready") ); } export function ChatActivityTranscript({ activeTurnIds, agent, blocks, identityPubkey, profiles, showAgentIdentity = true, }: { /** Turn ids currently live in this channel — drives per-turn rendering. */ activeTurnIds?: ReadonlySet; agent: ManagedAgent | null; blocks: ChatActivityRenderBlock[]; identityPubkey?: string; profiles?: UserProfileLookup; /** Hidden in solo chats so agent replies read as part of the stream. */ showAgentIdentity?: boolean; }) { if (blocks.length === 0) { return null; } return ( <> {blocks.map((renderBlock) => ( ))} ); } function ChatActivityBlockView({ agent, block, identityPubkey, isTurnActive, profiles, showAgentIdentity, suppressPromptMessage, }: { agent: ManagedAgent | null; block: TranscriptDisplayBlock; identityPubkey?: string; /** Whether THIS block's turn is live (per-turn, never channel-wide). */ isTurnActive: boolean; profiles?: UserProfileLookup; showAgentIdentity: boolean; suppressPromptMessage: boolean; }) { if (block.kind === "single") { return ( ); } if (!isTurnActive && isCompletedTurn(block)) { return ( ); } return (
{block.segments.map((segment) => ( ))} {isTurnActive && !hasLiveActivityItem(block) ? ( ) : null}
); } function CompletedTurnView({ agent, block, identityPubkey, profiles, showAgentIdentity, suppressPromptMessage, }: { agent: ManagedAgent | null; block: Extract; identityPubkey?: string; profiles?: UserProfileLookup; showAgentIdentity: boolean; suppressPromptMessage: boolean; }) { const promptSegments = block.segments.filter( (segment): segment is Extract => segment.kind === "prompt", ); const assistantMessages = collectFinalAssistantMessages(block); const activityItems = collectCompletedActivityItems(block); return (
{promptSegments.map((segment) => suppressPromptMessage ? null : ( ), )} {activityItems.length > 0 ? ( ) : null} {assistantMessages.map((item) => ( ))}
); } function getSegmentKey(turnId: string, segment: TranscriptTurnSegment) { if (segment.kind === "prompt") { return `${turnId}:prompt`; } if (segment.kind === "setup") { return `${turnId}:setup`; } if (segment.kind === "summary") { return segment.summary.id; } return segment.item.id; } function ChatActivitySegmentView({ agent, identityPubkey, profiles, segment, showAgentIdentity, suppressPromptMessage, }: { agent: ManagedAgent | null; identityPubkey?: string; profiles?: UserProfileLookup; segment: TranscriptTurnSegment; showAgentIdentity: boolean; suppressPromptMessage: boolean; }) { if (segment.kind === "prompt") { return ( <> {!suppressPromptMessage ? ( ) : null} {segment.context ? ( } entrance={hasRecentEntrance(segment.context.timestamp)} icon={} label="Captured prompt context" timestamp={segment.context.timestamp} tone="muted" /> ) : null} ); } if (segment.kind === "setup") { // "Turn started" / "Session ready" plumbing rows add noise to every // turn without telling the user anything actionable — the Working // marker (and its raw-event dropdown) already covers turn liveness. return null; } if (segment.kind === "summary") { return ; } return ( ); } function ChatActivityItemView({ agent, identityPubkey, item, profiles, showAgentIdentity, suppressPromptMessage, }: { agent: ManagedAgent | null; identityPubkey?: string; item: TranscriptItem; profiles?: UserProfileLookup; showAgentIdentity: boolean; suppressPromptMessage: boolean; }) { if (item.type === "message") { if (item.role === "user" && suppressPromptMessage) { return null; } if (item.role === "assistant" && !isHumanFacingAssistantMessage(item)) { return null; } if (cleanChatMessageText(item).length === 0) return null; return ( ); } if (item.type === "tool") { return ; } if (item.type === "thought") { return ( } entrance={hasRecentEntrance(item.timestamp)} icon={} label={item.title || "Thinking"} timestamp={item.timestamp} tone="muted" /> ); } if (item.type === "plan") { const label = item.isUpdate ? item.text ? `Updated plan · ${item.text}` : "Updated plan" : "Updated plan"; return ( ) } entrance={hasRecentEntrance(item.timestamp)} icon={} label={label} timestamp={item.timestamp} tone="default" /> ); } if (item.type === "metadata") { return ( } entrance={hasRecentEntrance(item.timestamp)} icon={} label={`Captured ${item.title.toLowerCase()}`} timestamp={item.timestamp} tone="muted" /> ); } if (isSetupLifecycleItem(item)) { return null; } return ( : null} entrance={hasRecentEntrance(item.timestamp)} icon={lifecycleIcon(item)} label={item.title} timestamp={item.timestamp} tone={item.renderClass === "error" ? "danger" : "muted"} /> ); } function ChatTranscriptMessageRow({ agent, identityPubkey, item, profiles, showAgentIdentity = true, }: { agent: ManagedAgent | null; identityPubkey?: string; item: Extract; profiles?: UserProfileLookup; showAgentIdentity?: boolean; }) { const isUser = item.role === "user"; const pubkey = isUser ? (item.authorPubkey ?? identityPubkey ?? "") : (agent?.pubkey ?? item.authorPubkey ?? ""); const label = pubkey ? resolveUserLabel({ pubkey, currentPubkey: identityPubkey, fallbackName: isUser ? item.title || "You" : agent?.name || "Fizz", profiles, preferResolvedSelfLabel: !isUser, }) : isUser ? item.title || "You" : agent?.name || "Fizz"; const profile = pubkey ? profiles?.[normalizePubkey(pubkey)] : null; const avatarUrl = isUser ? (profile?.avatarUrl ?? null) : (profile?.avatarUrl ?? agent?.avatarUrl ?? null); const text = item.text.trim(); const displayText = cleanChatMessageText(item); const entrance = hasRecentEntrance(item.timestamp); const hideIdentity = !isUser && !showAgentIdentity; return ( {!isUser && !hideIdentity ? ( ) : null} {!hideIdentity && !isUser ? ( {label} ) : null} {isUser ? ( ) : ( )} ); } function SummaryMarker({ summary }: { summary: TranscriptSameKindSummary }) { return ( {summary.items.map((item) => ( ))} } entrance={hasRecentEntrance(summary.timestamp)} icon={summaryIcon(summary)} label={summary.label} timestamp={summary.timestamp} tone="default" /> ); } function CompletedWorkMarker({ items }: { items: TranscriptItem[] }) { const [isOpen, setIsOpen] = React.useState(false); // Duration spans ALL items (setup lifecycle marks the turn's true start), // but the expanded list hides the "Turn started"/"Session ready" plumbing. const label = completedWorkLabel(items); const detailItems = items.filter((item) => !isSetupLifecycleItem(item)); const entrance = hasRecentEntrance(items[items.length - 1]?.timestamp); return (
{isOpen ? (
{detailItems.map((item) => ( ))}
) : null} ); } // How many of the turn's most recent raw observer events the "Working" // dropdown shows. Enough to read the current backend activity without // rendering the whole turn's wire history. const LIVE_TURN_RAW_EVENT_LIMIT = 12; function LiveTurnMarker({ agentPubkey, icon, startedAt, turnId, }: { agentPubkey?: string | null; icon: React.ReactNode; startedAt: string | null; turnId: string; }) { const elapsedSeconds = useElapsedSeconds(startedAt); const { events } = useObserverEvents(Boolean(agentPubkey), agentPubkey); const turnEvents = React.useMemo( () => events .filter((event) => event.turnId === turnId) .slice(-LIVE_TURN_RAW_EVENT_LIMIT), [events, turnId], ); return ( 0 ? (
) : ( Waiting for the first backend event… ) } // No entrance animation: this row mounts and unmounts with every gap // between tool executions, and replaying the fade on each reappearance // reads as blinking instead of a steady status. icon={icon} label="Working" loading meta={formatElapsedCounter(elapsedSeconds)} timestamp={startedAt ?? undefined} tone="muted" /> ); } function CompletedWorkDetailRow({ item }: { item: TranscriptItem }) { const details = activityItemDetails(item); return ( ); } function ToolMarker({ item, }: { item: Extract; }) { const compactSummary = buildCompactToolSummary(item); const hasArgs = Object.keys(item.args).length > 0; const hasResult = item.result.trim().length > 0; const canonicalToolName = item.buzzToolName ?? item.toolName; const buzzTool = getBuzzToolInfo(canonicalToolName); const shellCommand = getShellCommand(item, compactSummary); const showDetails = hasArgs || hasResult || compactSummary.fileEditDiff !== null || compactSummary.thumbnailSrc !== null || shellCommand !== null; return ( ) : null } entrance={hasRecentEntrance(item.timestamp)} icon={toolIcon(item, compactSummary)} label={toolLabel(item)} loading={isToolRunning(item)} meta={getToolDurationDisplay(item)} timestamp={item.timestamp} tone={ item.isError || item.status === "failed" ? "danger" : item.status === "executing" || item.status === "pending" ? "warning" : "default" } /> ); } function ActivityPreviewLine({ item }: { item: TranscriptItem }) { if (item.type === "tool") { const summary = buildCompactToolSummary(item); return (
{toolLabel(item)} {summary.preview && summary.kind !== "shell" ? ( {summary.preview} ) : null}
); } return (
{activityItemLabel(item)}
); } function activityItemDetails(item: TranscriptItem) { if (item.type === "tool") { const compactSummary = buildCompactToolSummary(item); const hasArgs = Object.keys(item.args).length > 0; const hasResult = item.result.trim().length > 0; const canonicalToolName = item.buzzToolName ?? item.toolName; const buzzTool = getBuzzToolInfo(canonicalToolName); const shellCommand = getShellCommand(item, compactSummary); return ( ); } if (item.type === "metadata") { return ; } if (item.type === "plan" || item.type === "thought") { return ; } if (item.type === "lifecycle") { return item.text ? : null; } return null; } function PromptSections({ sections }: { sections: PromptSection[] }) { if (sections.length === 0) { return (

No context captured.

); } return (
{sections.map((section) => (
{section.title}
))}
); } function isCompletedTurn( block: Extract, ) { if (!collectAssistantMessages(block).some((item) => item.text.trim())) { return false; } return !collectTurnItems(block).some( (item) => item.type === "tool" && (item.status === "executing" || item.status === "pending"), ); } function collectAssistantMessages( block: Extract, ) { return collectTurnItems(block).filter( (item): item is Extract => item.type === "message" && item.role === "assistant", ); } function collectFinalAssistantMessages( block: Extract, ) { const messages = collectAssistantMessages(block).filter( isHumanFacingAssistantMessage, ); const finalMessage = messages[messages.length - 1]; return finalMessage ? [finalMessage] : []; } function collectCompletedActivityItems( block: Extract, ) { const items: TranscriptItem[] = []; for (const segment of block.segments) { if (segment.kind === "prompt") { items.push(...segment.setup); if (segment.context) { items.push(segment.context); } } else if (segment.kind === "setup") { items.push(...segment.items); } else if (segment.kind === "summary") { items.push(...segment.summary.items); } else if ( segment.item.type !== "message" || segment.item.role !== "assistant" ) { items.push(segment.item); } } return items.filter((item) => activityItemLabel(item).length > 0); } function collectTurnItems( block: Extract, ) { const items: TranscriptItem[] = []; for (const segment of block.segments) { if (segment.kind === "prompt") { items.push(segment.user, ...segment.setup); if (segment.context) { items.push(segment.context); } } else if (segment.kind === "setup") { items.push(...segment.items); } else if (segment.kind === "summary") { items.push(...segment.summary.items); } else { items.push(segment.item); } } return items; } function isActivityItemLive(item: TranscriptItem) { return item.type === "tool" && isToolRunning(item); } function hasLiveActivityItem( block: Extract, ) { return collectTurnItems(block).some(isActivityItemLive); } function liveTurnMarkerIcon( block: Extract, ) { const latestTool = [...collectTurnItems(block)] .reverse() .find( (item): item is Extract => item.type === "tool", ); if (!latestTool) { return ; } return toolCategoryIcon(latestTool, buildCompactToolSummary(latestTool)); } function getTurnStartedAt( block: Extract, ) { const items = collectTurnItems(block); const turnStarted = items.find( (item): item is Extract => item.type === "lifecycle" && ((item.acpSource ?? "") === "turn_started" || item.title.toLowerCase().includes("turn started")), ); if (turnStarted) { return turnStarted.timestamp; } const timestamps = items .map((item) => Date.parse(item.timestamp)) .filter((value) => Number.isFinite(value)); if (timestamps.length === 0) { return null; } return new Date(Math.min(...timestamps)).toISOString(); } function useElapsedSeconds(startedAt: string | null) { const [now, setNow] = React.useState(() => Date.now()); React.useEffect(() => { const interval = window.setInterval(() => { setNow(Date.now()); }, 1000); return () => window.clearInterval(interval); }, []); if (!startedAt) { return null; } const start = Date.parse(startedAt); if (!Number.isFinite(start)) { return null; } return Math.max(0, Math.floor((now - start) / 1000)); } function formatElapsedCounter(seconds: number | null) { if (seconds === null) { return null; } if (seconds < 60) { return `${seconds}s`; } const minutes = Math.floor(seconds / 60); const remainder = seconds % 60; return remainder > 0 ? `${minutes}m ${remainder}s` : `${minutes}m`; } function isToolRunning(item: Extract) { return item.status === "executing" || item.status === "pending"; } function activityItemIcon(item: TranscriptItem) { const toolIconNode = toolActivityItemIcon(item); if (toolIconNode) { return toolIconNode; } if (item.type === "metadata") { return ; } if (item.type === "plan") { return ; } if (item.type === "thought") { return ; } if (item.type === "lifecycle") { return lifecycleIcon(item); } return ; } function lifecycleIcon(item: Extract) { const source = item.acpSource ?? ""; const title = item.title.toLowerCase(); if (source === "turn_started" || title.includes("turn started")) { return ; } if (source === "session_resolved" || title.includes("session ready")) { return ; } const renderClass = item.renderClass; if (renderClass === "permission") { return ; } if (renderClass === "error") { return ; } if (renderClass === "status") { return ; } return ; }