import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react' import { useRouter } from 'wouter' import { IconArrowBackUp, IconChevronDown, IconChevronsRight, IconX } from '@tabler/icons-react' import { draftSessionId } from '@/lib/session-drafts' import { resolveUrl } from '@/lib/navigation' import { useCurrentTabId } from './sessions/use-selected-session' import { canSubmitComposerAction, focusComposer } from '@/client/components/shared/composer' import { AgentBlobatar } from '@/client/components/shared/agent-blobatar' import { useStickToBottom } from '@/client/features/chat/messages/use-stick-to-bottom' import { appendPreviewTurn, groupTurns } from '@/client/features/chat/messages/group-turns' import { chatNoticeLabel, interleaveNotices } from '@/client/features/chat/messages/interleave-notices' import { attachmentKey, useLive } from '@/client/features/chat/chat-store' import type { ChatPromptBubble } from '@/client/features/chat/messages/chat-prompt-bubbles' import type { ChatSendOptions } from '@/client/features/chat/chat-send' import { useWorkspaceId } from '@/client/features/workspace/workspace-context' import type { AgentTheme, SystemNotice, Turn, ViewState } from '@/lib/types' import type { ComposerBanner } from './composer/banners/composer-banner' import { ChatComposer, type ComposerAnnotationControls } from './composer/chat-composer' import { ChatEmptyState, type WelcomeDestination, resolveChatEmptyState } from './messages/chat-empty-state' import { ChatSelector } from './sessions/chat-selector' import { useWorkspaceSessions } from './sessions/api' import { TurnView } from './messages/turn-view' import { Button } from '@/client/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/client/components/ui/tooltip' import { cn } from '@/client/lib/cn' import type { AgentAvailability } from '@/client/lib/agent-availability' import { useUiStore } from '@/client/store/ui' export type ViewChatDraft = { sessionId: string onRemoveDrawing: (localId: string) => void } type ChatPanelProps = { forkedFromSessionId?: string agent: AgentTheme active?: boolean focusRequest?: number docked?: boolean chatLoaded: boolean hasWorkspaceApplets: boolean view: ViewState // The live streaming preview as a synthetic assistant turn (or null). Merged // into the trailing assistant run so a thinking-only // preview folds into the current tool group. See client/lib/preview-turn.ts. previewTurn?: Turn | null sessionId?: string | null processing: boolean composerBanner?: ComposerBanner agentAvailability: AgentAvailability annotation?: ComposerAnnotationControls send: (text: string, options?: ChatSendOptions) => Promise stop: () => void onNavigateFromWelcome: (destination: WelcomeDestination) => void onClose: () => void viewDraft?: ViewChatDraft } const EMPTY_TURNS: Turn[] = [] const EMPTY_NOTICES: SystemNotice[] = [] export function ChatPanel({ forkedFromSessionId, agent, active = true, focusRequest = 0, docked = false, chatLoaded, hasWorkspaceApplets, view, previewTurn, sessionId, processing, composerBanner, agentAvailability, annotation, send, stop, onNavigateFromWelcome, onClose, viewDraft }: ChatPanelProps) { const workspaceId = useWorkspaceId() const { base } = useRouter() const { data: sessions } = useWorkspaceSessions(workspaceId) const sourceName = sessions?.find(session => session.sessionId === forkedFromSessionId)?.summary const tabId = useCurrentTabId() const composerRef = useRef(null) const scrollRef = useRef(null) const effectiveSessionId = viewDraft?.sessionId ?? sessionId ?? draftSessionId(tabId) const modelSessionId = viewDraft ? null : (sessionId ?? null) const turns = viewDraft ? EMPTY_TURNS : view.turns const hasSentMessageFromMoi = useUiStore(state => state.hasSentMessageFromMoi) const isWorkspacePendingAnalysis = useUiStore(state => (state.workspaceIdsPendingAnalysis ?? []).includes(workspaceId) ) const attachmentsUploading = useLive(state => (state.attachments[attachmentKey(workspaceId, effectiveSessionId)] ?? []).some( attachment => attachment.kind !== 'text' && attachment.status === 'uploading' ) ) const chatReady = chatLoaded || !!viewDraft const promptDisabled = !chatReady || !canSubmitComposerAction(true, attachmentsUploading, agentAvailability) // Visual grouping: fold consecutive tool-only assistant turns into one // synthetic turn so OpenAI Codex–style traces (which serialize one // assistant message per agent step) don't render with the wider // inter-turn gap between every tool call. See `dev/turn-spacing.md`. // Group saved history once, then merge previews into just the trailing run. const effectivePreviewTurn = viewDraft ? null : previewTurn const notices = viewDraft ? EMPTY_NOTICES : view.notices const savedGroups = useMemo(() => groupTurns(turns), [turns]) const groupedTurns = useMemo( () => appendPreviewTurn(savedGroups, effectivePreviewTurn), [savedGroups, effectivePreviewTurn] ) // Grouped turns plus the renderable notices (compaction, model changes) // woven in at the moment they happened. Interleaving runs AFTER grouping so // a notice never splits a tool-only run apart. const timeline = useMemo(() => interleaveNotices(groupedTurns, notices), [groupedTurns, notices]) const lastTurnId = groupedTurns.length > 0 ? groupedTurns[groupedTurns.length - 1].id : null const effectiveProcessing = viewDraft ? false : processing const showEmptyState = !!viewDraft || (!forkedFromSessionId && chatLoaded && timeline.length === 0 && !effectiveProcessing) const showTranscript = chatLoaded && !showEmptyState const emptyStateKind = resolveChatEmptyState({ tabId, isViewDraft: !!viewDraft, hasSentMessageFromMoi, isWorkspacePendingAnalysis }) // Stick to the bottom while pinned; respect scroll-up; jump on session switch. const { atBottom, scrollToBottom, scrollToTop } = useStickToBottom(scrollRef, effectiveSessionId) useLayoutEffect(() => { if (showEmptyState && emptyStateKind !== 'overview-empty' && emptyStateKind !== 'tab-empty') scrollToTop() }, [showEmptyState, emptyStateKind, scrollToTop]) // The active chat surface owns initial focus. A monotonically increasing // request also refocuses an already-visible composer after intent actions. useEffect(() => { if (active) focusComposer(composerRef.current) }, [active, focusRequest]) // Sending always returns the user to the bottom, even if they'd scrolled up — // they expect to see their message and the reply. const handleSend = useCallback( async (text: string, options?: ChatSendOptions) => { await send(text, options) scrollToBottom() }, [send, scrollToBottom] ) const handlePromptSelect = useCallback( (prompt: ChatPromptBubble) => { if (promptDisabled) return handleSend(prompt.prompt, { directives: prompt.context }) }, [handleSend, promptDisabled] ) return (
{docked && ( } /> Undock chat )} {!viewDraft && !docked && ( )}
{forkedFromSessionId && (
)} {showEmptyState && ( )} {showTranscript && timeline.map(item => item.kind === 'notice' ? ( ) : ( ) )} {showTranscript && (
)}
{/* Jump to latest — shown only when scrolled up, so following the tail never yanks the user while they read history. */} {showTranscript && !atBottom && turns.length > 0 && ( )}
{composerBanner?.content}
) } type ChatNoticeRowProps = { notice: SystemNotice } // A quiet, centered one-liner marking a session event (context compacted, // model changed) at its place in the transcript. Kinds without designed copy // render nothing (see chatNoticeLabel). Exported for the /dev/chat-states // catalog. export function ChatNoticeRow({ notice }: ChatNoticeRowProps) { const label = chatNoticeLabel(notice) if (!label) return null return (
{label}
) }