refactor chat components to improve state management and enhance UI responsiveness; replace ChatInputBar with ChatInputWithMentions, and update ChatSidebar and TabBar for better tab handling

This commit is contained in:
tusharmagar 2026-02-18 17:29:57 +05:30
parent 09288571aa
commit abb9f9b2ca
5 changed files with 1035 additions and 789 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,195 @@
import { useCallback, useEffect } from 'react'
import { ArrowUp, LoaderIcon, Square } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import {
type FileMention,
type PromptInputMessage,
PromptInputProvider,
PromptInputTextarea,
usePromptInputController,
} from '@/components/ai-elements/prompt-input'
interface ChatInputInnerProps {
onSubmit: (message: PromptInputMessage, mentions?: FileMention[]) => void
onStop?: () => void
isProcessing: boolean
isStopping?: boolean
presetMessage?: string
onPresetMessageConsumed?: () => void
runId?: string | null
initialDraft?: string
onDraftChange?: (text: string) => void
}
function ChatInputInner({
onSubmit,
onStop,
isProcessing,
isStopping,
presetMessage,
onPresetMessageConsumed,
runId,
initialDraft,
onDraftChange,
}: ChatInputInnerProps) {
const controller = usePromptInputController()
const message = controller.textInput.value
const canSubmit = Boolean(message.trim()) && !isProcessing
// Restore the tab draft when this input mounts.
useEffect(() => {
if (initialDraft) {
controller.textInput.setInput(initialDraft)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
onDraftChange?.(message)
}, [message, onDraftChange])
useEffect(() => {
if (presetMessage) {
controller.textInput.setInput(presetMessage)
onPresetMessageConsumed?.()
}
}, [presetMessage, controller.textInput, onPresetMessageConsumed])
const handleSubmit = useCallback(() => {
if (!canSubmit) return
onSubmit({ text: message.trim(), files: [] }, controller.mentions.mentions)
controller.textInput.clear()
controller.mentions.clearMentions()
}, [canSubmit, message, onSubmit, controller])
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
handleSubmit()
}
}, [handleSubmit])
useEffect(() => {
const onDragOver = (e: DragEvent) => {
if (e.dataTransfer?.types?.includes('Files')) {
e.preventDefault()
}
}
const onDrop = (e: DragEvent) => {
if (e.dataTransfer?.types?.includes('Files')) {
e.preventDefault()
}
if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {
const paths = Array.from(e.dataTransfer.files)
.map((file) => window.electronUtils?.getPathForFile(file))
.filter(Boolean)
if (paths.length > 0) {
const currentText = controller.textInput.value
const pathText = paths.join(' ')
controller.textInput.setInput(currentText ? `${currentText} ${pathText}` : pathText)
}
}
}
document.addEventListener('dragover', onDragOver)
document.addEventListener('drop', onDrop)
return () => {
document.removeEventListener('dragover', onDragOver)
document.removeEventListener('drop', onDrop)
}
}, [controller])
return (
<div className="flex items-center gap-2 rounded-lg border border-border bg-background px-4 py-4 shadow-none">
<PromptInputTextarea
placeholder="Type your message..."
onKeyDown={handleKeyDown}
autoFocus
focusTrigger={runId}
className="min-h-6 rounded-none border-0 py-0 shadow-none focus-visible:ring-0"
/>
{isProcessing ? (
<Button
size="icon"
onClick={onStop}
title={isStopping ? 'Click again to force stop' : 'Stop generation'}
className={cn(
'h-7 w-7 shrink-0 rounded-full transition-all',
isStopping
? 'bg-destructive text-destructive-foreground hover:bg-destructive/90'
: 'bg-primary text-primary-foreground hover:bg-primary/90'
)}
>
{isStopping ? (
<LoaderIcon className="h-4 w-4 animate-spin" />
) : (
<Square className="h-3 w-3 fill-current" />
)}
</Button>
) : (
<Button
size="icon"
onClick={handleSubmit}
disabled={!canSubmit}
className={cn(
'h-7 w-7 shrink-0 rounded-full transition-all',
canSubmit
? 'bg-primary text-primary-foreground hover:bg-primary/90'
: 'bg-muted text-muted-foreground'
)}
>
<ArrowUp className="h-4 w-4" />
</Button>
)}
</div>
)
}
export interface ChatInputWithMentionsProps {
knowledgeFiles: string[]
recentFiles: string[]
visibleFiles: string[]
onSubmit: (message: PromptInputMessage, mentions?: FileMention[]) => void
onStop?: () => void
isProcessing: boolean
isStopping?: boolean
presetMessage?: string
onPresetMessageConsumed?: () => void
runId?: string | null
initialDraft?: string
onDraftChange?: (text: string) => void
}
export function ChatInputWithMentions({
knowledgeFiles,
recentFiles,
visibleFiles,
onSubmit,
onStop,
isProcessing,
isStopping,
presetMessage,
onPresetMessageConsumed,
runId,
initialDraft,
onDraftChange,
}: ChatInputWithMentionsProps) {
return (
<PromptInputProvider knowledgeFiles={knowledgeFiles} recentFiles={recentFiles} visibleFiles={visibleFiles}>
<ChatInputInner
onSubmit={onSubmit}
onStop={onStop}
isProcessing={isProcessing}
isStopping={isStopping}
presetMessage={presetMessage}
onPresetMessageConsumed={onPresetMessageConsumed}
runId={runId}
initialDraft={initialDraft}
onDraftChange={onDraftChange}
/>
</PromptInputProvider>
)
}

View file

@ -1,13 +1,11 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ArrowUp, Expand, LoaderIcon, SquarePen, Square } from 'lucide-react'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Expand, Minimize2, SquarePen } from 'lucide-react'
import type { ToolUIPart } from 'ai'
import z from 'zod'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import {
Conversation,
ConversationContent,
@ -19,22 +17,17 @@ import {
MessageContent,
MessageResponse,
} from '@/components/ai-elements/message'
import { Shimmer } from '@/components/ai-elements/shimmer'
import { Tool, ToolContent, ToolHeader, ToolInput, ToolOutput } from '@/components/ai-elements/tool'
import { PermissionRequest } from '@/components/ai-elements/permission-request'
import { AskHumanRequest } from '@/components/ai-elements/ask-human-request'
import { Suggestions } from '@/components/ai-elements/suggestions'
import { type PromptInputMessage, type FileMention } from '@/components/ai-elements/prompt-input'
import { useMentionDetection } from '@/hooks/use-mention-detection'
import { MentionPopover } from '@/components/mention-popover'
import { toKnowledgePath, wikiLabel } from '@/lib/wiki-links'
import { getMentionHighlightSegments } from '@/lib/mention-highlights'
import { ToolPermissionRequestEvent, AskHumanRequestEvent } from '@x/shared/src/runs.js'
import z from 'zod'
import React from 'react'
import { FileCardProvider } from '@/contexts/file-card-context'
import { MarkdownPreOverride } from '@/components/ai-elements/markdown-code-override'
import { TabBar, type ChatTab } from '@/components/tab-bar'
import { ChatInputWithMentions } from '@/components/chat-input-with-mentions'
interface ChatMessage {
id: string
@ -61,6 +54,14 @@ interface ErrorMessage {
type ConversationItem = ChatMessage | ToolCall | ErrorMessage
type ChatTabViewState = {
conversation: ConversationItem[]
currentAssistantMessage: string
pendingAskHumanRequests: Map<string, z.infer<typeof AskHumanRequestEvent>>
allPermissionRequests: Map<string, z.infer<typeof ToolPermissionRequestEvent>>
permissionResponses: Map<string, 'approve' | 'deny'>
}
type ToolState = 'input-streaming' | 'input-available' | 'output-available' | 'output-error'
const isChatMessage = (item: ConversationItem): item is ChatMessage => 'role' in item
@ -107,28 +108,60 @@ const normalizeToolOutput = (output: ToolCall['result'] | undefined, status: Too
const streamdownComponents = { pre: MarkdownPreOverride }
const MIN_WIDTH = 300
const MAX_WIDTH = 700
const DEFAULT_WIDTH = 400
const MIN_WIDTH = 360
const MAX_WIDTH = 1600
const MIN_MAIN_PANE_WIDTH = 420
const MIN_MAIN_PANE_RATIO = 0.3
const DEFAULT_WIDTH = 460
const RIGHT_PANE_WIDTH_STORAGE_KEY = 'x:right-pane-width'
function clampPaneWidth(width: number, maxWidth: number = MAX_WIDTH): number {
const boundedMax = Math.max(0, Math.min(MAX_WIDTH, maxWidth))
const boundedMin = Math.min(MIN_WIDTH, boundedMax)
return Math.min(boundedMax, Math.max(boundedMin, width))
}
function getInitialPaneWidth(defaultWidth: number): number {
const fallback = clampPaneWidth(defaultWidth)
if (typeof window === 'undefined') return fallback
try {
const raw = window.localStorage.getItem(RIGHT_PANE_WIDTH_STORAGE_KEY)
if (!raw) return fallback
const parsed = Number(raw)
if (!Number.isFinite(parsed)) return fallback
return clampPaneWidth(parsed)
} catch {
return fallback
}
}
interface ChatSidebarProps {
defaultWidth?: number
isOpen?: boolean
onNewChat: () => void
isMaximized?: boolean
chatTabs: ChatTab[]
activeChatTabId: string
getChatTabTitle: (tab: ChatTab) => string
isChatTabProcessing: (tab: ChatTab) => boolean
onSwitchChatTab: (tabId: string) => void
onCloseChatTab: (tabId: string) => void
onNewChatTab: () => void
onOpenFullScreen?: () => void
conversation: ConversationItem[]
currentAssistantMessage: string
chatTabStates?: Record<string, ChatTabViewState>
isProcessing: boolean
isStopping?: boolean
onStop?: () => void
message: string
onMessageChange: (message: string) => void
onSubmit: (message: PromptInputMessage, mentions?: FileMention[]) => void
knowledgeFiles?: string[]
recentFiles?: string[]
visibleFiles?: string[]
selectedPath?: string | null
pendingPermissionRequests?: Map<string, z.infer<typeof ToolPermissionRequestEvent>>
runId?: string | null
presetMessage?: string
onPresetMessageConsumed?: () => void
initialDraft?: string
onDraftChange?: (text: string) => void
pendingAskHumanRequests?: Map<string, z.infer<typeof AskHumanRequestEvent>>
allPermissionRequests?: Map<string, z.infer<typeof ToolPermissionRequestEvent>>
permissionResponses?: Map<string, 'approve' | 'deny'>
@ -140,20 +173,30 @@ interface ChatSidebarProps {
export function ChatSidebar({
defaultWidth = DEFAULT_WIDTH,
isOpen = true,
onNewChat,
isMaximized = false,
chatTabs,
activeChatTabId,
getChatTabTitle,
isChatTabProcessing,
onSwitchChatTab,
onCloseChatTab,
onNewChatTab,
onOpenFullScreen,
conversation,
currentAssistantMessage,
chatTabStates = {},
isProcessing,
isStopping,
onStop,
message,
onMessageChange,
onSubmit,
knowledgeFiles = [],
recentFiles = [],
visibleFiles = [],
selectedPath,
runId,
presetMessage,
onPresetMessageConsumed,
initialDraft,
onDraftChange,
pendingAskHumanRequests = new Map(),
allPermissionRequests = new Map(),
permissionResponses = new Map(),
@ -161,91 +204,62 @@ export function ChatSidebar({
onAskHumanResponse,
onOpenKnowledgeFile,
}: ChatSidebarProps) {
const [width, setWidth] = useState(defaultWidth)
const [width, setWidth] = useState(() => getInitialPaneWidth(defaultWidth))
const [isResizing, setIsResizing] = useState(false)
const [showContent, setShowContent] = useState(isOpen)
const [localPresetMessage, setLocalPresetMessage] = useState<string | undefined>(undefined)
const paneRef = useRef<HTMLDivElement>(null)
const startXRef = useRef(0)
const startWidthRef = useRef(0)
const getMaxAllowedWidth = useCallback(() => {
if (typeof window === 'undefined') return MAX_WIDTH
const paneElement = paneRef.current
const splitContainer = paneElement?.parentElement
const mainPane = splitContainer?.querySelector<HTMLElement>('[data-slot="sidebar-inset"]')
const paneWidth = paneElement?.getBoundingClientRect().width ?? 0
const mainPaneWidth = mainPane?.getBoundingClientRect().width ?? 0
const splitWidth = paneWidth + mainPaneWidth
const fallbackWidth = splitContainer?.clientWidth ?? window.innerWidth
const availableSplitWidth = splitWidth > 0 ? splitWidth : fallbackWidth
const minMainPaneWidth = Math.min(
availableSplitWidth,
Math.max(
MIN_MAIN_PANE_WIDTH,
Math.floor(availableSplitWidth * MIN_MAIN_PANE_RATIO)
)
)
return Math.max(0, availableSplitWidth - minMainPaneWidth)
}, [])
// Delay showing content when opening, hide immediately when closing
useEffect(() => {
if (isOpen) {
const timer = setTimeout(() => setShowContent(true), 150)
return () => clearTimeout(timer)
} else {
setShowContent(false)
}
setShowContent(false)
}, [isOpen])
const startXRef = useRef(0)
const startWidthRef = useRef(0)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const highlightRef = useRef<HTMLDivElement>(null)
const [mentions, setMentions] = useState<FileMention[]>([])
const autoMentionRef = useRef<{ path: string; displayName: string } | null>(null)
const lastSelectedPathRef = useRef<string | null>(null)
// Build mention labels for highlighting (handles multi-word names like "AI Agents")
const mentionLabels = useMemo(() => {
if (knowledgeFiles.length === 0) return []
const labels = knowledgeFiles
.map((path) => wikiLabel(path))
.map((label) => label.trim())
.filter(Boolean)
return Array.from(new Set(labels))
}, [knowledgeFiles])
const { activeMention, cursorCoords } = useMentionDetection(
textareaRef,
message,
knowledgeFiles.length > 0
)
// Use proper regex-based highlight segmentation that handles multi-word names
const mentionHighlights = useMemo(
() => getMentionHighlightSegments(message, activeMention, mentionLabels),
[message, activeMention, mentionLabels]
)
// Sync highlight overlay scroll with textarea
const syncHighlightScroll = useCallback(() => {
const textarea = textareaRef.current
const highlight = highlightRef.current
if (!textarea || !highlight) return
highlight.scrollTop = textarea.scrollTop
highlight.scrollLeft = textarea.scrollLeft
}, [])
useEffect(() => {
syncHighlightScroll()
}, [message, mentionHighlights.hasHighlights, syncHighlightScroll])
if (typeof window === 'undefined') return
try {
window.localStorage.setItem(RIGHT_PANE_WIDTH_STORAGE_KEY, String(width))
} catch {
// Ignore persistence failures and keep in-memory behavior.
}
}, [width])
const handleMentionSelect = useCallback(
(path: string, displayName: string) => {
if (!activeMention) return
useEffect(() => {
const clampToAvailableWidth = () => {
const maxAllowedWidth = getMaxAllowedWidth()
setWidth((prev) => clampPaneWidth(prev, maxAllowedWidth))
}
const beforeAt = message.substring(0, activeMention.triggerIndex)
const afterQuery = message.substring(
activeMention.triggerIndex + 1 + activeMention.query.length
)
const newText = `${beforeAt}@${displayName} ${afterQuery}`
onMessageChange(newText)
const fullPath = toKnowledgePath(path)
if (fullPath) {
setMentions(prev => {
if (prev.some(m => m.path === fullPath)) return prev
return [...prev, { id: `mention-${Date.now()}`, path: fullPath, displayName }]
})
}
textareaRef.current?.focus()
},
[activeMention, message, onMessageChange]
)
const handleMentionClose = useCallback(() => {
// The popover handles its own closing
}, [])
clampToAvailableWidth()
window.addEventListener('resize', clampToAvailableWidth)
return () => window.removeEventListener('resize', clampToAvailableWidth)
}, [getMaxAllowedWidth])
const handleMouseDown = useCallback((e: React.MouseEvent) => {
e.preventDefault()
@ -253,10 +267,10 @@ export function ChatSidebar({
startWidthRef.current = width
setIsResizing(true)
const handleMouseMove = (e: MouseEvent) => {
const delta = startXRef.current - e.clientX
const newWidth = Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, startWidthRef.current + delta))
setWidth(newWidth)
const handleMouseMove = (event: MouseEvent) => {
const delta = startXRef.current - event.clientX
const maxAllowedWidth = getMaxAllowedWidth()
setWidth(clampPaneWidth(startWidthRef.current + delta, maxAllowedWidth))
}
const handleMouseUp = () => {
@ -267,127 +281,33 @@ export function ChatSidebar({
document.addEventListener('mousemove', handleMouseMove)
document.addEventListener('mouseup', handleMouseUp)
}, [width])
}, [width, getMaxAllowedWidth])
// Auto-focus textarea when sidebar opens or when conversation is cleared (new chat)
useEffect(() => {
// Focus when conversation is empty (new chat started)
if (conversation.length === 0) {
const timer = setTimeout(() => {
textareaRef.current?.focus()
}, 50)
return () => clearTimeout(timer)
}
}, [conversation.length])
// Auto-populate with @currentfile when switching knowledge files
useEffect(() => {
if (selectedPath === lastSelectedPathRef.current) return
lastSelectedPathRef.current = selectedPath ?? null
if (!selectedPath || !selectedPath.startsWith('knowledge/') || !selectedPath.endsWith('.md')) {
return
}
const displayName = wikiLabel(selectedPath)
const previousAuto = autoMentionRef.current
const trimmed = message.trim()
const previousToken = previousAuto ? `@${previousAuto.displayName}` : null
const shouldReplace = !trimmed || (previousToken && trimmed === previousToken)
if (!shouldReplace) {
return
}
const nextText = `@${displayName} `
if (message !== nextText) {
onMessageChange(nextText)
}
setMentions((prev) => {
const withoutPrevious = previousAuto
? prev.filter((mention) => mention.path !== previousAuto.path)
: prev
if (withoutPrevious.some((mention) => mention.path === selectedPath)) {
return withoutPrevious
}
return [
...withoutPrevious,
{
id: `mention-auto-${Date.now()}`,
path: selectedPath,
displayName,
},
]
})
autoMentionRef.current = { path: selectedPath, displayName }
}, [selectedPath, message, onMessageChange])
const hasConversation = conversation.length > 0 || currentAssistantMessage
const canSubmit = Boolean(message.trim()) && !isProcessing
const handleSubmit = () => {
const trimmed = message.trim()
if (trimmed && !isProcessing) {
onSubmit({ text: trimmed, files: [] }, mentions)
setMentions([])
}
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
// If mention popover is open, let it handle navigation keys
if (activeMention && ['ArrowDown', 'ArrowUp', 'Tab', 'Escape'].includes(e.key)) {
return
}
if (e.key === 'Enter') {
// If mention popover is open, Enter should select the item
if (activeMention) {
return
}
if (!e.shiftKey) {
e.preventDefault()
handleSubmit()
}
}
// Handle backspace to delete entire mention at once
if (e.key === 'Backspace') {
const textarea = e.currentTarget
const cursorPos = textarea.selectionStart
const selectionEnd = textarea.selectionEnd
// Only handle if no text is selected (cursor is at a single position)
if (cursorPos !== selectionEnd) return
// Check if cursor is right after a mention
for (const label of mentionLabels) {
const mentionText = `@${label}`
const startPos = cursorPos - mentionText.length
if (startPos >= 0) {
const textBefore = message.substring(startPos, cursorPos)
if (textBefore === mentionText) {
// Check if it's at word boundary (start of string or preceded by whitespace)
if (startPos === 0 || /\s/.test(message[startPos - 1])) {
e.preventDefault()
const newText = message.substring(0, startPos) + message.substring(cursorPos)
onMessageChange(newText)
// Remove the mention from state
setMentions(prev => prev.filter(m => m.displayName !== label))
// Set cursor position after React updates
setTimeout(() => {
textarea.selectionStart = startPos
textarea.selectionEnd = startPos
}, 0)
return
}
}
}
}
}
}
const activeTabState = useMemo<ChatTabViewState>(() => ({
conversation,
currentAssistantMessage,
pendingAskHumanRequests,
allPermissionRequests,
permissionResponses,
}), [
conversation,
currentAssistantMessage,
pendingAskHumanRequests,
allPermissionRequests,
permissionResponses,
])
const emptyTabState = useMemo<ChatTabViewState>(() => ({
conversation: [],
currentAssistantMessage: '',
pendingAskHumanRequests: new Map(),
allPermissionRequests: new Map(),
permissionResponses: new Map(),
}), [])
const getTabState = useCallback((tabId: string): ChatTabViewState => {
if (tabId === activeChatTabId) return activeTabState
return chatTabStates[tabId] ?? emptyTabState
}, [activeChatTabId, activeTabState, chatTabStates, emptyTabState])
const hasConversation = activeTabState.conversation.length > 0 || Boolean(activeTabState.currentAssistantMessage)
const renderConversationItem = (item: ConversationItem) => {
if (isChatMessage(item)) {
@ -410,16 +330,10 @@ export function ChatSidebar({
const input = normalizeToolInput(item.input)
return (
<Tool key={item.id}>
<ToolHeader
title={item.name}
type={`tool-${item.name}`}
state={toToolState(item.status)}
/>
<ToolHeader title={item.name} type={`tool-${item.name}`} state={toToolState(item.status)} />
<ToolContent>
<ToolInput input={input} />
{output !== null ? (
<ToolOutput output={output} errorText={errorText} />
) : null}
{output !== null ? <ToolOutput output={output} errorText={errorText} /> : null}
</ToolContent>
</Tool>
)
@ -438,218 +352,188 @@ export function ChatSidebar({
return null
}
const displayWidth = isOpen ? width : 0
const paneStyle = useMemo<React.CSSProperties>(() => {
if (!isOpen) {
return { width: 0, flex: '0 0 auto' }
}
if (isMaximized) {
// In maximize mode the pane should grow into the freed left space,
// not add extra width to the right and overflow the app viewport.
return { width: 0, flex: '1 1 auto' }
}
return { width, flex: '0 0 auto' }
}, [isOpen, isMaximized, width])
return (
<div
ref={paneRef}
className={cn(
"relative flex flex-col border-l border-border bg-background shrink-0 overflow-hidden",
!isResizing && "transition-[width] duration-200 ease-linear"
'relative flex min-w-0 flex-col overflow-hidden border-l border-border bg-background',
!isResizing && 'transition-[width] duration-200 ease-linear'
)}
style={{ width: displayWidth }}
style={paneStyle}
>
{/* Resize handle */}
<div
onMouseDown={handleMouseDown}
className={cn(
"absolute inset-y-0 left-0 z-20 w-4 -translate-x-1/2 cursor-col-resize",
"after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] after:transition-colors",
"hover:after:bg-sidebar-border",
isResizing && "after:bg-primary"
)}
/>
{!isMaximized && (
<div
onMouseDown={handleMouseDown}
className={cn(
'absolute inset-y-0 left-0 z-20 w-4 -translate-x-1/2 cursor-col-resize',
'after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] after:transition-colors',
'hover:after:bg-sidebar-border',
isResizing && 'after:bg-primary'
)}
/>
)}
{/* Content - delayed on open, hidden immediately on close to avoid layout issues during animation */}
{showContent && (
<>
{/* Header - minimal, expand and new chat buttons */}
<header className="titlebar-drag-region flex h-10 shrink-0 items-center justify-end gap-1 px-2 bg-sidebar">
<header className="titlebar-drag-region flex h-10 shrink-0 items-stretch border-b border-border bg-sidebar">
<TabBar
tabs={chatTabs}
activeTabId={activeChatTabId}
getTabTitle={getChatTabTitle}
getTabId={(tab) => tab.id}
isProcessing={isChatTabProcessing}
onSwitchTab={onSwitchChatTab}
onCloseTab={onCloseChatTab}
/>
<Tooltip>
<TooltipTrigger asChild>
<Button variant="ghost" size="icon" onClick={onNewChat} className="titlebar-no-drag h-8 w-8 text-muted-foreground hover:text-foreground">
<SquarePen className="h-4 w-4" />
<Button
variant="ghost"
size="icon"
onClick={onNewChatTab}
className="titlebar-no-drag my-1 h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground"
>
<SquarePen className="size-5" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">New chat</TooltipContent>
<TooltipContent side="bottom">New chat tab</TooltipContent>
</Tooltip>
{onOpenFullScreen && (
<Tooltip>
<TooltipTrigger asChild>
<Button variant="ghost" size="icon" onClick={onOpenFullScreen} className="titlebar-no-drag h-8 w-8 text-muted-foreground hover:text-foreground">
<Expand className="h-4 w-4" />
<Button
variant="ghost"
size="icon"
onClick={onOpenFullScreen}
className="titlebar-no-drag my-1 mr-2 h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground"
>
{isMaximized ? <Minimize2 className="size-5" /> : <Expand className="size-5" />}
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">Full screen chat</TooltipContent>
<TooltipContent side="bottom">
{isMaximized ? 'Restore two-pane view' : 'Maximize right pane'}
</TooltipContent>
</Tooltip>
)}
</header>
{/* Conversation area */}
<FileCardProvider onOpenKnowledgeFile={onOpenKnowledgeFile ?? (() => {})}>
<div className="flex min-h-0 flex-1 flex-col relative">
<Conversation className="relative flex-1 overflow-y-auto [scrollbar-gutter:stable]">
<ScrollPositionPreserver />
<ConversationContent className={hasConversation ? "px-4 pb-24" : "px-4 min-h-full items-center justify-center"}>
{!hasConversation ? (
<ConversationEmptyState className="h-auto">
<div className="flex flex-col items-center gap-1 text-center">
<div className="text-sm text-muted-foreground">
Ask anything...
<FileCardProvider onOpenKnowledgeFile={onOpenKnowledgeFile ?? (() => {})}>
<div className="flex min-h-0 flex-1 flex-col">
{chatTabs.map((tab) => {
const isActive = tab.id === activeChatTabId
const tabState = getTabState(tab.id)
const tabHasConversation = tabState.conversation.length > 0 || Boolean(tabState.currentAssistantMessage)
return (
<div
key={tab.id}
className={cn('min-h-0 flex-1 flex-col', isActive ? 'flex' : 'hidden')}
data-chat-tab-panel={tab.id}
aria-hidden={!isActive}
>
<Conversation className="relative flex-1 overflow-y-auto [scrollbar-gutter:stable]">
<ScrollPositionPreserver />
<ConversationContent className={tabHasConversation ? 'mx-auto w-full max-w-4xl px-3 pb-28' : 'mx-auto w-full max-w-4xl min-h-full items-center justify-center px-3 pb-0'}>
{!tabHasConversation ? (
<ConversationEmptyState className="h-auto">
<div className="text-sm text-muted-foreground">Ask anything...</div>
</ConversationEmptyState>
) : (
<>
{tabState.conversation.map((item) => {
const rendered = renderConversationItem(item)
if (isToolCall(item) && onPermissionResponse) {
const permRequest = tabState.allPermissionRequests.get(item.id)
if (permRequest) {
const response = tabState.permissionResponses.get(item.id) || null
return (
<React.Fragment key={item.id}>
{rendered}
<PermissionRequest
toolCall={permRequest.toolCall}
onApprove={() => onPermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve')}
onDeny={() => onPermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'deny')}
isProcessing={isActive && isProcessing}
response={response}
/>
</React.Fragment>
)
}
}
return rendered
})}
{onAskHumanResponse && Array.from(tabState.pendingAskHumanRequests.values()).map((request) => (
<AskHumanRequest
key={request.toolCallId}
query={request.query}
onResponse={(response) => onAskHumanResponse(request.toolCallId, request.subflow, response)}
isProcessing={isActive && isProcessing}
/>
))}
{tabState.currentAssistantMessage && (
<Message from="assistant">
<MessageContent>
<MessageResponse components={streamdownComponents}>{tabState.currentAssistantMessage}</MessageResponse>
</MessageContent>
</Message>
)}
{isActive && isProcessing && !tabState.currentAssistantMessage && (
<Message from="assistant">
<MessageContent>
<Shimmer duration={1}>Thinking...</Shimmer>
</MessageContent>
</Message>
)}
</>
)}
</ConversationContent>
</Conversation>
</div>
</div>
</ConversationEmptyState>
) : (
<>
{conversation.map(item => {
const rendered = renderConversationItem(item)
// If this is a tool call, check for permission request (pending or responded)
if (isToolCall(item) && onPermissionResponse) {
const permRequest = allPermissionRequests.get(item.id)
if (permRequest) {
const response = permissionResponses.get(item.id) || null
return (
<React.Fragment key={item.id}>
{rendered}
<PermissionRequest
toolCall={permRequest.toolCall}
onApprove={() => onPermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve')}
onDeny={() => onPermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'deny')}
isProcessing={isProcessing}
response={response}
/>
</React.Fragment>
)
}
}
return rendered
})}
)
})}
{/* Render pending ask-human requests */}
{onAskHumanResponse && Array.from(pendingAskHumanRequests.values()).map((request) => (
<AskHumanRequest
key={request.toolCallId}
query={request.query}
onResponse={(response) => onAskHumanResponse(request.toolCallId, request.subflow, response)}
isProcessing={isProcessing}
/>
))}
{currentAssistantMessage && (
<Message from="assistant">
<MessageContent>
<MessageResponse components={streamdownComponents}>{currentAssistantMessage}</MessageResponse>
</MessageContent>
</Message>
)}
{isProcessing && !currentAssistantMessage && (
<Message from="assistant">
<MessageContent>
<Shimmer duration={1}>Thinking...</Shimmer>
</MessageContent>
</Message>
)}
</>
)}
</ConversationContent>
</Conversation>
{/* Input area - responsive to sidebar width, matches floating bar position exactly */}
<div className="absolute bottom-6 left-14 right-6 z-10" ref={containerRef}>
{!hasConversation && (
<Suggestions
onSelect={(prompt) => {
onMessageChange(prompt)
setTimeout(() => textareaRef.current?.focus(), 0)
}}
vertical
className="mb-3"
/>
)}
<div className="flex items-center gap-2 bg-background border border-border rounded-lg shadow-none px-4 py-2.5">
<div className="relative flex-1 min-w-0">
{mentionHighlights.hasHighlights && (
<div
ref={highlightRef}
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-0 overflow-hidden whitespace-pre-wrap wrap-break-word text-sm text-transparent"
>
{mentionHighlights.segments.map((segment, index) =>
segment.highlighted ? (
<span
key={`mention-${index}`}
className="rounded bg-primary/20 text-transparent [box-decoration-break:clone] shadow-[inset_0_0_0_1px_hsl(var(--primary)/0.15),-3px_0_0_hsl(var(--primary)/0.2),3px_0_0_hsl(var(--primary)/0.2),0_-2px_0_hsl(var(--primary)/0.2),0_2px_0_hsl(var(--primary)/0.2)]"
>
{segment.text}
</span>
) : (
<span key={`text-${index}`}>{segment.text}</span>
)
<div className="sticky bottom-0 z-10 bg-background pb-12 pt-0 shadow-lg">
<div className="pointer-events-none absolute inset-x-0 -top-6 h-6 bg-linear-to-t from-background to-transparent" />
<div className="mx-auto w-full max-w-4xl px-3">
{!hasConversation && (
<Suggestions onSelect={setLocalPresetMessage} className="mb-3 justify-center" />
)}
<ChatInputWithMentions
key={activeChatTabId}
knowledgeFiles={knowledgeFiles}
recentFiles={recentFiles}
visibleFiles={visibleFiles}
onSubmit={onSubmit}
onStop={onStop}
isProcessing={isProcessing}
isStopping={isStopping}
presetMessage={localPresetMessage ?? presetMessage}
onPresetMessageConsumed={() => {
setLocalPresetMessage(undefined)
onPresetMessageConsumed?.()
}}
runId={runId}
initialDraft={initialDraft}
onDraftChange={onDraftChange}
/>
</div>
)}
<textarea
ref={textareaRef}
value={message}
onChange={(e) => onMessageChange(e.target.value)}
onKeyDown={handleKeyDown}
onScroll={syncHighlightScroll}
placeholder="Ask anything..."
rows={1}
className="relative z-10 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground resize-none max-h-32 min-h-6"
style={{ fieldSizing: 'content' } as React.CSSProperties}
/>
</div>
</div>
{isProcessing ? (
<Button
size="icon"
onClick={onStop}
title={isStopping ? "Click again to force stop" : "Stop generation"}
className={cn(
"h-7 w-7 rounded-full shrink-0 transition-all",
isStopping
? "bg-destructive text-destructive-foreground hover:bg-destructive/90"
: "bg-primary text-primary-foreground hover:bg-primary/90"
)}
>
{isStopping ? (
<LoaderIcon className="h-4 w-4 animate-spin" />
) : (
<Square className="h-3 w-3 fill-current" />
)}
</Button>
) : (
<Button
size="icon"
onClick={handleSubmit}
disabled={!canSubmit}
className={cn(
"h-7 w-7 rounded-full shrink-0 transition-all",
canSubmit
? "bg-primary text-primary-foreground hover:bg-primary/90"
: "bg-muted text-muted-foreground"
)}
>
<ArrowUp className="h-4 w-4" />
</Button>
)}
</div>
{knowledgeFiles.length > 0 && (
<MentionPopover
files={knowledgeFiles}
recentFiles={recentFiles}
visibleFiles={visibleFiles}
query={activeMention?.query ?? ''}
position={cursorCoords}
containerRef={containerRef}
onSelect={handleMentionSelect}
onClose={handleMentionClose}
open={Boolean(activeMention)}
/>
)}
</div>
</div>
</FileCardProvider>
</FileCardProvider>
</>
)}
</div>

View file

@ -20,6 +20,7 @@ interface TabBarProps<T> {
isProcessing?: (tab: T) => boolean
onSwitchTab: (tabId: string) => void
onCloseTab: (tabId: string) => void
layout?: 'fill' | 'scroll'
}
export function TabBar<T>({
@ -30,9 +31,17 @@ export function TabBar<T>({
isProcessing,
onSwitchTab,
onCloseTab,
layout = 'fill',
}: TabBarProps<T>) {
return (
<div className="titlebar-no-drag flex flex-1 self-stretch min-w-0 overflow-hidden">
<div
className={cn(
'flex flex-1 self-stretch min-w-0',
layout === 'scroll'
? 'overflow-x-auto overflow-y-hidden [scrollbar-width:none] [&::-webkit-scrollbar]:hidden'
: 'overflow-hidden'
)}
>
{tabs.map((tab, index) => {
const tabId = getTabId(tab)
const isActive = tabId === activeTabId
@ -48,12 +57,13 @@ export function TabBar<T>({
type="button"
onClick={() => onSwitchTab(tabId)}
className={cn(
"group/tab relative flex items-center gap-1.5 px-3 self-stretch text-xs min-w-0 max-w-[220px] transition-colors",
'titlebar-no-drag group/tab relative flex items-center gap-1.5 px-3 self-stretch text-xs transition-colors',
layout === 'scroll' ? 'min-w-[140px] max-w-[240px]' : 'min-w-0 max-w-[220px]',
isActive
? "bg-background text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
? 'bg-background text-foreground'
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
)}
style={{ flex: '1 1 0px' }}
style={layout === 'scroll' ? { flex: '0 0 auto' } : { flex: '1 1 0px' }}
>
{processing && (
<span className="size-1.5 shrink-0 rounded-full bg-emerald-500 animate-pulse" />

View file

@ -245,6 +245,16 @@
align-self: center;
}
/* Keep knowledge text width readable while margins collapse on narrow panes. */
.tiptap-editor .ProseMirror {
width: 100%;
max-width: min(56rem, calc(100% - clamp(0.5rem, 2.5vw, 2rem)));
margin-left: auto;
margin-right: auto;
box-sizing: border-box;
padding-left: clamp(0.5rem, 1.5vw, 1rem);
padding-right: clamp(0.5rem, 1.5vw, 1rem);
}
.wiki-link-anchor {
position: absolute;
height: 0;