fix: open markdown file images in Orca (#1734)

This commit is contained in:
Neil
2026-05-12 22:42:39 -07:00
committed by GitHub
parent aa0a1d2ed9
commit 4608f622bf
6 changed files with 100 additions and 56 deletions
+7 -2
View File
@@ -1,11 +1,11 @@
import { resolve, relative, dirname, basename, isAbsolute } from 'path'
import { realpathSync } from 'fs'
import { realpath } from 'fs/promises'
import type { Store } from '../persistence'
import { listRepoWorktrees } from '../repo-worktrees'
export const PATH_ACCESS_DENIED_MESSAGE =
'Access denied: path resolves outside allowed directories. If this blocks a legitimate workflow, please file a GitHub issue.'
const authorizedExternalPaths = new Set<string>()
const registeredWorktreeRoots = new Set<string>()
const registeredWorktreeRootsByRepo = new Map<string, Set<string>>()
@@ -14,7 +14,12 @@ let registeredWorktreeRootsDirty = true
let registeredWorktreeRootsRefresh: Promise<void> | null = null
export function authorizeExternalPath(targetPath: string): void {
authorizedExternalPaths.add(resolve(targetPath))
const resolvedTarget = resolve(targetPath)
authorizedExternalPaths.add(resolvedTarget)
try {
// Why: macOS canonicalizes /tmp to /private/tmp during read authorization.
authorizedExternalPaths.add(realpathSync(resolvedTarget))
} catch {}
}
export function invalidateAuthorizedRootsCache(): void {
@@ -26,7 +26,6 @@ import { detectLanguage } from '@/lib/language-detect'
import type { MarkdownDocument, Worktree } from '../../../../shared/types'
import {
fileUrlToAbsolutePath,
getMarkdownPreviewImageOpenTarget,
getMarkdownPreviewLinkTarget,
isMarkdownPreviewOpenModifier,
resolveMarkdownPreviewHref
@@ -49,6 +48,7 @@ import {
} from './markdown-preview-search'
import { usePreserveSectionDuringExternalEdit } from './usePreserveSectionDuringExternalEdit'
import { openHttpLink } from '@/lib/http-link-routing'
import { markdownPreviewUrlTransform } from './markdown-preview-url-transform'
type MarkdownPreviewProps = {
content: string
@@ -62,6 +62,14 @@ type MarkdownPreviewProps = {
const markdownPreviewSanitizeSchema = {
...defaultSchema,
tagNames: [...(defaultSchema.tagNames ?? []), 'details', 'summary', 'kbd', 'sub', 'sup', 'ins'],
protocols: {
...defaultSchema.protocols,
// Why: markdown preview owns file:// click routing and authorizes the
// user-selected path before opening it in Orca. Sanitization must preserve
// the target so the click handler can make that security decision.
href: [...(defaultSchema.protocols?.href ?? []), 'file'],
src: [...(defaultSchema.protocols?.src ?? []), 'file']
},
attributes: {
...defaultSchema.attributes,
'*': [...(defaultSchema.attributes?.['*'] ?? []), 'id'],
@@ -169,11 +177,13 @@ export default function MarkdownPreview({
const [activeMatchIndex, setActiveMatchIndex] = useState(-1)
const isMac = navigator.userAgent.includes('Mac')
const openFile = useAppStore((s) => s.openFile)
const activateMarkdownLink = useAppStore((s) => s.activateMarkdownLink)
const openMarkdownPreview = useAppStore((s) => s.openMarkdownPreview)
const setMarkdownViewMode = useAppStore((s) => s.setMarkdownViewMode)
const setPendingEditorReveal = useAppStore((s) => s.setPendingEditorReveal)
const worktreesByRepo = useAppStore((s) => s.worktreesByRepo)
const worktreeRoot = findWorktreeForMarkdownPreviewPath(worktreesByRepo, filePath)?.path ?? null
const sourceWorktree = findWorktreeForMarkdownPreviewPath(worktreesByRepo, filePath)
const worktreeRoot = sourceWorktree?.path ?? null
const settings = useAppStore((s) => s.settings)
const editorFontZoomLevel = useAppStore((s) => s.editorFontZoomLevel)
const editorFontSize = computeEditorFontSize(14, editorFontZoomLevel)
@@ -534,6 +544,14 @@ export default function MarkdownPreview({
const targetWorktree = findWorktreeForMarkdownPreviewPath(worktreesByRepo, absolutePath)
if (!targetWorktree) {
if (sourceWorktree) {
void activateMarkdownLink(href, {
sourceFilePath: filePath,
worktreeId: sourceWorktree.id,
worktreeRoot: sourceWorktree.path
})
return
}
void window.api.shell.openFileUri(target.toString())
return
}
@@ -613,41 +631,16 @@ export default function MarkdownPreview({
return
}
const target = getMarkdownPreviewImageOpenTarget(src, filePath)
if (!target) {
if (!src || !sourceWorktree) {
return
}
event.preventDefault()
event.stopPropagation()
if (target.protocol === 'http:' || target.protocol === 'https:') {
void window.api.shell.openUrl(target.toString())
return
}
if (target.protocol !== 'file:') {
return
}
const absolutePath = fileUrlToAbsolutePath(target)
if (!absolutePath) {
return
}
const targetWorktree = findWorktreeForMarkdownPreviewPath(worktreesByRepo, absolutePath)
if (!targetWorktree) {
void window.api.shell.openFileUri(target.toString())
return
}
const relativePath = absolutePath.slice(targetWorktree.path.length + 1)
openFile({
filePath: absolutePath,
relativePath,
worktreeId: targetWorktree.id,
language: detectLanguage(absolutePath),
mode: 'edit'
void activateMarkdownLink(src, {
sourceFilePath: filePath,
worktreeId: sourceWorktree.id,
worktreeRoot: sourceWorktree.path
})
}
@@ -739,6 +732,7 @@ export default function MarkdownPreview({
// cover every value the overrides actually close over; slugger is a ref.
}, [
filePath,
activateMarkdownLink,
isDark,
isMac,
markdownDocumentIndex,
@@ -748,6 +742,7 @@ export default function MarkdownPreview({
scrollToAnchor,
setMarkdownViewMode,
setPendingEditorReveal,
sourceWorktree,
worktreeRoot,
worktreesByRepo
])
@@ -847,6 +842,9 @@ export default function MarkdownPreview({
)}
<Markdown
components={components}
// Why: react-markdown filters file:// after rehype-sanitize; preview
// click handlers need the target so they can authorize and open it.
urlTransform={markdownPreviewUrlTransform}
remarkPlugins={[
remarkGfm,
remarkBreaks,
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest'
import { markdownPreviewUrlTransform } from './markdown-preview-url-transform'
describe('markdownPreviewUrlTransform', () => {
it('preserves file URLs for preview links and images', () => {
expect(markdownPreviewUrlTransform('file:///tmp/screenshot.png', 'src')).toBe(
'file:///tmp/screenshot.png'
)
expect(markdownPreviewUrlTransform('file:///tmp/screenshot.png', 'href')).toBe(
'file:///tmp/screenshot.png'
)
})
it('keeps react-markdown defaults for unsafe protocols', () => {
expect(markdownPreviewUrlTransform('javascript:alert(1)', 'href')).toBe('')
expect(markdownPreviewUrlTransform('file:///tmp/screenshot.png', 'cite')).toBe('')
})
})
@@ -0,0 +1,9 @@
import { defaultUrlTransform } from 'react-markdown'
export function markdownPreviewUrlTransform(value: string, key: string): string {
if ((key === 'href' || key === 'src') && value.toLowerCase().startsWith('file:')) {
return value
}
return defaultUrlTransform(value)
}
+16 -3
View File
@@ -1019,12 +1019,14 @@ describe('createEditorSlice activateMarkdownLink', () => {
const openUrlMock = vi.fn()
const openFileUriMock = vi.fn()
const pathExistsMock = vi.fn()
const authorizeExternalPathMock = vi.fn()
beforeEach(() => {
toastErrorMock.mockReset()
openUrlMock.mockReset()
openFileUriMock.mockReset()
pathExistsMock.mockReset()
authorizeExternalPathMock.mockReset()
openHttpLinkMock.mockReset()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(globalThis as any).window = (globalThis as any).window ?? {}
@@ -1034,6 +1036,9 @@ describe('createEditorSlice activateMarkdownLink', () => {
openUrl: openUrlMock,
openFileUri: openFileUriMock,
pathExists: pathExistsMock
},
fs: {
authorizeExternalPath: authorizeExternalPathMock
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -1150,15 +1155,23 @@ describe('createEditorSlice activateMarkdownLink', () => {
expect(openFileUriMock).not.toHaveBeenCalled()
})
it('delegates outside-worktree files to shell.openFileUri', async () => {
it('opens explicit file URLs outside the worktree in Orca after authorizing them', async () => {
const store = createEditorStore()
await store.getState().activateMarkdownLink('file:///tmp/image.png', {
sourceFilePath: '/repo/docs/note.md',
worktreeId: 'wt-1',
worktreeRoot: '/repo'
})
expect(openFileUriMock).toHaveBeenCalledWith('file:///tmp/image.png')
expect(store.getState().openFiles).toEqual([])
expect(authorizeExternalPathMock).toHaveBeenCalledWith({ targetPath: '/tmp/image.png' })
expect(store.getState().openFiles).toEqual([
expect.objectContaining({
filePath: '/tmp/image.png',
relativePath: '/tmp/image.png',
mode: 'edit',
isPreview: true
})
])
expect(openFileUriMock).not.toHaveBeenCalled()
})
it('activates same-file line anchors via setActiveFile without opening a new tab', async () => {
+20 -19
View File
@@ -2131,26 +2131,27 @@ export const createEditorSlice: StateCreator<AppState, [], [], EditorSlice> = (s
return
}
if (target.kind === 'file') {
if (target.relativePath !== undefined) {
// Why: explicit file:// links inside the active worktree should behave
// like relative file links and open in Orca, including image files.
get().openFile(
{
filePath: target.absolutePath,
relativePath: target.relativePath,
worktreeId: ctx.worktreeId,
language: detectLanguage(target.absolutePath),
mode: 'edit'
},
{
preview: true,
targetGroupId: get().activeGroupIdByWorktree?.[ctx.worktreeId],
recordReplacedPreview: true
}
)
return
if (target.relativePath === undefined) {
// Why: terminal file links already authorize clicked external paths
// before opening them in Orca. Markdown file:// links need the same
// user-gesture authorization so /tmp screenshots can use ImageViewer.
await window.api.fs.authorizeExternalPath({ targetPath: target.absolutePath })
}
void window.api.shell.openFileUri(target.uri)
get().openFile(
{
filePath: target.absolutePath,
relativePath: target.relativePath ?? target.absolutePath,
worktreeId: ctx.worktreeId,
language: detectLanguage(target.absolutePath),
mode: 'edit'
},
{
preview: true,
targetGroupId: get().activeGroupIdByWorktree?.[ctx.worktreeId],
recordReplacedPreview: true
}
)
return
}