fix(files): open relative markdown links and preinstall Chromium

Resolve relative and absolute markdown links against the previewed file
and open them in the file browser; external links open in a new tab.
Install Playwright and Chromium into the Manager image with NODE_PATH
and PLAYWRIGHT_BROWSERS_PATH so agents can run browser automation
without a project-local install.
This commit is contained in:
Chris Scott committed 2026-09-28 23:58:26 -04:00
1 parent 16f00c50d4
commit f1bd7ee940
11 files changed
+188 -21

No files matched your search

@@ -236,21 +236,23 @@ useEffect(() => {
getCurrentPath: () => currentPath,
}), [currentPath, goToParentDirectory, canNavigateUp])
const handleFileSelect = useCallback(async (file: FileInfo) => {
if (file.isDirectory) {
setSelectedFile(null)
return
}
// Fetch the full file content when selecting a file
const openFilePath = useCallback(async (path: string) => {
setLoading(true)
try {
const response = await fetch(getFileApiUrl(file.path))
const response = await fetch(getFileApiUrl(path))
if (!response.ok) {
throw new Error(`Failed to load file: ${response.statusText}`)
}
const fullFileData = await response.json()
const fullFileData: FileInfo = await response.json()
if (fullFileData.isDirectory) {
setSelectedFile(null)
setIsPreviewModalOpen(false)
onPreviewStateChange?.(false)
await loadFiles(fullFileData.path)
return
}
setSelectedFile(fullFileData)
onFileSelect?.(fullFileData)
@@ -265,7 +267,16 @@ useEffect(() => {
} finally {
setLoading(false)
}
}, [onFileSelect, isMobile, onPreviewStateChange])
}, [onFileSelect, isMobile, onPreviewStateChange, loadFiles])
const handleFileSelect = useCallback(async (file: FileInfo) => {
if (file.isDirectory) {
setSelectedFile(null)
return
}
await openFilePath(file.path)
}, [openFilePath])
const handleCloseModal = useCallback(() => {
setIsPreviewModalOpen(false)
@@ -639,7 +650,7 @@ useEffect(() => {
{!isMobile && (
<div className="flex-1 overflow-y-auto min-h-0 h-full">
{selectedFile && !selectedFile.isDirectory ? (
<FilePreview key={selectedFile.path} file={selectedFile} />
<FilePreview key={selectedFile.path} file={selectedFile} onOpenFile={openFilePath} />
) : (
<div className="flex items-center justify-center h-full text-muted-foreground">
Select a file to preview
@@ -655,6 +666,7 @@ useEffect(() => {
onClose={handleCloseModal}
file={selectedFile}
showFilePreviewHeader={true}
onOpenFile={openFilePath}
/>
</div>
)
@@ -740,7 +752,7 @@ useEffect(() => {
{!isMobile && (
<div className="flex-1 overflow-y-auto min-h-0 ">
{selectedFile && !selectedFile.isDirectory ? (
<FilePreview key={selectedFile.path} file={selectedFile} />
<FilePreview key={selectedFile.path} file={selectedFile} onOpenFile={openFilePath} />
) : (
<div className="flex items-center justify-center h-64 text-muted-foreground">
Select a file to preview
@@ -756,6 +768,7 @@ useEffect(() => {
isOpen={isMobile && isPreviewModalOpen}
onClose={handleCloseModal}
file={selectedFile}
onOpenFile={openFilePath}
/>
{uploadDialog}
@@ -89,6 +89,22 @@ describe('FilePreview header buttons', () => {
expect(onCloseModal).toHaveBeenCalled()
})
it('opens relative markdown links in the file browser and external links in a new tab', () => {
const onOpenFile = vi.fn()
const file = {
...textFile('index.md', 'text/markdown'),
content: btoa('- [ ] [report](sub/report.html)\n\n[site](https://example.com)'),
}
render(<FilePreview file={file} onOpenFile={onOpenFile} />)
fireEvent.click(screen.getByRole('link', { name: 'report' }))
expect(onOpenFile).toHaveBeenCalledWith('docker/sub/report.html')
const external = screen.getByRole('link', { name: 'site' })
expect(external).toHaveAttribute('target', '_blank')
expect(external).toHaveAttribute('rel', 'noopener noreferrer')
})
it('keeps the success and destructive tints on the edit actions in dark mode', () => {
render(<FilePreview file={textFile('Dockerfile', 'text/plain')} />)
@@ -20,9 +20,10 @@ interface FilePreviewProps {
onCloseModal?: () => void
onFileSaved?: () => void
initialLineNumber?: number
onOpenFile?: (path: string) => void
}
export const FilePreview = memo(function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal, onFileSaved, initialLineNumber }: FilePreviewProps) {
export const FilePreview = memo(function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal, onFileSaved, initialLineNumber, onOpenFile }: 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
@@ -276,7 +277,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
<div className="w-6 h-6 border-2 border-muted-foreground border-t-transparent rounded-full animate-spin" />
</div>
) : fullContent ? (
<MarkdownRenderer content={fullContent} onContentChange={handleFullMarkdownContentChange} />
<MarkdownRenderer content={fullContent} onContentChange={handleFullMarkdownContentChange} filePath={file.path} onOpenFile={onOpenFile} />
) : null}
</>
)}
@@ -315,7 +316,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
}
if (isMarkdownFile && renderedPreview) {
return <MarkdownRenderer content={displayContent} onContentChange={handleLocalMarkdownContentChange} />
return <MarkdownRenderer content={displayContent} onContentChange={handleLocalMarkdownContentChange} filePath={file.path} onOpenFile={onOpenFile} />
}
const lines = displayContent.split('\n')
@@ -4,14 +4,19 @@ import remarkGfm from 'remark-gfm'
import rehypeHighlight from 'rehype-highlight'
import rehypeRaw from 'rehype-raw'
import { markdownComponents } from './MarkdownComponents'
import { resolveLinkedFilePath } from './resolve-link-path'
import type { Components } from 'react-markdown'
interface MarkdownRendererProps {
content: string
className?: string
onContentChange?: (newContent: string) => void
filePath?: string
onOpenFile?: (path: string) => void
}
const EXTERNAL_LINK = /^https?:\/\//i
interface TaskItem {
lineIndex: number
checked: boolean
@@ -29,7 +34,7 @@ function parseTaskItems(content: string): TaskItem[] {
return items
}
export const MarkdownRenderer = memo(function MarkdownRenderer({ content, className = '', onContentChange }: MarkdownRendererProps) {
export const MarkdownRenderer = memo(function MarkdownRenderer({ content, className = '', onContentChange, filePath, onOpenFile }: MarkdownRendererProps) {
const taskItems = useMemo(() => parseTaskItems(content), [content])
const handleToggle = useCallback((taskItem: TaskItem) => {
@@ -74,6 +79,32 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({ content, classN
return <input type={type} checked={checked} disabled={disabled} {...rest} />
},
a(props) {
const { href, children, ...rest } = props
delete (rest as Record<string, unknown>).node
const linkedPath = href && filePath && onOpenFile ? resolveLinkedFilePath(filePath, href) : null
if (linkedPath && onOpenFile) {
return (
<a
href={href}
{...rest}
onClick={(event) => {
event.preventDefault()
onOpenFile(linkedPath)
}}
>
{children}
</a>
)
}
if (href && EXTERNAL_LINK.test(href)) {
return <a href={href} target="_blank" rel="noopener noreferrer" {...rest}>{children}</a>
}
return <a href={href} {...rest}>{children}</a>
},
}
return (
@@ -10,6 +10,7 @@ interface MobileFilePreviewModalProps {
onClose: () => void;
file: FileInfo | null;
showFilePreviewHeader?: boolean;
onOpenFile?: (path: string) => void;
}
export const MobileFilePreviewModal = memo(function MobileFilePreviewModal({
@@ -17,6 +18,7 @@ export const MobileFilePreviewModal = memo(function MobileFilePreviewModal({
onClose,
file,
showFilePreviewHeader = false,
onOpenFile,
}: MobileFilePreviewModalProps) {
const [localFile, setLocalFile] = useState<FileInfo | null>(null);
const isClosingRef = useRef(false);
@@ -77,6 +79,7 @@ export const MobileFilePreviewModal = memo(function MobileFilePreviewModal({
hideHeader={!showFilePreviewHeader}
isMobileModal={showFilePreviewHeader}
onCloseModal={handleClose}
onOpenFile={onOpenFile}
/>
</div>
</FullscreenSheet>
@@ -0,0 +1,47 @@
import { describe, it, expect } from 'vitest'
import { resolveLinkedFilePath } from './resolve-link-path'
const FROM = 'opencode-manager/ocm-link-test/index.md'
describe('resolveLinkedFilePath', () => {
it('resolves sibling, dot-relative, nested, and parent links against the containing file', () => {
expect(resolveLinkedFilePath(FROM, 'report.html')).toBe('opencode-manager/ocm-link-test/report.html')
expect(resolveLinkedFilePath(FROM, './report.html')).toBe('opencode-manager/ocm-link-test/report.html')
expect(resolveLinkedFilePath(FROM, 'sub/page.html')).toBe('opencode-manager/ocm-link-test/sub/page.html')
expect(resolveLinkedFilePath(FROM, '../README.md')).toBe('opencode-manager/README.md')
})
it('resolves folder links without the trailing slash', () => {
expect(resolveLinkedFilePath(FROM, 'sub/')).toBe('opencode-manager/ocm-link-test/sub')
expect(resolveLinkedFilePath(FROM, '..')).toBe('opencode-manager')
})
it('keeps parent segments above the repos root for the files API to validate', () => {
expect(resolveLinkedFilePath('opencode-manager/index.md', '../../notes.md')).toBe('../notes.md')
expect(resolveLinkedFilePath('../.config/opencode/AGENTS.md', 'skills/x.md')).toBe('../.config/opencode/skills/x.md')
})
it('returns absolute paths unchanged apart from query, fragment, and trailing slash', () => {
expect(resolveLinkedFilePath(FROM, '/workspace/repos/app/report.html#top')).toBe('/workspace/repos/app/report.html')
expect(resolveLinkedFilePath(FROM, '/workspace/repos/app/')).toBe('/workspace/repos/app')
})
it('drops query and fragment and decodes encoded names', () => {
expect(resolveLinkedFilePath(FROM, 'report.html#summary')).toBe('opencode-manager/ocm-link-test/report.html')
expect(resolveLinkedFilePath(FROM, 'my%20report.html?x=1')).toBe('opencode-manager/ocm-link-test/my report.html')
expect(resolveLinkedFilePath('repo/my docs/index.md', 'a.html')).toBe('repo/my docs/a.html')
})
it('ignores anchors, protocol-relative URLs, and scheme links', () => {
expect(resolveLinkedFilePath(FROM, '#section')).toBeNull()
expect(resolveLinkedFilePath(FROM, '//example.com/a')).toBeNull()
expect(resolveLinkedFilePath(FROM, 'https://example.com')).toBeNull()
expect(resolveLinkedFilePath(FROM, 'mailto:a@b.c')).toBeNull()
expect(resolveLinkedFilePath(FROM, '')).toBeNull()
expect(resolveLinkedFilePath(FROM, '/')).toBeNull()
})
it('returns null for malformed percent-encoding', () => {
expect(resolveLinkedFilePath(FROM, 'bad%zz.html')).toBeNull()
})
})
@@ -0,0 +1,35 @@
const URL_SCHEME = /^[a-z][a-z\d+.-]*:/i
/**
* Resolves a markdown link to the workspace path of the file or folder it points at.
* Relative links resolve against the containing file; absolute paths are returned as-is for the files API to validate.
* Returns null for anchors, protocol-relative URLs, and links with a URL scheme.
*/
export function resolveLinkedFilePath(fromFilePath: string, href: string): string | null {
if (!href || href.startsWith('#') || href.startsWith('//') || URL_SCHEME.test(href)) {
return null
}
let linkPath: string
try {
linkPath = decodeURIComponent(href.split(/[?#]/)[0])
} catch {
return null
}
if (linkPath.startsWith('/')) {
return linkPath.replace(/\/+$/, '') || null
}
const segments = fromFilePath.split('/').filter(Boolean).slice(0, -1)
for (const segment of linkPath.split('/')) {
if (segment === '' || segment === '.') continue
if (segment === '..' && segments.length > 0 && segments[segments.length - 1] !== '..') {
segments.pop()
} else {
segments.push(segment)
}
}
return segments.join('/') || null
}