Improve chat UI with scroll management and bash command handling

This commit is contained in:
Chris Scott committed 2025-11-28 17:07:51 -05:00
1 parent 8e955f783b
commit 64e49a8a52
9 files changed
+353 -149

No files matched your search

@@ -1,3 +1,4 @@
import { memo } from 'react'
import type { components } from '@/api/opencode-types'
import { Copy } from 'lucide-react'
import { TextPart } from './TextPart'
@@ -33,8 +34,6 @@ function getCopyableContent(part: Part, allParts?: Part[]): string {
return part.snapshot || ''
case 'agent':
return `Agent: ${part.name}`
case 'step-start':
return 'Starting step...'
case 'step-finish':
if (allParts) {
return allParts
@@ -77,7 +76,7 @@ function CopyButton({ content, title, className = "" }: { content: string; title
export function MessagePart({ part, role, allParts, partIndex, onFileClick }: MessagePartProps) {
export const MessagePart = memo(function MessagePart({ part, role, allParts, partIndex, onFileClick }: MessagePartProps) {
const copyableContent = getCopyableContent(part, allParts)
switch (part.type) {
@@ -116,16 +115,10 @@ export function MessagePart({ part, role, allParts, partIndex, onFileClick }: Me
<div className="text-sm font-medium text-blue-400">Agent: {part.name}</div>
</div>
)
case 'step-start':
return (
<div className="text-xs text-muted-foreground my-1">
→ Starting step...
</div>
)
case 'step-finish':
return (
<div className="text-xs text-muted-foreground my-1 flex items-center gap-2">
<span>✓ Step complete • ${part.cost.toFixed(4)} • {part.tokens.input + part.tokens.output} tokens</span>
<span>${part.cost.toFixed(4)} • {part.tokens.input + part.tokens.output} tokens</span>
<CopyButton content={copyableContent} title="Copy step complete" />
</div>
)
@@ -137,10 +130,6 @@ export function MessagePart({ part, role, allParts, partIndex, onFileClick }: Me
</span>
)
default:
return (
<div className="border border-zinc-800 rounded-lg p-4 my-2 bg-zinc-950">
<div className="text-xs text-zinc-500">Unknown part type</div>
</div>
)
return
}
}
})
@@ -1,4 +1,4 @@
import { memo, useRef, useEffect } from 'react'
import { memo, useRef, useEffect, useCallback } from 'react'
import { useMessages } from '@/hooks/useOpenCode'
import { useSettings } from '@/hooks/useSettings'
import { MessagePart } from './MessagePart'
@@ -10,6 +10,7 @@ interface MessageThreadProps {
directory?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
containerRef?: React.RefObject<HTMLDivElement | null>
onScrollStateChange?: (isScrolledUp: boolean) => void
}
const isMessageStreaming = (msg: MessageWithParts): boolean => {
@@ -22,23 +23,68 @@ const isMessageThinking = (msg: MessageWithParts): boolean => {
return msg.parts.length === 0 && isMessageStreaming(msg)
}
export const MessageThread = memo(function MessageThread({ opcodeUrl, sessionID, directory, onFileClick, containerRef }: MessageThreadProps) {
const SCROLL_THRESHOLD = 150
const SCROLL_DEBOUNCE_MS = 50
export const MessageThread = memo(function MessageThread({ opcodeUrl, sessionID, directory, onFileClick, containerRef, onScrollStateChange }: MessageThreadProps) {
const { data: messages, isLoading, error } = useMessages(opcodeUrl, sessionID, directory)
const { preferences } = useSettings()
const lastMessageCountRef = useRef(0)
const userJustSentMessageRef = useRef(false)
const userScrolledUpRef = useRef(false)
const hasInitialScrolledRef = useRef(false)
const scrollRAFRef = useRef<number | null>(null)
const lastScrollTimeRef = useRef(0)
const scrollToBottom = useCallback((force = false) => {
if (!containerRef?.current) return
const now = Date.now()
if (!force && now - lastScrollTimeRef.current < SCROLL_DEBOUNCE_MS) {
return
}
lastScrollTimeRef.current = now
if (scrollRAFRef.current) {
cancelAnimationFrame(scrollRAFRef.current)
}
scrollRAFRef.current = requestAnimationFrame(() => {
if (containerRef?.current) {
containerRef.current.scrollTop = containerRef.current.scrollHeight
userScrolledUpRef.current = false
onScrollStateChange?.(false)
}
scrollRAFRef.current = null
})
}, [containerRef, onScrollStateChange])
useEffect(() => {
if (!containerRef?.current) return
const container = containerRef.current
const handleScroll = () => {
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight
const isScrolledUp = distanceFromBottom > SCROLL_THRESHOLD
if (userScrolledUpRef.current !== isScrolledUp) {
userScrolledUpRef.current = isScrolledUp
onScrollStateChange?.(isScrolledUp)
}
}
container.addEventListener('scroll', handleScroll, { passive: true })
return () => container.removeEventListener('scroll', handleScroll)
}, [containerRef, onScrollStateChange])
useEffect(() => {
if (!containerRef?.current || !messages) return
const container = containerRef.current
const currentMessageCount = messages.length
const previousMessageCount = lastMessageCountRef.current
if (!hasInitialScrolledRef.current && currentMessageCount > 0) {
hasInitialScrolledRef.current = true
container.scrollTop = container.scrollHeight
scrollToBottom(true)
lastMessageCountRef.current = currentMessageCount
return
}
@@ -50,28 +96,25 @@ export const MessageThread = memo(function MessageThread({ opcodeUrl, sessionID,
const isUserMessage = lastMessage?.info.role === 'user'
if (messageAdded && isUserMessage) {
userJustSentMessageRef.current = true
container.scrollTop = container.scrollHeight
userScrolledUpRef.current = false
scrollToBottom(true)
return
}
if (!preferences?.autoScroll) return
const isNearBottom =
container.scrollHeight - container.scrollTop - container.clientHeight < 100
if (userJustSentMessageRef.current || isNearBottom) {
container.scrollTop = container.scrollHeight
if (!userScrolledUpRef.current) {
scrollToBottom()
}
}, [messages, preferences?.autoScroll, containerRef, scrollToBottom])
if (
lastMessage?.info.role === 'assistant' &&
'completed' in lastMessage.info.time &&
lastMessage.info.time.completed
) {
userJustSentMessageRef.current = false
useEffect(() => {
return () => {
if (scrollRAFRef.current) {
cancelAnimationFrame(scrollRAFRef.current)
}
}
}, [messages, preferences?.autoScroll, containerRef])
}, [])
if (isLoading) {
return (
@@ -98,7 +141,7 @@ export const MessageThread = memo(function MessageThread({ opcodeUrl, sessionID,
}
return (
<div className="flex flex-col space-y-2 p-4 overflow-x-hidden">
<div className="flex flex-col space-y-2 p-2 overflow-x-hidden">
{messages.map((msg) => {
const streaming = isMessageStreaming(msg)
const thinking = isMessageThinking(msg)
@@ -109,7 +152,7 @@ export const MessageThread = memo(function MessageThread({ opcodeUrl, sessionID,
className="flex flex-col"
>
<div
className={`w-full rounded-lg p-2 ${
className={`w-full rounded-lg p-1.5 ${
msg.info.role === 'user'
? 'bg-blue-600/20 border border-blue-600/30'
: 'bg-card/50 border border-border'
+53 -37
View File
@@ -5,6 +5,8 @@ import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
import { useFileSearch } from '@/hooks/useFileSearch'
import { useStandalone } from '@/hooks/useStandalone'
import { useUserBash } from '@/stores/userBashStore'
import { ChevronDown } from 'lucide-react'
import { CommandSuggestions } from '@/components/command/CommandSuggestions'
import { FileSuggestions } from './FileSuggestions'
@@ -26,6 +28,8 @@ interface PromptInputProps {
directory?: string
sessionID: string
disabled?: boolean
showScrollButton?: boolean
onScrollToBottom?: () => void
onShowSessionsDialog?: () => void
onShowModelsDialog?: () => void
onShowHelpDialog?: () => void
@@ -35,7 +39,9 @@ export function PromptInput({
opcodeUrl,
directory,
sessionID,
disabled,
disabled,
showScrollButton,
onScrollToBottom,
onShowSessionsDialog,
onShowModelsDialog,
onShowHelpDialog
@@ -79,12 +85,14 @@ export function PromptInput({
)
const isStandalone = useStandalone()
const { addUserBashCommand } = useUserBash()
const handleSubmit = () => {
if (!prompt.trim() || disabled) return
if (isBashMode) {
const command = prompt.startsWith('!') ? prompt.slice(1) : prompt
addUserBashCommand(command)
sendShell.mutate({
sessionID,
command,
@@ -418,7 +426,7 @@ export function PromptInput({
return (
<div className={`backdrop-blur-md bg-background/90 border border-border rounded-lg p-1 md:p-3 mx-2 md:mx-4 md:mb-4 max-w-4xl md:mx-auto pb-safe ${isStandalone ? 'mb-6' : 'mb-2'}`}>
<div className={`backdrop-blur-md bg-background opacity-95 border border-border rounded-lg p-2 md:p-3 mx-2 md:mx-4 md:mb-4 w-full max-w-4xl pb-safe ${isStandalone ? 'mb-6' : 'mb-2'}`}>
<textarea
@@ -428,43 +436,40 @@ export function PromptInput({
onKeyDown={handleKeyDown}
placeholder={
isBashMode
? "Enter bash command... (Esc to exit)"
: "Send a message... (Cmd/Ctrl+Enter)"
? "Enter bash command..."
: "Send a message..."
}
disabled={disabled || hasActiveStream}
className={`w-full bg-background px-3 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none resize-none min-h-[36px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm rounded-lg ${
className={`w-full bg-background/90 px-2 md:px-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:bg-black resize-none min-h-[40px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm rounded-lg ${
isBashMode
? 'border-purple-500/50 bg-purple-500/5'
? 'border-purple-500/50 bg-purple-500/5 focus:bg-black'
: ''
}`}
rows={1}
/>
<div className="flex gap-2 items-center justify-between">
<div className="flex gap-2 items-center">
<div className="flex gap-1.5 md:gap-2 items-center justify-between mb-1">
<div className="flex gap-1.5 md:gap-2 items-center">
<button
onClick={handleModeToggle}
className={`w-16 px-2 py-1 rounded-md text-xs font-medium border ${modeBg} ${modeColor} hover:opacity-80 transition-opacity cursor-pointer`}
className={`px-2 py-1 rounded-md text-xs font-medium border w-14 ${
isBashMode
? 'bg-purple-500/10 border-purple-500/30 text-purple-600 dark:text-purple-400'
: `${modeBg} ${modeColor}`
} hover:opacity-80 transition-opacity cursor-pointer`}
>
{currentMode.toUpperCase()}
{isBashMode ? 'BASH' : currentMode.toUpperCase()}
</button>
<button
onClick={onShowModelsDialog}
className="px-2 py-1 rounded-md text-xs font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 transition-colors cursor-pointer max-w-[120px] md:max-w-[180px] truncate"
>
{modelName.length > 12 ? modelName.substring(0, 10) + '...' : modelName || 'Select model'}
</button>
{isBashMode && (
<div className="px-2 py-1 rounded-md text-xs font-medium border bg-purple-500/10 border-purple-500/30 text-purple-600 dark:text-purple-400">
BASH MODE
</div>
)}
{modelName && (
<button
onClick={onShowModelsDialog}
className="px-2 py-1 rounded-md text-xs font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 transition-colors cursor-pointer"
>
{modelName.length > 20 ? `${modelName.slice(0, 20)}...` : modelName}
</button>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
className="w-6 h-6 rounded-full border-2 border-foreground text-foreground hover:bg-foreground hover:text-background transition-colors flex items-center justify-center text-sm font-medium"
className="w-6 h-6 rounded-full border-2 border-foreground text-foreground hover:bg-foreground hover:text-background transition-colors flex items-center justify-center text-sm font-medium flex-shrink-0"
title="Help"
>
?
@@ -486,19 +491,30 @@ export function PromptInput({
</DropdownMenuContent>
</DropdownMenu>
</div>
<button
data-submit-prompt
onClick={hasActiveStream ? handleStop : handleSubmit}
disabled={(!prompt.trim() && !hasActiveStream) || disabled}
className={`px-6 py-1.5 rounded-lg text-sm font-medium transition-colors ${
hasActiveStream
? 'bg-destructive hover:bg-destructive/90 text-destructive-foreground'
: 'bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground'
}`}
title={hasActiveStream ? 'Stop' : 'Send'}
>
{hasActiveStream ? 'Stop' : 'Send'}
</button>
<div className="flex items-center gap-1.5 md:gap-2 flex-shrink-0">
{showScrollButton && (
<button
onClick={onScrollToBottom}
className="p-1.5 md:p-2 rounded-lg bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground transition-colors"
title="Scroll to bottom"
>
<ChevronDown className="w-4 h-4" />
</button>
)}
<button
data-submit-prompt
onClick={hasActiveStream ? handleStop : handleSubmit}
disabled={(!prompt.trim() && !hasActiveStream) || disabled}
className={`px-5 md:px-6 py-1.5 rounded-lg text-sm font-medium transition-colors ${
hasActiveStream
? 'bg-destructive hover:bg-destructive/90 text-destructive-foreground'
: 'bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground'
}`}
title={hasActiveStream ? 'Stop' : 'Send'}
>
{hasActiveStream ? 'Stop' : 'Send'}
</button>
</div>
</div>
<CommandSuggestions
@@ -1,7 +1,33 @@
import { useState } from 'react'
import { useState, useRef, useEffect } from 'react'
import type { components } from '@/api/opencode-types'
import { useSettings } from '@/hooks/useSettings'
import { useUserBash } from '@/stores/userBashStore'
import { detectFileReferences } from '@/lib/fileReferences'
import { Copy } from 'lucide-react'
function CopyButton({ content, title, className = "" }: { content: string; title: string; className?: string }) {
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(content)
} catch (error) {
console.error('Failed to copy content:', error)
}
}
if (!content.trim()) {
return null
}
return (
<button
onClick={handleCopy}
className={`p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground ${className}`}
title={title}
>
<Copy className="w-4 h-4" />
</button>
)
}
type ToolPart = components['schemas']['ToolPart']
@@ -52,9 +78,21 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
export function ToolCallPart({ part, onFileClick }: ToolCallPartProps) {
const { preferences } = useSettings()
const defaultExpanded = preferences?.expandToolCalls ?? false
const { userBashCommands } = useUserBash()
const outputRef = useRef<HTMLDivElement>(null)
const isUserBashCommand = part.tool === 'bash' &&
part.state.status === 'completed' &&
typeof part.state.input?.command === 'string' &&
userBashCommands.has(part.state.input.command)
const defaultExpanded = isUserBashCommand || (preferences?.expandToolCalls ?? false)
const [expanded, setExpanded] = useState(defaultExpanded)
useEffect(() => {
if (part.tool === 'bash' && expanded && outputRef.current) {
outputRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
}, [expanded, part.tool])
const getStatusColor = () => {
switch (part.state.status) {
case 'completed':
@@ -110,6 +148,30 @@ export function ToolCallPart({ part, onFileClick }: ToolCallPartProps) {
const previewText = getPreviewText()
const isFileTool = ['read', 'write', 'edit'].includes(part.tool)
if (isUserBashCommand) {
const command = part.state.input.command as string
const output = part.state.status === 'completed' ? part.state.output : ''
return (
<div ref={outputRef} className="my-2">
<div className="flex items-center gap-2 text-sm mb-2">
<span className="text-green-400">✓</span>
<span className="font-medium">$</span>
<span className="text-zinc-300">{command}</span>
{part.state.status === 'completed' && part.state.time && (
<span className="text-muted-foreground text-xs ml-auto">
{((part.state.time.end - part.state.time.start) / 1000).toFixed(2)}s
</span>
)}
</div>
<pre className="bg-accent p-3 rounded text-xs overflow-x-auto whitespace-pre-wrap cursor-pointer hover:bg-accent/80 transition-colors"
onClick={() => navigator.clipboard.writeText(output)}
title="Click to copy output">
{output}
</pre>
</div>
)
}
return (
<div className="border border-border rounded-lg overflow-hidden my-2">
<button
@@ -138,7 +200,7 @@ export function ToolCallPart({ part, onFileClick }: ToolCallPartProps) {
</button>
{expanded && (
<div className="bg-card p-4 space-y-2">
<div className="bg-card space-y-2">
{part.state.status === 'running' && (
<div className="text-sm">
<div className="text-zinc-400 mb-1">Input:</div>
@@ -148,14 +210,31 @@ export function ToolCallPart({ part, onFileClick }: ToolCallPartProps) {
{part.state.status === 'completed' && (
<>
<div className="text-sm">
<div className="text-zinc-400 mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
</div>
<div className="text-sm">
{part.tool === 'bash' ? (
<div className="text-sm">
<div className="flex items-center gap-2 mb-1">
<div className="text-zinc-400">Command:</div>
<CopyButton
content={typeof part.state.input?.command === 'string' ? part.state.input.command : ''}
title="Copy command"
/>
</div>
<div className="bg-accent p-2 rounded text-xs overflow-x-auto">
<span className="text-green-400">$</span> {typeof part.state.input?.command === 'string' ? part.state.input.command : ''}
</div>
</div>
) : (
<div className="text-sm">
<div className="text-zinc-400 mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
</div>
)}
<div className="text-sm" ref={outputRef}>
<div className="text-zinc-400 mb-1">Output:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap">
{part.state.output}
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap cursor-pointer hover:bg-accent/80 transition-colors"
onClick={() => part.state.status === 'completed' && navigator.clipboard.writeText(part.state.output)}
title="Click to copy output">
{part.state.status === 'completed' ? part.state.output : ''}
</pre>
</div>
{part.state.time && (