mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix(files): resolve workspace paths and add sandboxed HTML preview (#367)
* fix(files): resolve workspace paths and add sandboxed HTML preview Accept workspace-absolute paths in the file service and return repo-relative paths for file reads and directory listings. Serve raw content under a CSP sandbox and preview HTML files in a sandboxed iframe with a raw toggle. Resolve file-click paths from the session directory and repo local path, detect absolute and html/htm file references while ignoring URLs, accept the legacy filePath input key and filediff metadata, fix the file browser navigating into an initially selected directory, and use focus-visible rings across shared UI primitives. * fix(files): address review feedback on navigation and path fallback Key initial directory navigation to the initial selection so viewport changes do not reset it, and open the mobile preview from a separate effect. Fall back to the legacy filePath input when path is empty, and cover both with regression tests.
This commit is contained in:
1 parent
5bd688de4b
commit
68b13c8e35
19 files changed
+307
-58
No files matched your search
@@ -120,6 +120,7 @@ export function createFileRoutes() {
|
||||
headers: {
|
||||
'Content-Type': result.mimeType || 'application/octet-stream',
|
||||
'Content-Length': result.size.toString(),
|
||||
'Content-Security-Policy': 'sandbox allow-scripts',
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -64,6 +64,7 @@ export async function getRawFileContent(userPath: string): Promise<Buffer> {
|
||||
|
||||
export async function getFile(userPath: string): Promise<FileInfo> {
|
||||
const validatedPath = validatePath(userPath)
|
||||
const responsePath = path.isAbsolute(userPath.trim()) ? path.relative(SHARED_WORKSPACE_BASE, validatedPath) : userPath
|
||||
logger.info(`Getting file for path: ${userPath} -> ${validatedPath}`)
|
||||
|
||||
try {
|
||||
@@ -84,7 +85,7 @@ export async function getFile(userPath: string): Promise<FileInfo> {
|
||||
for (const entry of entries) {
|
||||
children.push({
|
||||
name: entry.name,
|
||||
path: path.join(userPath, entry.name),
|
||||
path: path.join(responsePath, entry.name),
|
||||
isDirectory: entry.isDirectory,
|
||||
size: entry.size,
|
||||
lastModified: entry.lastModified,
|
||||
@@ -93,7 +94,7 @@ export async function getFile(userPath: string): Promise<FileInfo> {
|
||||
|
||||
return {
|
||||
name: path.basename(validatedPath),
|
||||
path: userPath,
|
||||
path: responsePath,
|
||||
isDirectory: true,
|
||||
size: 0,
|
||||
children: children.sort((a, b) => {
|
||||
@@ -127,7 +128,7 @@ export async function getFile(userPath: string): Promise<FileInfo> {
|
||||
|
||||
return {
|
||||
name: path.basename(validatedPath),
|
||||
path: userPath,
|
||||
path: responsePath,
|
||||
isDirectory: false,
|
||||
size: stats.size,
|
||||
mimeType,
|
||||
@@ -234,14 +235,21 @@ export async function renameOrMoveFile(userPath: string, body: { newPath: string
|
||||
}
|
||||
}
|
||||
|
||||
function isWithinBase(resolved: string, basePath: string): boolean {
|
||||
return resolved === basePath || resolved.startsWith(`${basePath}${path.sep}`)
|
||||
}
|
||||
|
||||
function validatePath(userPath: string): string {
|
||||
const trimmed = userPath.trim()
|
||||
const normalized = path.normalize(trimmed || '.')
|
||||
const fullPath = path.join(SHARED_WORKSPACE_BASE, normalized)
|
||||
const resolved = path.resolve(fullPath)
|
||||
|
||||
const basePath = path.resolve(WORKSPACE_BASE)
|
||||
if (resolved !== basePath && !resolved.startsWith(`${basePath}${path.sep}`)) {
|
||||
|
||||
if (path.isAbsolute(normalized) && isWithinBase(path.resolve(normalized), basePath)) {
|
||||
return path.resolve(normalized)
|
||||
}
|
||||
|
||||
const resolved = path.resolve(path.join(SHARED_WORKSPACE_BASE, normalized))
|
||||
if (!isWithinBase(resolved, basePath)) {
|
||||
throw { message: 'Path traversal detected', statusCode: 403 }
|
||||
}
|
||||
|
||||
|
||||
@@ -166,6 +166,17 @@ describe('File Routes', () => {
|
||||
expect(getFile).toHaveBeenCalledWith('test-repo/test.txt')
|
||||
})
|
||||
|
||||
it('should serve raw content inside a CSP sandbox', async () => {
|
||||
getFile.mockResolvedValue({ ...mockFileInfo, name: 'report.html', mimeType: 'text/html', size: 13 })
|
||||
vi.mocked(fileService.getRawFileContent).mockResolvedValue(Buffer.from('<h1>hi</h1>\n\n'))
|
||||
|
||||
const response = await app.request('/api/files?path=test-repo/report.html&raw=true')
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('Content-Type')).toBe('text/html')
|
||||
expect(response.headers.get('Content-Security-Policy')).toBe('sandbox allow-scripts')
|
||||
})
|
||||
|
||||
it('should return 404 when path does not exist', async () => {
|
||||
getFile.mockRejectedValue({ message: 'File or directory not found', statusCode: 404 })
|
||||
|
||||
|
||||
@@ -386,6 +386,30 @@ describe('files service', () => {
|
||||
})
|
||||
|
||||
describe('path traversal protection', () => {
|
||||
it('reads an absolute path that lies inside the workspace', async () => {
|
||||
const absolutePath = await writeLines(`${relativeRoot}/report.html`, '<h1>hi</h1>')
|
||||
|
||||
const buffer = await getRawFileContent(absolutePath)
|
||||
|
||||
expect(buffer.toString('utf8')).toBe('<h1>hi</h1>')
|
||||
})
|
||||
|
||||
it('returns repos-relative paths for directories requested by absolute path', async () => {
|
||||
await writeLines(`${relativeRoot}/sub/a.txt`, 'a')
|
||||
|
||||
const result = await getFile(path.join(reposPath, relativeRoot, 'sub'))
|
||||
|
||||
expect(result.path).toBe(`${relativeRoot}/sub`)
|
||||
expect(result.children?.map((child) => child.path)).toEqual([`${relativeRoot}/sub/a.txt`])
|
||||
})
|
||||
|
||||
it('treats an absolute path outside the workspace as repos-relative', async () => {
|
||||
await expect(getRawFileContent('/etc/passwd')).rejects.toEqual({
|
||||
message: 'File not found or cannot be read',
|
||||
statusCode: 404,
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects traversal in getFile', async () => {
|
||||
await expect(getFile('../../etc/passwd')).rejects.toEqual({
|
||||
message: 'Path traversal detected',
|
||||
|
||||
@@ -144,20 +144,11 @@ export const FileBrowser = forwardRef<FileBrowserHandle, FileBrowserProps>(funct
|
||||
|
||||
const dropZoneRef = useRef<HTMLDivElement>(null)
|
||||
const uploadCancelledRef = useRef(false)
|
||||
const loadRequestRef = useRef(0)
|
||||
const isMobile = useMobile()
|
||||
|
||||
const { data: initialFileData, error: initialFileError } = useFile(initialSelectedFile)
|
||||
|
||||
useEffect(() => {
|
||||
if (initialFileData) {
|
||||
setSelectedFile(initialFileData)
|
||||
if (isMobile) {
|
||||
setIsPreviewModalOpen(true)
|
||||
onPreviewStateChange?.(true)
|
||||
}
|
||||
}
|
||||
}, [initialFileData, isMobile, onPreviewStateChange])
|
||||
|
||||
useEffect(() => {
|
||||
if (initialFileError) {
|
||||
setError(initialFileError.message)
|
||||
@@ -165,6 +156,7 @@ useEffect(() => {
|
||||
}, [initialFileError])
|
||||
|
||||
const loadFiles = useCallback(async (path: string) => {
|
||||
const request = ++loadRequestRef.current
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
@@ -175,13 +167,15 @@ useEffect(() => {
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
if (request !== loadRequestRef.current) return
|
||||
setFiles(data)
|
||||
setCurrentPath(path)
|
||||
onDirectoryLoad?.({ workspaceRoot: data.workspaceRoot, currentPath: path })
|
||||
} catch (err) {
|
||||
if (request !== loadRequestRef.current) return
|
||||
setError(err instanceof Error ? err.message : 'Failed to load files')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
if (request === loadRequestRef.current) setLoading(false)
|
||||
}
|
||||
}, [onDirectoryLoad])
|
||||
|
||||
@@ -448,6 +442,23 @@ useEffect(() => {
|
||||
loadFiles(basePath)
|
||||
}, [basePath, loadFiles])
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialFileData) return
|
||||
setError(null)
|
||||
if (initialFileData.isDirectory) {
|
||||
setSelectedFile(null)
|
||||
void loadFiles(initialFileData.path)
|
||||
return
|
||||
}
|
||||
setSelectedFile(initialFileData)
|
||||
}, [initialFileData, loadFiles])
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialFileData || initialFileData.isDirectory || !isMobile) return
|
||||
setIsPreviewModalOpen(true)
|
||||
onPreviewStateChange?.(true)
|
||||
}, [initialFileData, isMobile, onPreviewStateChange])
|
||||
|
||||
useEffect(() => {
|
||||
const handleFileSaved = (event: CustomEvent<{ path: string; content?: string }>) => {
|
||||
if (selectedFile && selectedFile.path === event.detail.path) {
|
||||
|
||||
@@ -86,6 +86,88 @@ describe('FileBrowserSheet', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('FileBrowser initial selection', () => {
|
||||
it('navigates into an initially selected directory even when the base listing resolves later', async () => {
|
||||
const directory = (path: string, children: string[]) => ({
|
||||
name: path.split('/').pop(),
|
||||
path,
|
||||
isDirectory: true,
|
||||
size: 0,
|
||||
lastModified: new Date().toISOString(),
|
||||
children: children.map((name) => ({ name, path: `${path}/${name}`, isDirectory: true, size: 0, lastModified: new Date().toISOString() })),
|
||||
})
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const path = new URL(String(input), 'http://localhost').searchParams.get('path')
|
||||
if (path === 'repo') {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
return new Response(JSON.stringify(directory('repo', ['frontend'])), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
||||
}
|
||||
return new Response(JSON.stringify(directory('repo/frontend', ['src'])), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const ref = { current: null as unknown as FileBrowserHandle }
|
||||
|
||||
try {
|
||||
render(
|
||||
<FileBrowser ref={ref as never} basePath="repo" embedded={true} initialSelectedFile="repo/frontend" />,
|
||||
{ wrapper: createWrapper() }
|
||||
)
|
||||
|
||||
expect(await screen.findByText('src')).toBeInTheDocument()
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
expect(ref.current.getCurrentPath()).toBe('repo/frontend')
|
||||
expect(screen.queryByText('frontend')).not.toBeInTheDocument()
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not reload the initial directory when the viewport changes', async () => {
|
||||
const directory = (path: string, children: string[]) => ({
|
||||
name: path.split('/').pop(),
|
||||
path,
|
||||
isDirectory: true,
|
||||
size: 0,
|
||||
lastModified: new Date().toISOString(),
|
||||
children: children.map((name) => ({ name, path: `${path}/${name}`, isDirectory: true, size: 0, lastModified: new Date().toISOString() })),
|
||||
})
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const path = new URL(String(input), 'http://localhost').searchParams.get('path')
|
||||
if (path === 'repo') {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
return new Response(JSON.stringify(directory('repo', ['frontend'])), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
||||
}
|
||||
return new Response(JSON.stringify(directory('repo/frontend', ['src'])), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const mobileSpy = vi.spyOn(useMobile, 'useMobile').mockReturnValue(false)
|
||||
const ref = { current: null as unknown as FileBrowserHandle }
|
||||
|
||||
try {
|
||||
const { rerender } = render(
|
||||
<FileBrowser ref={ref as never} basePath="repo" embedded={true} initialSelectedFile="repo/frontend" />,
|
||||
{ wrapper: createWrapper() }
|
||||
)
|
||||
|
||||
expect(await screen.findByText('src')).toBeInTheDocument()
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
const callsBefore = fetchMock.mock.calls.length
|
||||
|
||||
mobileSpy.mockReturnValue(true)
|
||||
rerender(
|
||||
<FileBrowser ref={ref as never} basePath="repo" embedded={true} initialSelectedFile="repo/frontend" />
|
||||
)
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
expect(fetchMock.mock.calls.length).toBe(callsBefore)
|
||||
expect(ref.current.getCurrentPath()).toBe('repo/frontend')
|
||||
} finally {
|
||||
mobileSpy.mockRestore()
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('FileBrowser navigation', () => {
|
||||
it('exposes imperative handle with goBack, canGoBack, and getCurrentPath', () => {
|
||||
const ref = { current: null as unknown as FileBrowserHandle }
|
||||
|
||||
@@ -40,6 +40,21 @@ describe('FilePreview header buttons', () => {
|
||||
expect(active.className).not.toMatch(OUTLINE_DARK_OVERRIDE)
|
||||
})
|
||||
|
||||
it('renders HTML files in a sandboxed iframe with a raw toggle', () => {
|
||||
render(<FilePreview file={textFile('report.html', 'text/html')} />)
|
||||
|
||||
const frame = screen.getByTitle('report.html')
|
||||
expect(frame.tagName).toBe('IFRAME')
|
||||
expect(frame).toHaveAttribute('sandbox', 'allow-scripts')
|
||||
expect(frame.getAttribute('src')).toContain('raw=true')
|
||||
expect(screen.getByTitle('Open HTML in new tab')).toHaveAttribute('target', '_blank')
|
||||
|
||||
fireEvent.click(screen.getByTitle('Show raw HTML'))
|
||||
|
||||
expect(screen.queryByTitle('report.html')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('# heading')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the success and destructive tints on the edit actions in dark mode', () => {
|
||||
render(<FilePreview file={textFile('Dockerfile', 'text/plain')} />)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useCallback, useRef, useEffect, memo } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Download, X, Edit3, Save, X as XIcon, WrapText, Eye, Code } from 'lucide-react'
|
||||
import { Download, X, Edit3, Save, X as XIcon, WrapText, Eye, Code, ExternalLink } from 'lucide-react'
|
||||
import type { FileInfo } from '@/types/files'
|
||||
import { getFileApiUrl } from '@/api/files'
|
||||
import { saveFileFromUrl } from '@/lib/download'
|
||||
@@ -24,6 +24,9 @@ interface FilePreviewProps {
|
||||
|
||||
export const FilePreview = memo(function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal, onFileSaved, initialLineNumber }: FilePreviewProps) {
|
||||
const isMarkdownFile = file.name.toLowerCase().endsWith('.md') || file.name.toLowerCase().endsWith('.mdx') || file.mimeType === 'text/markdown'
|
||||
const isHtmlFile = /\.html?$/i.test(file.name) || file.mimeType === 'text/html'
|
||||
const hasRenderedPreview = isMarkdownFile || isHtmlFile
|
||||
const previewLabel = isHtmlFile ? 'HTML' : 'markdown'
|
||||
|
||||
const [viewMode, setViewMode] = useState<'preview' | 'edit'>('preview')
|
||||
const [editContent, setEditContent] = useState('')
|
||||
@@ -31,7 +34,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
const [hasVirtualizedChanges, setHasVirtualizedChanges] = useState(false)
|
||||
const [highlightedLine, setHighlightedLine] = useState<number | undefined>(initialLineNumber)
|
||||
const [lineWrap, setLineWrap] = useState(true)
|
||||
const [markdownPreview, setMarkdownPreview] = useState(isMarkdownFile)
|
||||
const [renderedPreview, setRenderedPreview] = useState(hasRenderedPreview)
|
||||
const [isLoadingAllContent, setIsLoadingAllContent] = useState(false)
|
||||
const [fullContentLoaded, setFullContentLoaded] = useState(false)
|
||||
const [fullContent, setFullContent] = useState<string | null>(null)
|
||||
@@ -41,16 +44,18 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
|
||||
const shouldVirtualize = file.size > VIRTUALIZATION_THRESHOLD_BYTES && !file.mimeType?.startsWith('image/')
|
||||
const isMarkdownTooLarge = file.size > MARKDOWN_PREVIEW_SIZE_LIMIT
|
||||
const showHtmlPreview = isHtmlFile && renderedPreview && viewMode !== 'edit'
|
||||
const rawFileUrl = getFileApiUrl(file.path, { params: { raw: true } })
|
||||
|
||||
useEffect(() => {
|
||||
setFullContentLoaded(false)
|
||||
setMarkdownPreview(isMarkdownFile)
|
||||
setRenderedPreview(hasRenderedPreview)
|
||||
setFullContent(null)
|
||||
setLocalMdContent(null)
|
||||
}, [file.path, isMarkdownFile])
|
||||
}, [file.path, hasRenderedPreview])
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldVirtualize && isMarkdownFile && markdownPreview && !isMarkdownTooLarge && !fullContentLoaded) {
|
||||
if (shouldVirtualize && isMarkdownFile && renderedPreview && !isMarkdownTooLarge && !fullContentLoaded) {
|
||||
const loadContent = async () => {
|
||||
if (!virtualizedRef.current) return
|
||||
setIsLoadingAllContent(true)
|
||||
@@ -66,7 +71,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
const timer = setTimeout(loadContent, 0)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [shouldVirtualize, isMarkdownFile, markdownPreview, isMarkdownTooLarge, fullContentLoaded])
|
||||
}, [shouldVirtualize, isMarkdownFile, renderedPreview, isMarkdownTooLarge, fullContentLoaded])
|
||||
|
||||
|
||||
|
||||
@@ -216,7 +221,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
return (
|
||||
<div className="flex justify-center p-4">
|
||||
<img
|
||||
src={getFileApiUrl(file.path, { params: { raw: true } })}
|
||||
src={rawFileUrl}
|
||||
alt={file.name}
|
||||
className="max-w-full h-auto object-contain rounded"
|
||||
/>
|
||||
@@ -224,8 +229,19 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
)
|
||||
}
|
||||
|
||||
if (showHtmlPreview) {
|
||||
return (
|
||||
<iframe
|
||||
src={rawFileUrl}
|
||||
title={file.name}
|
||||
sandbox="allow-scripts"
|
||||
className="w-full h-full border-0 bg-white"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (shouldVirtualize && isTextFile) {
|
||||
const showMarkdownPreview = isMarkdownFile && markdownPreview && viewMode !== 'edit'
|
||||
const showMarkdownPreview = isMarkdownFile && renderedPreview && viewMode !== 'edit'
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -248,7 +264,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
{isMarkdownTooLarge ? (
|
||||
<div className="flex flex-col items-center justify-center h-32 gap-2 text-muted-foreground">
|
||||
<span>File too large for markdown preview (max 1MB)</span>
|
||||
<Button variant="outline" size="sm" onClick={() => setMarkdownPreview(false)}>
|
||||
<Button variant="outline" size="sm" onClick={() => setRenderedPreview(false)}>
|
||||
View raw
|
||||
</Button>
|
||||
</div>
|
||||
@@ -295,7 +311,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
)
|
||||
}
|
||||
|
||||
if (isMarkdownFile && markdownPreview) {
|
||||
if (isMarkdownFile && renderedPreview) {
|
||||
return <MarkdownRenderer content={displayContent} onContentChange={handleLocalMarkdownContentChange} />
|
||||
}
|
||||
|
||||
@@ -379,19 +395,27 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 flex-shrink-0 mt-1">
|
||||
{isMarkdownFile && viewMode !== 'edit' && (
|
||||
{hasRenderedPreview && viewMode !== 'edit' && (
|
||||
<Button
|
||||
variant={markdownPreview ? 'default' : 'outline'}
|
||||
variant={renderedPreview ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={(e) => { e.stopPropagation(); e.preventDefault(); setMarkdownPreview(!markdownPreview) }}
|
||||
onClick={(e) => { e.stopPropagation(); e.preventDefault(); setRenderedPreview(!renderedPreview) }}
|
||||
className="h-7 w-7 p-0"
|
||||
title={markdownPreview ? "Show raw markdown" : "Preview rendered markdown"}
|
||||
title={renderedPreview ? `Show raw ${previewLabel}` : `Preview rendered ${previewLabel}`}
|
||||
>
|
||||
{markdownPreview ? <Code className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
|
||||
{renderedPreview ? <Code className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isHtmlFile && viewMode !== 'edit' && (
|
||||
<Button variant="outline" size="sm" asChild className="h-7 w-7 p-0">
|
||||
<a href={rawFileUrl} target="_blank" rel="noopener noreferrer" title="Open HTML in new tab" onClick={(e) => e.stopPropagation()}>
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isTextFile && !markdownPreview && (
|
||||
{isTextFile && !renderedPreview && (
|
||||
<Button
|
||||
variant={lineWrap ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
@@ -439,9 +463,9 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
|
||||
<div
|
||||
ref={contentRef}
|
||||
className={`flex-1 ${viewMode === 'edit' && !shouldVirtualize ? 'overflow-hidden' : shouldVirtualize ? '' : 'overflow-y-auto overscroll-contain'} min-h-0 overflow-x-hidden`}
|
||||
className={`flex-1 ${viewMode === 'edit' && !shouldVirtualize ? 'overflow-hidden' : shouldVirtualize || showHtmlPreview ? '' : 'overflow-y-auto overscroll-contain'} min-h-0 overflow-x-hidden`}
|
||||
>
|
||||
<div className={`${shouldVirtualize ? 'h-full' : 'p-2'} min-w-0`}>
|
||||
<div className={`${shouldVirtualize || showHtmlPreview ? 'h-full' : 'p-2'} min-w-0`}>
|
||||
{renderContent()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -134,16 +134,24 @@ function FileToolRender({ part, filediff, filePath, content, toolName, onFileCli
|
||||
|
||||
function fileDiffs(part: SessionMessageAssistantTool): FileDiffInfo[] {
|
||||
if (part.state.status !== 'completed') return []
|
||||
const files = part.state.metadata?.files
|
||||
if (!Array.isArray(files)) return []
|
||||
const metadata = part.state.metadata
|
||||
const files: unknown[] = Array.isArray(metadata?.files) ? metadata.files : [metadata?.filediff]
|
||||
return files.filter(isFileDiff)
|
||||
}
|
||||
|
||||
/** Returns the file path a file tool was called with, accepting both the `path` and legacy `filePath` input keys. */
|
||||
export function getToolInputPath(input: Record<string, unknown> | undefined): string | undefined {
|
||||
const path = input?.path
|
||||
if (typeof path === 'string' && path) return path
|
||||
const filePath = input?.filePath
|
||||
return typeof filePath === 'string' && filePath ? filePath : undefined
|
||||
}
|
||||
|
||||
export function getToolSpecificRender(part: SessionMessageAssistantTool, onFileClick?: (filePath: string) => void): React.ReactElement | null {
|
||||
if (part.state.status !== 'completed') return null
|
||||
|
||||
const input = part.state.input
|
||||
const inputPath = typeof input.path === 'string' ? input.path : undefined
|
||||
const inputPath = getToolInputPath(input)
|
||||
|
||||
if (part.name === 'edit' || part.name === 'patch') {
|
||||
const diffs = fileDiffs(part)
|
||||
|
||||
@@ -377,6 +377,54 @@ describe('MessagePart', () => {
|
||||
expect(screen.getByText('/test/file.txt')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('makes legacy filePath read, write, and filediff edit calls clickable', () => {
|
||||
const onFileClick = vi.fn()
|
||||
const legacy = (name: string, metadata: Record<string, unknown>) =>
|
||||
toolPart(name, {
|
||||
status: 'completed',
|
||||
input: { filePath: `/test/${name}.html` },
|
||||
content: [{ type: 'text', text: 'ok' }],
|
||||
metadata,
|
||||
})
|
||||
|
||||
renderWithProviders(
|
||||
<>
|
||||
<MessagePart part={legacy('read', {})} onFileClick={onFileClick} />
|
||||
<MessagePart part={legacy('write', {})} onFileClick={onFileClick} />
|
||||
<MessagePart
|
||||
part={legacy('edit', { filediff: { file: '/test/edit.html', patch: '@@ -1 +1 @@\n-a\n+b', additions: 1, deletions: 1 } })}
|
||||
onFileClick={onFileClick}
|
||||
/>
|
||||
</>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByText('/test/read.html'))
|
||||
fireEvent.click(screen.getByText('/test/write.html'))
|
||||
fireEvent.click(screen.getByText('/test/edit.html'))
|
||||
|
||||
expect(onFileClick.mock.calls.map(([filePath]) => filePath)).toEqual(['/test/read.html', '/test/write.html', '/test/edit.html'])
|
||||
expect(screen.getByText('+1')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('falls back to filePath when path is empty', () => {
|
||||
const onFileClick = vi.fn()
|
||||
renderWithProviders(
|
||||
<MessagePart
|
||||
part={toolPart('read', {
|
||||
status: 'completed',
|
||||
input: { path: '', filePath: '/test/fallback.html' },
|
||||
content: [{ type: 'text', text: 'ok' }],
|
||||
metadata: {},
|
||||
})}
|
||||
onFileClick={onFileClick}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByText('/test/fallback.html'))
|
||||
|
||||
expect(onFileClick).toHaveBeenCalledWith('/test/fallback.html')
|
||||
})
|
||||
|
||||
it('renders every file of a multi-file patch with per-file links', () => {
|
||||
const onFileClick = vi.fn()
|
||||
renderWithProviders(
|
||||
|
||||
@@ -9,7 +9,7 @@ import { detectFileReferences } from '@/lib/fileReferences'
|
||||
import { ExternalLink, Loader2, Shield } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { getToolSpecificRender } from './FileToolRender'
|
||||
import { getToolInputPath, getToolSpecificRender } from './FileToolRender'
|
||||
|
||||
const DISPLAY_LIMIT = 30_000
|
||||
const DISPLAY_HEAD_LENGTH = 20_000
|
||||
@@ -174,7 +174,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, onFile
|
||||
case 'write':
|
||||
case 'edit':
|
||||
case 'patch':
|
||||
return (input.path as string) || null
|
||||
return getToolInputPath(input) ?? null
|
||||
case 'shell':
|
||||
return displayCommand || null
|
||||
case 'glob':
|
||||
|
||||
@@ -285,7 +285,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
checked={skipSSHVerification}
|
||||
onChange={(e) => setSkipSSHVerification(e.target.checked)}
|
||||
disabled={mutation.isPending}
|
||||
className="mt-1 h-5 w-5 rounded border-border bg-muted text-primary focus:ring-primary"
|
||||
className="mt-1 h-5 w-5 rounded border-border bg-muted text-primary focus-visible:ring-primary"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<label htmlFor="skip-ssh-verification" className="cursor-pointer text-sm text-foreground">
|
||||
|
||||
@@ -4,7 +4,7 @@ import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
|
||||
@@ -125,7 +125,7 @@ const DialogContent = React.forwardRef<
|
||||
)}
|
||||
{!hideCloseButton && !fullscreen && (
|
||||
<DialogPrimitive.Close
|
||||
className="absolute right-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground"
|
||||
className="absolute right-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground"
|
||||
style={mobileFullscreen ? {
|
||||
top: 'calc(env(safe-area-inset-top, 0px) + 1rem)',
|
||||
} : { top: '1rem' }}
|
||||
|
||||
@@ -19,7 +19,7 @@ const SelectTrigger = React.forwardRef<
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-[16px] ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 md:text-sm",
|
||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-[16px] ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 md:text-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -120,7 +120,7 @@ export function SidebarItem({
|
||||
|
||||
const baseClasses = cn(
|
||||
'flex items-center gap-3 rounded-md transition-colors duration-150',
|
||||
'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background',
|
||||
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
|
||||
asPrimary ? 'p-3 text-sm font-medium' : 'p-2.5 text-sm',
|
||||
variant === 'primary' && 'bg-primary text-primary-foreground hover:bg-primary/90',
|
||||
variant === 'secondary' && 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { detectFileReferences } from './fileReferences'
|
||||
|
||||
describe('detectFileReferences', () => {
|
||||
it('keeps the leading slash of absolute paths and parses line numbers', () => {
|
||||
const [reference] = detectFileReferences('{"path": "/Users/me/workspace/repos/app/src/a.ts:12"}')
|
||||
|
||||
expect(reference.filePath).toBe('/Users/me/workspace/repos/app/src/a.ts')
|
||||
expect(reference.lineNumber).toBe(12)
|
||||
})
|
||||
|
||||
it('detects relative html and htm paths', () => {
|
||||
expect(detectFileReferences('{"path": "./out/report.html", "other": "docs/page.htm"}').map((ref) => ref.filePath))
|
||||
.toEqual(['./out/report.html', 'docs/page.htm'])
|
||||
})
|
||||
|
||||
it('ignores the path portion of URLs', () => {
|
||||
expect(detectFileReferences('fetch https://example.com/assets/app.js')).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -6,7 +6,7 @@ export interface FileReference {
|
||||
fullMatch: string
|
||||
}
|
||||
|
||||
const FILE_REFERENCE_PATTERN = /\b([\w\-./]+\.(ts|tsx|js|jsx|py|java|cpp|c|h|hpp|go|rs|rb|php|swift|kt|cs|vue|svelte|css|scss|sass|less|html|xml|json|yaml|yml|md|txt|sh|bash|sql|graphql|proto|toml|ini|conf|env))(?::(\d+))?\b/gi
|
||||
const FILE_REFERENCE_PATTERN = /(?<![\w\-./:])([\w\-./]+\.(ts|tsx|js|jsx|py|java|cpp|c|h|hpp|go|rs|rb|php|swift|kt|cs|vue|svelte|css|scss|sass|less|html|htm|xml|json|yaml|yml|md|txt|sh|bash|sql|graphql|proto|toml|ini|conf|env))(?::(\d+))?\b/gi
|
||||
|
||||
export function detectFileReferences(text: string): FileReference[] {
|
||||
const references: FileReference[] = []
|
||||
|
||||
@@ -400,19 +400,16 @@ export function SessionDetail() {
|
||||
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
const absolutePath = filePath.startsWith('/') || !sessionDirectory
|
||||
? filePath
|
||||
: `${sessionDirectory}/${filePath.replace(/^\.\//, '')}`
|
||||
const repoRoot = repo?.fullPath
|
||||
const pathToOpen = repoRoot && repo?.localPath && absolutePath.startsWith(`${repoRoot}/`)
|
||||
? `${repo.localPath}/${absolutePath.slice(repoRoot.length + 1)}`
|
||||
: absolutePath
|
||||
setSelectedFilePath(pathToOpen)
|
||||
setFileBrowserOpen(true)
|
||||
}, [repo?.fullPath, setFileBrowserOpen]);
|
||||
}, [repo?.fullPath, repo?.localPath, sessionDirectory, setFileBrowserOpen]);
|
||||
|
||||
const handleSessionTitleUpdate = useCallback((newTitle: string) => {
|
||||
if (sessionId) {
|
||||
|
||||
Reference in new issue
Block a user