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

@@ -44,7 +44,7 @@ export const FileOperations = memo(function FileOperations({ onUpload, onCreate
<Button variant="outline" size="sm" asChild>
<label htmlFor="file-upload" className="cursor-pointer flex items-center gap-2">
<Upload className="w-4 h-4" />
Upload
<span className='hidden sm:inline'>Upload</span>
</label>
</Button>
</div>
@@ -103,4 +103,4 @@ export const FileOperations = memo(function FileOperations({ onUpload, onCreate
</Dialog>
</div>
)
})
})
@@ -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 && (
@@ -22,6 +22,7 @@ interface SessionDetailHeaderProps {
sessionTitle: string;
repoId: number;
isConnected: boolean;
isReconnecting?: boolean;
opcodeUrl: string | null;
repoDirectory: string | undefined;
onFileBrowserOpen: () => void;
@@ -35,6 +36,7 @@ export function SessionDetailHeader({
sessionTitle,
repoId,
isConnected,
isReconnecting,
opcodeUrl,
repoDirectory,
onFileBrowserOpen,
@@ -139,10 +141,16 @@ export function SessionDetailHeader({
</div>
<div className="flex items-center gap-1 sm:gap-2">
<div
className={`w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full ${isConnected ? "bg-green-500" : "bg-red-500"}`}
className={`w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full ${
isConnected
? "bg-green-500"
: isReconnecting
? "bg-yellow-500 animate-pulse"
: "bg-red-500"
}`}
/>
<span className="text-xs text-muted-foreground hidden sm:inline">
{isConnected ? "Connected" : "Disconnected"}
{isConnected ? "Connected" : isReconnecting ? "Reconnecting..." : "Disconnected"}
</span>
</div>
<Button
+97 -57
View File
@@ -1,19 +1,49 @@
import { useEffect, useRef, useState } from 'react'
import { useEffect, useRef, useState, useCallback } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useOpenCodeClient } from './useOpenCode'
import type { SSEEvent, MessageListResponse } from '@/api/types'
import { permissionEvents } from './usePermissionRequests'
const MAX_RECONNECT_DELAY = 30000
const INITIAL_RECONNECT_DELAY = 1000
export const useSSE = (opcodeUrl: string | null | undefined, directory?: string) => {
const client = useOpenCodeClient(opcodeUrl, directory)
const queryClient = useQueryClient()
const eventSourceRef = useRef<EventSource | null>(null)
const urlRef = useRef<string | null>(null)
const reconnectTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const reconnectDelayRef = useRef(INITIAL_RECONNECT_DELAY)
const mountedRef = useRef(true)
const [isConnected, setIsConnected] = useState(false)
const [error, setError] = useState<string | null>(null)
const [isReconnecting, setIsReconnecting] = useState(false)
const scheduleReconnect = useCallback((connectFn: () => void) => {
if (!mountedRef.current) return
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current)
}
const delay = reconnectDelayRef.current
setIsReconnecting(true)
reconnectTimeoutRef.current = setTimeout(() => {
if (!mountedRef.current) return
reconnectDelayRef.current = Math.min(delay * 2, MAX_RECONNECT_DELAY)
connectFn()
}, delay)
}, [])
const resetReconnectDelay = useCallback(() => {
reconnectDelayRef.current = INITIAL_RECONNECT_DELAY
setIsReconnecting(false)
}, [])
useEffect(() => {
mountedRef.current = true
if (!client) {
if (eventSourceRef.current) {
eventSourceRef.current.close()
@@ -35,59 +65,6 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string)
}
urlRef.current = eventSourceUrl
const connectSSE = () => {
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current)
reconnectTimeoutRef.current = null
}
if (eventSourceRef.current) {
eventSourceRef.current.close()
eventSourceRef.current = null
}
try {
const eventSource = new EventSource(eventSourceUrl)
eventSourceRef.current = eventSource
eventSource.onopen = () => {
setIsConnected(true)
setError(null)
queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, directory] })
queryClient.invalidateQueries({ queryKey: ['opencode', 'messages', opcodeUrl] })
}
eventSource.onerror = (e) => {
console.error('[SSE] Connection error:', e)
setIsConnected(false)
setError('OpenCode server is not running. Please start the server first.')
if (eventSourceRef.current) {
eventSourceRef.current.close()
eventSourceRef.current = null
}
}
eventSource.onmessage = (event) => {
try {
const data: SSEEvent = JSON.parse(event.data)
handleSSEEvent(data)
} catch (err) {
console.error('Failed to parse SSE event:', err)
}
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to connect')
setIsConnected(false)
}
}
const handleReconnect = () => {
if (!eventSourceRef.current || eventSourceRef.current.readyState === EventSource.CLOSED) {
connectSSE()
}
}
const handleSSEEvent = (event: SSEEvent) => {
switch (event.type) {
@@ -147,7 +124,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string)
break
}
case 'message.updated':
case 'message.updated':
case 'messagev2.updated': {
if (!('info' in event.properties)) break
@@ -255,6 +232,68 @@ case 'message.updated':
break
}
}
const connectSSE = () => {
if (!mountedRef.current) return
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current)
reconnectTimeoutRef.current = null
}
if (eventSourceRef.current) {
eventSourceRef.current.close()
eventSourceRef.current = null
}
try {
const eventSource = new EventSource(eventSourceUrl)
eventSourceRef.current = eventSource
eventSource.onopen = () => {
if (!mountedRef.current) return
setIsConnected(true)
setError(null)
resetReconnectDelay()
queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, directory] })
queryClient.invalidateQueries({ queryKey: ['opencode', 'messages', opcodeUrl] })
}
eventSource.onerror = () => {
if (!mountedRef.current) return
setIsConnected(false)
setError('Connection lost. Reconnecting...')
if (eventSourceRef.current) {
eventSourceRef.current.close()
eventSourceRef.current = null
}
scheduleReconnect(connectSSE)
}
eventSource.onmessage = (event) => {
try {
const data: SSEEvent = JSON.parse(event.data)
handleSSEEvent(data)
} catch (err) {
console.error('Failed to parse SSE event:', err)
}
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to connect')
setIsConnected(false)
scheduleReconnect(connectSSE)
}
}
const handleReconnect = () => {
if (!eventSourceRef.current || eventSourceRef.current.readyState === EventSource.CLOSED) {
resetReconnectDelay()
connectSSE()
}
}
connectSSE()
@@ -262,6 +301,7 @@ case 'message.updated':
window.addEventListener('online', handleReconnect)
return () => {
mountedRef.current = false
window.removeEventListener('focus', handleReconnect)
window.removeEventListener('online', handleReconnect)
if (reconnectTimeoutRef.current) {
@@ -274,7 +314,7 @@ case 'message.updated':
setIsConnected(false)
}
}
}, [client, queryClient])
}, [client, queryClient, opcodeUrl, directory, scheduleReconnect, resetReconnectDelay])
return { isConnected, error }
return { isConnected, error, isReconnecting }
}
+16 -4
View File
@@ -31,6 +31,7 @@ export function SessionDetail() {
const [sessionsDialogOpen, setSessionsDialogOpen] = useState(false);
const [fileBrowserOpen, setFileBrowserOpen] = useState(false);
const [selectedFilePath, setSelectedFilePath] = useState<string | undefined>();
const [showScrollButton, setShowScrollButton] = useState(false);
const { data: repo, isLoading: repoLoading } = useQuery({
queryKey: ["repo", repoId],
@@ -50,7 +51,7 @@ const { currentPermission, pendingCount, dismissPermission } = usePermissionRequ
sessionId,
repoDirectory,
);
const { isConnected } = useSSE(opcodeUrl, repoDirectory);
const { isConnected, isReconnecting } = useSSE(opcodeUrl, repoDirectory);
const abortSession = useAbortSession(opcodeUrl, repoDirectory);
const updateSession = useUpdateSession(opcodeUrl, repoDirectory);
const { open: openSettings } = useSettingsDialog();
@@ -111,6 +112,13 @@ const { currentPermission, pendingCount, dismissPermission } = usePermissionRequ
setSelectedFilePath(undefined)
}, []);
const handleScrollToBottom = useCallback(() => {
if (messageContainerRef.current) {
messageContainerRef.current.scrollTop = messageContainerRef.current.scrollHeight;
setShowScrollButton(false);
}
}, []);
const handlePermissionResponse = useCallback(async (
permissionID: string,
permissionSessionID: string,
@@ -153,6 +161,7 @@ const { currentPermission, pendingCount, dismissPermission } = usePermissionRequ
sessionTitle={session.title || "Untitled Session"}
repoId={repoId}
isConnected={isConnected}
isReconnecting={isReconnecting}
opcodeUrl={opcodeUrl}
repoDirectory={repoDirectory}
onFileBrowserOpen={() => setFileBrowserOpen(true)}
@@ -160,8 +169,8 @@ const { currentPermission, pendingCount, dismissPermission } = usePermissionRequ
onSessionTitleUpdate={handleSessionTitleUpdate}
/>
<div className="flex-1 overflow-hidden flex flex-col">
<div ref={messageContainerRef} className="flex-1 overflow-y-auto overflow-x-hidden">
<div className="flex-1 overflow-hidden flex flex-col relative">
<div ref={messageContainerRef} className="flex-1 overflow-y-auto overflow-x-hidden pb-28">
{opcodeUrl && repoDirectory && (
<MessageThread
opcodeUrl={opcodeUrl}
@@ -169,16 +178,19 @@ const { currentPermission, pendingCount, dismissPermission } = usePermissionRequ
directory={repoDirectory}
onFileClick={handleFileClick}
containerRef={messageContainerRef}
onScrollStateChange={setShowScrollButton}
/>
)}
</div>
{opcodeUrl && repoDirectory && (
<div className="flex-shrink-0">
<div className="absolute bottom-0 left-0 right-0 flex justify-center">
<PromptInput
opcodeUrl={opcodeUrl}
directory={repoDirectory}
sessionID={sessionId}
disabled={!isConnected}
showScrollButton={showScrollButton}
onScrollToBottom={handleScrollToBottom}
onShowModelsDialog={() => setModelDialogOpen(true)}
onShowSessionsDialog={() => setSessionsDialogOpen(true)}
onShowHelpDialog={() => {
+17
View File
@@ -0,0 +1,17 @@
import { create } from 'zustand'
interface UserBashStore {
userBashCommands: Map<string, number> // command -> timestamp
addUserBashCommand: (command: string) => void
}
export const useUserBash = create<UserBashStore>((set) => ({
userBashCommands: new Map(),
addUserBashCommand: (command: string) => {
set((state) => {
const newMap = new Map(state.userBashCommands)
newMap.set(command, Date.now())
return { userBashCommands: newMap }
})
},
}))