From 4cac704207695ace492f8f21e7b12cef20194e54 Mon Sep 17 00:00:00 2001 From: Chris Scott Date: Thu, 27 Nov 2025 14:19:33 -0500 Subject: [PATCH] Optimize file browser performance with memoization and improve virtualized text rendering --- .../components/file-browser/FileBrowser.tsx | 20 +- .../file-browser/FileBrowserSheet.tsx | 39 +- .../file-browser/FileOperations.tsx | 6 +- .../src/components/file-browser/FileTree.tsx | 6 +- .../file-browser/MobileFilePreviewModal.tsx | 59 ++- .../src/components/message/MessageThread.tsx | 55 ++- .../components/ui/virtualized-text-view.tsx | 454 ++++++++++++++---- frontend/src/lib/utils.ts | 9 + frontend/src/pages/SessionDetail.tsx | 97 +--- 9 files changed, 543 insertions(+), 202 deletions(-) diff --git a/frontend/src/components/file-browser/FileBrowser.tsx b/frontend/src/components/file-browser/FileBrowser.tsx index 30f3176d..92c1a532 100644 --- a/frontend/src/components/file-browser/FileBrowser.tsx +++ b/frontend/src/components/file-browser/FileBrowser.tsx @@ -104,10 +104,10 @@ useEffect(() => { } }, [onFileSelect, isMobile]) - const handleCloseModal = () => { + const handleCloseModal = useCallback(() => { setIsPreviewModalOpen(false) setSelectedFile(null) - } + }, []) const handleDirectoryClick = (path: string) => { loadFiles(path) @@ -117,7 +117,7 @@ useEffect(() => { loadFiles(currentPath) } - const handleUpload = async (files: FileList) => { + const handleUpload = useCallback(async (files: FileList) => { const formData = new FormData() formData.append('file', files[0]) @@ -135,9 +135,9 @@ useEffect(() => { } catch (err) { setError(err instanceof Error ? err.message : 'Upload failed') } - } + }, [currentPath]) - const handleCreateFile = async (name: string, type: 'file' | 'folder') => { + const handleCreateFile = useCallback(async (name: string, type: 'file' | 'folder') => { try { const response = await fetch(`${API_BASE_URL}/api/files/${currentPath}/${name}`, { method: 'PUT', @@ -153,9 +153,9 @@ useEffect(() => { } catch (err) { setError(err instanceof Error ? err.message : 'Create failed') } - } + }, [currentPath]) - const handleDelete = async (path: string) => { + const handleDelete = useCallback(async (path: string) => { try { const response = await fetch(`${API_BASE_URL}/api/files/${path}`, { method: 'DELETE', @@ -170,9 +170,9 @@ useEffect(() => { } catch (err) { setError(err instanceof Error ? err.message : 'Delete failed') } - } + }, [currentPath]) - const handleRename = async (oldPath: string, newPath: string) => { + const handleRename = useCallback(async (oldPath: string, newPath: string) => { try { const response = await fetch(`${API_BASE_URL}/api/files/${oldPath}`, { method: 'PATCH', @@ -188,7 +188,7 @@ useEffect(() => { } catch (err) { setError(err instanceof Error ? err.message : 'Rename failed') } - } + }, [currentPath]) const handleDragEnter = (e: React.DragEvent) => { e.preventDefault() diff --git a/frontend/src/components/file-browser/FileBrowserSheet.tsx b/frontend/src/components/file-browser/FileBrowserSheet.tsx index bd81fedb..c3a97a96 100644 --- a/frontend/src/components/file-browser/FileBrowserSheet.tsx +++ b/frontend/src/components/file-browser/FileBrowserSheet.tsx @@ -1,8 +1,9 @@ -import { useEffect, useState } from 'react' +import { useEffect, useState, memo, useCallback } from 'react' import { FileBrowser } from './FileBrowser' import { Button } from '@/components/ui/button' import { PathDisplay } from '@/components/ui/path-display' import { X } from 'lucide-react' +import { GPU_ACCELERATED_STYLE, MODAL_TRANSITION_MS } from '@/lib/utils' interface FileBrowserSheetProps { isOpen: boolean @@ -12,11 +13,21 @@ interface FileBrowserSheetProps { initialSelectedFile?: string } -export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, initialSelectedFile }: FileBrowserSheetProps) { +export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, initialSelectedFile }: FileBrowserSheetProps) { const normalizedBasePath = basePath || '.' const [isEditing, setIsEditing] = useState(false) const [displayPath, setDisplayPath] = useState('/') - const handleDirectoryLoad = (info: { workspaceRoot?: string; currentPath: string }) => { + const [shouldRender, setShouldRender] = useState(false) + + useEffect(() => { + if (isOpen) { + setShouldRender(true) + } else { + const timer = setTimeout(() => setShouldRender(false), MODAL_TRANSITION_MS) + return () => clearTimeout(timer) + } + }, [isOpen]) + const handleDirectoryLoad = useCallback((info: { workspaceRoot?: string; currentPath: string }) => { if (!info.currentPath || info.currentPath === '.' || info.currentPath === '') { setDisplayPath('/') return @@ -35,7 +46,7 @@ export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, ini } else { setDisplayPath('/' + pathParts.join('/')) } - } + }, [repoName]) useEffect(() => { const handleEscape = (e: KeyboardEvent) => { @@ -61,12 +72,21 @@ export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, ini } }, [isOpen, onClose]) - if (!isOpen) return null + if (!isOpen && !shouldRender) return null return ( -
-
- {/* Header */} +
+
@@ -90,7 +110,6 @@ export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, ini
- {/* File Browser Content */}
) -} +}) diff --git a/frontend/src/components/file-browser/FileOperations.tsx b/frontend/src/components/file-browser/FileOperations.tsx index 7a45b0a2..1b5028dc 100644 --- a/frontend/src/components/file-browser/FileOperations.tsx +++ b/frontend/src/components/file-browser/FileOperations.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react' +import { useState, memo } from 'react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog' @@ -10,7 +10,7 @@ interface FileOperationsProps { onCreate: (name: string, type: 'file' | 'folder') => void } -export function FileOperations({ onUpload, onCreate }: FileOperationsProps) { +export const FileOperations = memo(function FileOperations({ onUpload, onCreate }: FileOperationsProps) { const [createDialogOpen, setCreateDialogOpen] = useState(false) const [createType, setCreateType] = useState<'file' | 'folder'>('file') const [createName, setCreateName] = useState('') @@ -103,4 +103,4 @@ export function FileOperations({ onUpload, onCreate }: FileOperationsProps) {
) -} \ No newline at end of file +}) \ No newline at end of file diff --git a/frontend/src/components/file-browser/FileTree.tsx b/frontend/src/components/file-browser/FileTree.tsx index d0a79e8f..2c98daa5 100644 --- a/frontend/src/components/file-browser/FileTree.tsx +++ b/frontend/src/components/file-browser/FileTree.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react' +import { useState, memo } from 'react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { DeleteDialog } from '@/components/ui/delete-dialog' @@ -215,7 +215,7 @@ function TreeNode({ file, level, onFileSelect, onDirectoryClick, selectedFile, o ) } -export function FileTree({ files, onFileSelect, onDirectoryClick, selectedFile, onDelete, onRename, currentPath = '', basePath = '' }: FileTreeProps) { +export const FileTree = memo(function FileTree({ files, onFileSelect, onDirectoryClick, selectedFile, onDelete, onRename, currentPath = '', basePath = '' }: FileTreeProps) { const handleGoUp = () => { // If currentPath has content and is different from basePath, go up if (currentPath !== basePath) { @@ -262,4 +262,4 @@ export function FileTree({ files, onFileSelect, onDirectoryClick, selectedFile, )}
) -} \ No newline at end of file +}) \ No newline at end of file diff --git a/frontend/src/components/file-browser/MobileFilePreviewModal.tsx b/frontend/src/components/file-browser/MobileFilePreviewModal.tsx index f13cdac3..d0f58f19 100644 --- a/frontend/src/components/file-browser/MobileFilePreviewModal.tsx +++ b/frontend/src/components/file-browser/MobileFilePreviewModal.tsx @@ -1,6 +1,7 @@ -import { Dialog, DialogContent } from "@/components/ui/dialog"; +import { memo, useCallback, useState, useEffect, useRef } from "react"; import { FilePreview } from "./FilePreview"; import type { FileInfo } from "@/types/files"; +import { GPU_ACCELERATED_STYLE, MODAL_TRANSITION_MS } from "@/lib/utils"; interface MobileFilePreviewModalProps { isOpen: boolean; @@ -9,33 +10,51 @@ interface MobileFilePreviewModalProps { showFilePreviewHeader?: boolean; } -export function MobileFilePreviewModal({ +export const MobileFilePreviewModal = memo(function MobileFilePreviewModal({ isOpen, onClose, file, showFilePreviewHeader = false, }: MobileFilePreviewModalProps) { - if (!file || file.isDirectory) { + const [localFile, setLocalFile] = useState(null); + const isClosingRef = useRef(false); + + useEffect(() => { + if (isOpen && file && !file.isDirectory) { + setLocalFile(file); + isClosingRef.current = false; + } + }, [isOpen, file]); + + const handleClose = useCallback(() => { + if (isClosingRef.current) return; + isClosingRef.current = true; + onClose(); + setTimeout(() => { + setLocalFile(null); + isClosingRef.current = false; + }, MODAL_TRANSITION_MS); + }, [onClose]); + + if (!isOpen || !localFile) { return null; } return ( - !open && onClose()}> - +
-
- -
- -
+ +
+
); -} +}) diff --git a/frontend/src/components/message/MessageThread.tsx b/frontend/src/components/message/MessageThread.tsx index 96a34ed7..bd15186d 100644 --- a/frontend/src/components/message/MessageThread.tsx +++ b/frontend/src/components/message/MessageThread.tsx @@ -1,4 +1,6 @@ +import { memo, useRef, useEffect } from 'react' import { useMessages } from '@/hooks/useOpenCode' +import { useSettings } from '@/hooks/useSettings' import { MessagePart } from './MessagePart' import type { MessageWithParts } from '@/api/types' @@ -7,6 +9,7 @@ interface MessageThreadProps { sessionID: string directory?: string onFileClick?: (filePath: string, lineNumber?: number) => void + containerRef?: React.RefObject } const isMessageStreaming = (msg: MessageWithParts): boolean => { @@ -19,8 +22,56 @@ const isMessageThinking = (msg: MessageWithParts): boolean => { return msg.parts.length === 0 && isMessageStreaming(msg) } -export function MessageThread({ opcodeUrl, sessionID, directory, onFileClick }: MessageThreadProps) { +export const MessageThread = memo(function MessageThread({ opcodeUrl, sessionID, directory, onFileClick, containerRef }: MessageThreadProps) { const { data: messages, isLoading, error } = useMessages(opcodeUrl, sessionID, directory) + const { preferences } = useSettings() + const lastMessageCountRef = useRef(0) + const userJustSentMessageRef = useRef(false) + const hasInitialScrolledRef = useRef(false) + + 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 + lastMessageCountRef.current = currentMessageCount + return + } + + const messageAdded = currentMessageCount > previousMessageCount + lastMessageCountRef.current = currentMessageCount + + const lastMessage = messages[messages.length - 1] + const isUserMessage = lastMessage?.info.role === 'user' + + if (messageAdded && isUserMessage) { + userJustSentMessageRef.current = true + container.scrollTop = container.scrollHeight + return + } + + if (!preferences?.autoScroll) return + + const isNearBottom = + container.scrollHeight - container.scrollTop - container.clientHeight < 100 + + if (userJustSentMessageRef.current || isNearBottom) { + container.scrollTop = container.scrollHeight + } + + if ( + lastMessage?.info.role === 'assistant' && + 'completed' in lastMessage.info.time && + lastMessage.info.time.completed + ) { + userJustSentMessageRef.current = false + } + }, [messages, preferences?.autoScroll, containerRef]) if (isLoading) { return ( @@ -106,4 +157,4 @@ export function MessageThread({ opcodeUrl, sessionID, directory, onFileClick }: })}
) -} +}) diff --git a/frontend/src/components/ui/virtualized-text-view.tsx b/frontend/src/components/ui/virtualized-text-view.tsx index 10a849a3..fac1f9e7 100644 --- a/frontend/src/components/ui/virtualized-text-view.tsx +++ b/frontend/src/components/ui/virtualized-text-view.tsx @@ -1,5 +1,7 @@ -import { useRef, useCallback, useEffect, useState, useMemo, forwardRef, useImperativeHandle } from 'react' +import { useRef, useCallback, useEffect, useState, useMemo, forwardRef, useImperativeHandle, memo } from 'react' import { useVirtualizedContent } from '@/hooks/useVirtualizedContent' +import { useMobile } from '@/hooks/useMobile' +import { GPU_ACCELERATED_STYLE } from '@/lib/utils' interface VirtualizedTextViewProps { filePath: string @@ -18,7 +20,113 @@ export interface VirtualizedTextViewHandle { } const LINE_HEIGHT = 20 -const GUTTER_WIDTH = 40 +const GUTTER_WIDTH = 48 +const CHAR_WIDTH_ESTIMATE = 8.5 +const CONTENT_PADDING = 24 + +let measureCanvas: HTMLCanvasElement | null = null +let measureContext: CanvasRenderingContext2D | null = null + +function getTextWidth(text: string): number { + if (!measureCanvas) { + measureCanvas = document.createElement('canvas') + measureContext = measureCanvas.getContext('2d') + if (measureContext) { + measureContext.font = '14px ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace' + } + } + if (measureContext) { + return measureContext.measureText(text).width + } + return text.length * CHAR_WIDTH_ESTIMATE +} + +function calculateWrappedLineCount( + content: string, + containerWidth: number +): number { + if (!content || containerWidth <= GUTTER_WIDTH + CONTENT_PADDING) return 1 + const availableWidth = containerWidth - GUTTER_WIDTH - CONTENT_PADDING + const textWidth = getTextWidth(content) + return Math.max(1, Math.ceil(textWidth / availableWidth)) +} + +interface VirtualizedLineProps { + lineNum: number + content: string + isEdited: boolean + height: number + top: number + isHighlighted: boolean + lineHeight: number + editable: boolean + lineWrap: boolean + isLoaded: boolean + onLineChange: (lineNum: number, value: string) => void +} + +const VirtualizedLine = memo(function VirtualizedLine({ + lineNum, + content, + isEdited, + height, + top, + isHighlighted, + lineHeight, + editable, + lineWrap, + isLoaded, + onLineChange, +}: VirtualizedLineProps) { + return ( +
+
+ {lineNum + 1} +
+ + {!isLoaded ? ( +
+
+
+ ) : editable ? ( + onLineChange(lineNum, e.target.value)} + className={`flex-1 bg-transparent outline-none pl-2 ${ + isEdited ? 'bg-yellow-500/10' : '' + } ${ + lineWrap ? 'whitespace-pre-wrap break-all' : 'whitespace-pre' + }`} + style={{ lineHeight: `${lineHeight}px` }} + /> + ) : ( +
+ {content} +
+ )} +
+ ) +}) export const VirtualizedTextView = forwardRef(function VirtualizedTextView({ filePath, @@ -32,9 +140,27 @@ export const VirtualizedTextView = forwardRef(null) - const [scrollTop, setScrollTop] = useState(0) + const scrollTopRef = useRef(0) + const [renderTrigger, setRenderTrigger] = useState(0) const [viewportHeight, setViewportHeight] = useState(600) + const [containerWidth, setContainerWidth] = useState(0) const [highlightedLine, setHighlightedLine] = useState(initialLineNumber) + const loadedBufferRef = useRef<{ start: number; end: number }>({ start: 0, end: 0 }) + const heightCacheRef = useRef>(new Map()) + const lineOffsetsRef = useRef<{ offsets: Map; totalHeight: number } | null>(null) + const lastContainerWidthRef = useRef(0) + const lastTotalLinesRef = useRef(0) + const lastVisibleRangeRef = useRef<{ start: number; end: number }>({ start: 0, end: 0 }) + const currentVisibleRangeRef = useRef<{ start: number; end: number }>({ start: 0, end: 200 }) + const scrollRafRef = useRef(null) + const isMobile = useMobile() + + void renderTrigger + + const chunkSize = isMobile && lineWrap ? 800 : 400 + const overscan = isMobile && lineWrap ? 200 : 100 + const bufferMultiplier = 4 + const preRenderMultiplier = 3 const { lines, @@ -48,11 +174,10 @@ export const VirtualizedTextView = forwardRef { - return getVisibleRange(scrollTop, viewportHeight, lineHeight) - }, [scrollTop, viewportHeight, lineHeight, getVisibleRange]) - useEffect(() => { - const { start, end } = visibleRange - loadRange(start, end) - prefetchAdjacent(start, end) - }, [visibleRange, loadRange, prefetchAdjacent]) + loadedBufferRef.current = { start: 0, end: 0 } + heightCacheRef.current.clear() + lineOffsetsRef.current = null + }, [filePath]) useEffect(() => { const container = containerRef.current @@ -78,29 +199,180 @@ export const VirtualizedTextView = forwardRef { for (const entry of entries) { setViewportHeight(entry.contentRect.height) + const newWidth = entry.contentRect.width + if (newWidth !== containerWidth) { + heightCacheRef.current.clear() + setContainerWidth(newWidth) + } } }) resizeObserver.observe(container) return () => resizeObserver.disconnect() - }, []) - - useEffect(() => { - if (initialLineNumber && containerRef.current) { - const scrollPosition = (initialLineNumber - 1) * lineHeight - setHighlightedLine(initialLineNumber) - setTimeout(() => { - containerRef.current?.scrollTo({ top: scrollPosition, behavior: 'smooth' }) - }, 100) - setTimeout(() => { - setHighlightedLine(undefined) - }, 3000) + }, [containerWidth]) + + const lineOffsets = useMemo(() => { + if (!lineWrap || containerWidth === 0) return null + + const widthChanged = lastContainerWidthRef.current !== containerWidth + const totalLinesChanged = lastTotalLinesRef.current !== totalLines + + if (widthChanged) { + heightCacheRef.current.clear() + lineOffsetsRef.current = null } - }, [initialLineNumber, lineHeight]) + + lastContainerWidthRef.current = containerWidth + lastTotalLinesRef.current = totalLines + + const offsets = new Map() + const cache = heightCacheRef.current + let cumulativeTop = 0 + let hasChanges = false + + for (let i = 0; i < totalLines; i++) { + const editedContent = editedLines.get(i) + const lineData = lines.get(i) + const content = editedContent ?? lineData?.content ?? '' + + let height: number + + if (cache.has(i)) { + height = cache.get(i)! + } else if (content) { + const wrappedCount = calculateWrappedLineCount(content, containerWidth) + height = wrappedCount * lineHeight + cache.set(i, height) + hasChanges = true + } else { + height = lineHeight + } + + offsets.set(i, { height, top: cumulativeTop }) + cumulativeTop += height + } + + if (!hasChanges && !totalLinesChanged && lineOffsetsRef.current) { + return lineOffsetsRef.current + } + + const result = { offsets, totalHeight: cumulativeTop } + lineOffsetsRef.current = result + return result + }, [lineWrap, containerWidth, totalLines, lines, editedLines, lineHeight]) + + const totalHeight = lineOffsets?.totalHeight ?? totalLines * lineHeight + + const lineOffsetsForCalcRef = useRef(lineOffsets) + lineOffsetsForCalcRef.current = lineOffsets + + const calculateVisibleRange = useCallback((scrollTop: number) => { + const currentLineOffsets = lineOffsetsForCalcRef.current + if (currentLineOffsets) { + const searchTop = scrollTop - overscan * lineHeight + const searchBottom = scrollTop + viewportHeight + overscan * lineHeight + + let low = 0 + let high = totalLines - 1 + let startLine = 0 + + while (low <= high) { + const mid = Math.floor((low + high) / 2) + const offset = currentLineOffsets.offsets.get(mid) + if (!offset) break + + if (offset.top + offset.height < searchTop) { + low = mid + 1 + } else { + startLine = mid + high = mid - 1 + } + } + + low = startLine + high = totalLines - 1 + let endLine = totalLines + + while (low <= high) { + const mid = Math.floor((low + high) / 2) + const offset = currentLineOffsets.offsets.get(mid) + if (!offset) break + + if (offset.top <= searchBottom) { + low = mid + 1 + } else { + endLine = mid + high = mid - 1 + } + } + + return { start: Math.max(0, startLine), end: Math.min(totalLines, endLine) } + } + + return getVisibleRange(scrollTop, viewportHeight, lineHeight) + }, [viewportHeight, lineHeight, getVisibleRange, totalLines, overscan]) + + const visibleRange = useMemo(() => { + const range = calculateVisibleRange(scrollTopRef.current) + currentVisibleRangeRef.current = range + return range + }, [calculateVisibleRange, renderTrigger]) + + useEffect(() => { + const { start, end } = visibleRange + const buffer = loadedBufferRef.current + const visibleCount = end - start + const desiredBuffer = visibleCount * bufferMultiplier + + const needsLoadBefore = start < buffer.start + visibleCount + const needsLoadAfter = end > buffer.end - visibleCount + + if (needsLoadBefore || needsLoadAfter || buffer.start === 0 && buffer.end === 0) { + const newStart = Math.max(0, start - desiredBuffer) + const newEnd = Math.min(totalLines, end + desiredBuffer) + + loadedBufferRef.current = { start: newStart, end: newEnd } + loadRange(newStart, newEnd) + } + }, [visibleRange, loadRange, totalLines, bufferMultiplier]) + + const lastRenderTimeRef = useRef(0) + const pendingRenderRef = useRef(false) + const RENDER_THROTTLE_MS = 32 const handleScroll = useCallback((e: React.UIEvent) => { - setScrollTop(e.currentTarget.scrollTop) - }, []) + const newScrollTop = e.currentTarget.scrollTop + scrollTopRef.current = newScrollTop + + if (scrollRafRef.current) { + cancelAnimationFrame(scrollRafRef.current) + } + + scrollRafRef.current = requestAnimationFrame(() => { + const newRange = calculateVisibleRange(newScrollTop) + const currentRange = currentVisibleRangeRef.current + + const rangeChanged = newRange.start !== currentRange.start || newRange.end !== currentRange.end + if (!rangeChanged) return + + currentVisibleRangeRef.current = newRange + + const now = performance.now() + const timeSinceLastRender = now - lastRenderTimeRef.current + + if (timeSinceLastRender >= RENDER_THROTTLE_MS) { + lastRenderTimeRef.current = now + setRenderTrigger(t => t + 1) + } else if (!pendingRenderRef.current) { + pendingRenderRef.current = true + setTimeout(() => { + pendingRenderRef.current = false + lastRenderTimeRef.current = performance.now() + setRenderTrigger(t => t + 1) + }, RENDER_THROTTLE_MS - timeSinceLastRender) + } + }) + }, [calculateVisibleRange]) const handleLineChange = useCallback((lineNum: number, value: string) => { setLineContent(lineNum, value) @@ -128,24 +400,62 @@ export const VirtualizedTextView = forwardRef { + if (initialLineNumber && containerRef.current) { + const offsetData = lineOffsets?.offsets.get(initialLineNumber - 1) + const scrollPosition = offsetData?.top ?? (initialLineNumber - 1) * lineHeight + setHighlightedLine(initialLineNumber) + setTimeout(() => { + containerRef.current?.scrollTo({ top: scrollPosition, behavior: 'smooth' }) + }, 100) + setTimeout(() => { + setHighlightedLine(undefined) + }, 3000) + } + }, [initialLineNumber, lineHeight, lineOffsets]) const visibleLines = useMemo(() => { - const result: Array<{ lineNum: number; content: string; isEdited: boolean }> = [] + const result: Array<{ lineNum: number; content: string; isEdited: boolean; height: number; top: number; isLoaded: boolean }> = [] - for (let i = visibleRange.start; i < visibleRange.end; i++) { + const lastRange = lastVisibleRangeRef.current + const visibleCount = visibleRange.end - visibleRange.start + const maxExpansion = visibleCount * preRenderMultiplier + + const expandedStart = Math.max( + 0, + visibleRange.start - maxExpansion, + Math.min(visibleRange.start, lastRange.start) + ) + const expandedEnd = Math.min( + totalLines, + visibleRange.end + maxExpansion, + Math.max(visibleRange.end, lastRange.end) + ) + + lastVisibleRangeRef.current = visibleRange + + for (let i = expandedStart; i < expandedEnd; i++) { const editedContent = editedLines.get(i) const lineData = lines.get(i) + const isLoaded = lineData?.loaded === true || editedContent !== undefined + const content = editedContent ?? lineData?.content ?? '' + + const offsetData = lineOffsets?.offsets.get(i) + const height = offsetData?.height ?? lineHeight + const top = offsetData?.top ?? i * lineHeight result.push({ lineNum: i, - content: editedContent ?? lineData?.content ?? '', + content: isLoaded ? content : '', isEdited: editedContent !== undefined, + height, + top, + isLoaded, }) } return result - }, [visibleRange, lines, editedLines]) + }, [visibleRange, lines, editedLines, lineOffsets, lineHeight, totalLines, preRenderMultiplier]) if (error) { return ( @@ -158,61 +468,39 @@ export const VirtualizedTextView = forwardRef -
- {visibleLines.map(({ lineNum, content, isEdited }) => { - const isHighlighted = highlightedLine === lineNum + 1 - return ( -
+ {visibleLines.map(({ lineNum, content, isEdited, height, top, isLoaded }) => ( + -
- {lineNum + 1} -
- - {editable ? ( - handleLineChange(lineNum, e.target.value)} - className={`flex-1 bg-transparent outline-none pl-2 ${ - isEdited ? 'bg-yellow-500/10' : '' - } ${ - lineWrap ? 'whitespace-pre-wrap break-all' : 'whitespace-pre' - }`} - style={{ lineHeight: `${lineHeight}px` }} - /> - ) : ( -
- {content} -
- )} -
- )})} + lineNum={lineNum} + content={content} + isEdited={isEdited} + height={height} + top={top} + isHighlighted={highlightedLine === lineNum + 1} + lineHeight={lineHeight} + editable={editable} + lineWrap={lineWrap} + isLoaded={isLoaded} + onLineChange={handleLineChange} + /> + ))} - {isLoading && visibleLines.length === 0 && ( -
+ {visibleLines.length === 0 && ( +
+ {isLoading ? 'Loading...' : 'No content'} +
+ )} + + {isLoading && visibleLines.length > 0 && ( +
Loading...
)} diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index bd0c391d..0c8e9e97 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -1,6 +1,15 @@ import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" +import type { CSSProperties } from "react" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } + +export const GPU_ACCELERATED_STYLE: CSSProperties = { + transform: 'translateZ(0)', + backfaceVisibility: 'hidden', + WebkitBackfaceVisibility: 'hidden', +} + +export const MODAL_TRANSITION_MS = 300 diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index 5de0bca8..82fada5f 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -9,13 +9,13 @@ import { SessionDetailHeader } from "@/components/session/SessionDetailHeader"; import { SessionList } from "@/components/session/SessionList"; import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"; import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; -import { useSession, useMessages, useAbortSession, useUpdateSession } from "@/hooks/useOpenCode"; +import { useSession, useAbortSession, useUpdateSession } from "@/hooks/useOpenCode"; import { OPENCODE_API_ENDPOINT } from "@/config"; import { useSSE } from "@/hooks/useSSE"; import { useSettings } from "@/hooks/useSettings"; import { useKeyboardShortcuts } from "@/hooks/useKeyboardShortcuts"; import { useSettingsDialog } from "@/hooks/useSettingsDialog"; -import { useEffect, useRef } from "react"; +import { useEffect, useRef, useCallback } from "react"; import { Loader2 } from "lucide-react"; export function SessionDetail() { @@ -28,9 +28,6 @@ export function SessionDetail() { const [sessionsDialogOpen, setSessionsDialogOpen] = useState(false); const [fileBrowserOpen, setFileBrowserOpen] = useState(false); const [selectedFilePath, setSelectedFilePath] = useState(); - const lastMessageCountRef = useRef(0); - const userJustSentMessageRef = useRef(false); - const hasInitialScrolledRef = useRef(false); const { data: repo, isLoading: repoLoading } = useQuery({ queryKey: ["repo", repoId], @@ -49,7 +46,6 @@ export function SessionDetail() { sessionId, repoDirectory, ); - const { data: messages } = useMessages(opcodeUrl, sessionId, repoDirectory); const { isConnected } = useSSE(opcodeUrl, repoDirectory); const abortSession = useAbortSession(opcodeUrl, repoDirectory); const updateSession = useUpdateSession(opcodeUrl, repoDirectory); @@ -83,50 +79,33 @@ export function SessionDetail() { return () => document.removeEventListener("keydown", handleKeyDown); }, [preferences?.mode, updateSettings]); - useEffect(() => { - if (!messageContainerRef.current) return; + - const container = messageContainerRef.current; - const currentMessageCount = messages?.length || 0; - const previousMessageCount = lastMessageCountRef.current; - - if (!hasInitialScrolledRef.current && currentMessageCount > 0) { - hasInitialScrolledRef.current = true; - container.scrollTop = container.scrollHeight; - lastMessageCountRef.current = currentMessageCount; - return; + const handleFileClick = useCallback((filePath: string) => { + let pathToOpen = filePath + + if (filePath.startsWith('/') && repo?.fullPath) { + const workspaceReposPath = repo.fullPath.substring(0, repo.fullPath.lastIndexOf('/')) + + if (filePath.startsWith(workspaceReposPath + '/')) { + pathToOpen = filePath.substring(workspaceReposPath.length + 1) + } } + + setSelectedFilePath(pathToOpen) + setFileBrowserOpen(true) + }, [repo?.fullPath]); - const messageAdded = currentMessageCount > previousMessageCount; - lastMessageCountRef.current = currentMessageCount; - - const lastMessage = messages?.[messages.length - 1]; - const isUserMessage = lastMessage?.info.role === "user"; - - if (messageAdded && isUserMessage) { - userJustSentMessageRef.current = true; - container.scrollTop = container.scrollHeight; - return; + const handleSessionTitleUpdate = useCallback((newTitle: string) => { + if (sessionId) { + updateSession.mutate({ sessionID: sessionId, title: newTitle }); } + }, [sessionId, updateSession]); - if (!preferences?.autoScroll) return; - - const isNearBottom = - container.scrollHeight - container.scrollTop - container.clientHeight < - 100; - - if (userJustSentMessageRef.current || isNearBottom) { - container.scrollTop = container.scrollHeight; - } - - if ( - lastMessage?.info.role === "assistant" && - "completed" in lastMessage.info.time && - lastMessage.info.time.completed - ) { - userJustSentMessageRef.current = false; - } - }, [messages, preferences?.autoScroll]); + const handleFileBrowserClose = useCallback(() => { + setFileBrowserOpen(false) + setSelectedFilePath(undefined) + }, []); if (repoLoading || sessionLoading) { return ( @@ -151,28 +130,6 @@ export function SessionDetail() {
); } - - const handleFileClick = (filePath: string) => { - - let pathToOpen = filePath - - if (filePath.startsWith('/') && repo.fullPath) { - const workspaceReposPath = repo.fullPath.substring(0, repo.fullPath.lastIndexOf('/')) - - if (filePath.startsWith(workspaceReposPath + '/')) { - pathToOpen = filePath.substring(workspaceReposPath.length + 1) - } - } - - setSelectedFilePath(pathToOpen) - setFileBrowserOpen(true) - }; - - const handleSessionTitleUpdate = (newTitle: string) => { - if (sessionId) { - updateSession.mutate({ sessionID: sessionId, title: newTitle }); - } - }; return ( @@ -198,6 +155,7 @@ export function SessionDetail() { sessionID={sessionId} directory={repoDirectory} onFileClick={handleFileClick} + containerRef={messageContainerRef} /> )}
@@ -257,10 +215,7 @@ export function SessionDetail() { { - setFileBrowserOpen(false) - setSelectedFilePath(undefined) - }} + onClose={handleFileBrowserClose} basePath={repo.localPath} repoName={repo.repoUrl.split("/").pop()?.replace(".git", "") || "Repository"} initialSelectedFile={selectedFilePath}