Fix markdown preview links routing to system browser instead of Orca (#5265)

* Fix markdown preview links opening in system browser instead of Orca

In the markdown preview, a plain (or Cmd/Ctrl) click on an http/https link
called window.api.shell.openUrl() directly, which always routes to
shell.openExternal (the OS default browser). It bypassed openHttpLink, so a
plain click could never open in the Orca built-in browser, regressing the
behavior from #987. The Cmd/Ctrl+Shift escape hatch was already correct.

Route both http click paths through openHttpLink via a new
resolveMarkdownPreviewHttpOpenOptions helper that centralizes the
cross-platform modifier decision (Cmd on Mac, Ctrl on Linux/Windows):
- plain / Cmd-click -> { worktreeId } -> Orca browser (per openLinksInApp),
  falling back to the system browser when the setting is off, no worktree is
  known, or a remote runtime is active.
- Cmd/Ctrl+Shift-click -> { forceSystemBrowser: true } -> system browser.

The remote/SSH case is handled inside openHttpLink (http stays on the client
system browser; file:// blocking is unchanged).

Adds a happy-dom interaction test that renders the real component and fires
real modifier clicks, plus full modifier-matrix coverage for the helper.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* review: share markdown preview link modifier logic

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com>
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Borja
2026-06-12 15:20:51 -07:00
committed by GitHub
co-authored by Claude Opus 4.8 Orca Jinwoo-H
parent 5f0a4fc5f3
commit d538549bb5
4 changed files with 297 additions and 5 deletions
@@ -0,0 +1,147 @@
// @vitest-environment happy-dom
//
// Faithful end-to-end check of the markdown-preview http link routing: renders
// the real MarkdownPreview, lets react-markdown produce a real <a>, and fires
// real modifier clicks so the component's own handleClick + modifier detection
// run. openHttpLink stays real (wired through its registerHttpLinkStoreAccessor
// seam); only its store data and window.api are controlled. This is the
// regression guard for "Cmd+Shift-click opens the system browser, plain/Cmd
// click opens the Orca browser".
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const createBrowserTabMock = vi.fn()
const setActiveWorktreeMock = vi.fn()
const openUrlMock = vi.fn()
// Minimal store: MarkdownPreview reads settings/worktreesByRepo plus a handful
// of action functions. None of the actions fire on the http path under test.
const storeState = {
openFile: vi.fn(),
activateMarkdownLink: vi.fn(),
openMarkdownPreview: vi.fn(),
setMarkdownViewMode: vi.fn(),
markdownFrontmatterVisible: {},
setPendingEditorReveal: vi.fn(),
addDiffComment: vi.fn(),
deleteDiffComment: vi.fn(),
updateDiffComment: vi.fn(),
clearDeliveredDiffComments: vi.fn(),
keybindings: {},
worktreesByRepo: {},
openFiles: [],
activeFileIdByWorktree: {},
settings: { openLinksInApp: true },
editorFontZoomLevel: 0
}
vi.mock('@/store', () => {
const useAppStore = Object.assign(
(selector: (s: typeof storeState) => unknown) => selector(storeState),
{ getState: () => storeState }
)
return { useAppStore }
})
vi.mock('@/store/slices/worktree-helpers', () => ({ findWorktreeById: () => null }))
vi.mock('@/runtime/runtime-rpc-client', () => ({
settingsForRuntimeOwner: (settings: unknown) => settings
}))
vi.mock('@/runtime/runtime-file-client', () => ({
statRuntimePath: vi.fn(async () => ({ isDirectory: false }))
}))
vi.mock('@/lib/connection-context', () => ({ getConnectionId: () => null }))
vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback }))
vi.mock('./useLocalImageSrc', () => ({ useLocalImageSrc: (src?: string) => src }))
vi.mock('./MermaidBlock', () => ({ default: () => null }))
vi.mock('./CodeBlockCopyButton', () => ({
default: ({ children }: { children: React.ReactNode }) => children
}))
vi.mock('../diff-comments/DiffCommentCard', () => ({ DiffCommentCard: () => null }))
vi.mock('./NotesSendMenu', () => ({ NotesSendMenu: () => null }))
vi.mock('./MarkdownTableOfContentsPanel', () => ({ MarkdownTableOfContentsPanel: () => null }))
import MarkdownPreview from './MarkdownPreview'
import { registerHttpLinkStoreAccessor } from '../../lib/http-link-routing'
describe('MarkdownPreview http link routing (Cmd vs Cmd+Shift click)', () => {
let container: HTMLDivElement
let root: Root
beforeEach(() => {
Object.defineProperty(window.navigator, 'userAgent', {
value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
configurable: true
})
;(window as unknown as { api: unknown }).api = {
shell: {
openUrl: openUrlMock,
openFileUri: vi.fn(),
pathExists: vi.fn(async () => true)
},
ui: { writeClipboardText: vi.fn(async () => true) }
}
// openHttpLink reads the store through this injected accessor, not @/store.
registerHttpLinkStoreAccessor(() => ({
settings: { openLinksInApp: true, activeRuntimeEnvironmentId: null },
setActiveWorktree: setActiveWorktreeMock,
createBrowserTab: createBrowserTabMock
}))
createBrowserTabMock.mockClear()
setActiveWorktreeMock.mockClear()
openUrlMock.mockClear()
})
afterEach(() => {
act(() => {
root.unmount()
})
container.remove()
})
function render(): HTMLAnchorElement {
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
act(() => {
root.render(
<MarkdownPreview
content="[example](https://example.com)"
filePath="/repo/docs/README.md"
sourceWorktreeId="wt-1"
scrollCacheKey="test-key"
/>
)
})
const anchor = container.querySelector<HTMLAnchorElement>('a[href="https://example.com"]')
if (!anchor) {
throw new Error('expected a rendered http anchor')
}
return anchor
}
function click(anchor: HTMLAnchorElement, modifiers: Partial<MouseEventInit>): void {
act(() => {
anchor.dispatchEvent(
new window.MouseEvent('click', { bubbles: true, cancelable: true, ...modifiers })
)
})
}
it('plain Cmd-click opens the link in the Orca browser', () => {
const anchor = render()
click(anchor, { metaKey: true })
expect(createBrowserTabMock).toHaveBeenCalledWith('wt-1', 'https://example.com/', {
activate: true
})
expect(openUrlMock).not.toHaveBeenCalled()
})
it('Cmd+Shift-click opens the link in the system default browser', () => {
const anchor = render()
click(anchor, { metaKey: true, shiftKey: true })
expect(openUrlMock).toHaveBeenCalledWith('https://example.com/')
expect(createBrowserTabMock).not.toHaveBeenCalled()
})
})
@@ -46,7 +46,9 @@ import {
fileUrlToAbsolutePath,
getMarkdownPreviewLinkTarget,
isMarkdownPreviewOpenModifier,
resolveMarkdownPreviewHref
isMarkdownPreviewSystemBrowserModifier,
resolveMarkdownPreviewHref,
resolveMarkdownPreviewHttpOpenOptions
} from './markdown-preview-links'
import {
createMarkdownDocumentIndex,
@@ -1238,8 +1240,7 @@ export default function MarkdownPreview({
// link to the system default handler, bypassing the classifier. For a
// dangling in-worktree .md, pre-check existence so the user sees a
// toast instead of the silent no-op from shell.openFileUri.
const modKey = isMac ? event.metaKey : event.ctrlKey
if (modKey && event.shiftKey) {
if (isMarkdownPreviewSystemBrowserModifier(event, isMac)) {
const osTarget = getMarkdownPreviewLinkTarget(href, filePath)
if (!osTarget) {
return
@@ -1251,7 +1252,10 @@ export default function MarkdownPreview({
return
}
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
openHttpLink(parsed.toString(), { forceSystemBrowser: true })
openHttpLink(
parsed.toString(),
resolveMarkdownPreviewHttpOpenOptions(event, isMac, sourceRoutingWorktreeId)
)
return
}
if (parsed.protocol === 'file:') {
@@ -1303,7 +1307,14 @@ export default function MarkdownPreview({
}
if (target.protocol === 'http:' || target.protocol === 'https:') {
void window.api.shell.openUrl(target.toString())
// Why: route through openHttpLink (not raw shell.openUrl) so a plain
// click honors the "open links in Orca" setting; openHttpLink keeps
// remote runtimes on the system browser. (Cmd/Ctrl+Shift-click is
// handled above; this path only sees non-escape-hatch clicks.)
openHttpLink(
target.toString(),
resolveMarkdownPreviewHttpOpenOptions(event, isMac, sourceRoutingWorktreeId)
)
return
}
@@ -5,7 +5,9 @@ import {
getMarkdownPreviewImageOpenTarget,
getMarkdownPreviewLinkTarget,
isMarkdownPreviewOpenModifier,
isMarkdownPreviewSystemBrowserModifier,
resolveMarkdownPreviewHref,
resolveMarkdownPreviewHttpOpenOptions,
resolveImageAbsolutePath
} from './markdown-preview-links'
@@ -106,6 +108,115 @@ describe('isMarkdownPreviewOpenModifier', () => {
})
})
describe('isMarkdownPreviewSystemBrowserModifier', () => {
it('uses Cmd+Shift on macOS', () => {
expect(
isMarkdownPreviewSystemBrowserModifier(
{ metaKey: true, ctrlKey: false, shiftKey: true },
true
)
).toBe(true)
expect(
isMarkdownPreviewSystemBrowserModifier(
{ metaKey: false, ctrlKey: true, shiftKey: true },
true
)
).toBe(false)
})
it('uses Ctrl+Shift on non-macOS platforms', () => {
expect(
isMarkdownPreviewSystemBrowserModifier(
{ metaKey: false, ctrlKey: true, shiftKey: true },
false
)
).toBe(true)
expect(
isMarkdownPreviewSystemBrowserModifier(
{ metaKey: true, ctrlKey: false, shiftKey: true },
false
)
).toBe(false)
})
})
describe('resolveMarkdownPreviewHttpOpenOptions', () => {
// forceSystemBrowser -> shell.openExternal (system default browser);
// worktreeId (no force) -> openHttpLink routes into the Orca browser per the
// openLinksInApp setting. See http-link-routing.test.ts for that mapping.
it('forces the system browser on Cmd+Shift-click on macOS', () => {
expect(
resolveMarkdownPreviewHttpOpenOptions(
{ metaKey: true, ctrlKey: false, shiftKey: true },
true,
'wt-1'
)
).toEqual({ forceSystemBrowser: true })
})
it('forces the system browser on Ctrl+Shift-click on Linux/Windows', () => {
expect(
resolveMarkdownPreviewHttpOpenOptions(
{ metaKey: false, ctrlKey: true, shiftKey: true },
false,
'wt-1'
)
).toEqual({ forceSystemBrowser: true })
})
it('routes a plain Cmd-click through the worktree so it can open in Orca', () => {
expect(
resolveMarkdownPreviewHttpOpenOptions(
{ metaKey: true, ctrlKey: false, shiftKey: false },
true,
'wt-1'
)
).toEqual({ worktreeId: 'wt-1' })
})
it('routes a plain click (no modifier) through the worktree', () => {
expect(
resolveMarkdownPreviewHttpOpenOptions(
{ metaKey: false, ctrlKey: false, shiftKey: false },
true,
'wt-1'
)
).toEqual({ worktreeId: 'wt-1' })
})
it('does not force the system browser for Shift without the platform mod key', () => {
// Plain Shift-click (no Cmd/Ctrl) is not the escape hatch.
expect(
resolveMarkdownPreviewHttpOpenOptions(
{ metaKey: false, ctrlKey: false, shiftKey: true },
true,
'wt-1'
)
).toEqual({ worktreeId: 'wt-1' })
})
it('does not treat Mac Ctrl+Shift-click as the escape hatch', () => {
// On macOS the mod key is Cmd; Ctrl+Shift must not force the system browser.
expect(
resolveMarkdownPreviewHttpOpenOptions(
{ metaKey: false, ctrlKey: true, shiftKey: true },
true,
'wt-1'
)
).toEqual({ worktreeId: 'wt-1' })
})
it('passes through a null worktree (openHttpLink then falls back to system browser)', () => {
expect(
resolveMarkdownPreviewHttpOpenOptions(
{ metaKey: false, ctrlKey: false, shiftKey: false },
true,
null
)
).toEqual({ worktreeId: null })
})
})
describe('resolveImageAbsolutePath', () => {
it('resolves a relative image src to an absolute filesystem path', () => {
expect(resolveImageAbsolutePath('diagram.png', '/repo/docs/README.md')).toBe(
@@ -4,6 +4,7 @@ import {
fileUriToFilesystemPath
} from '../../../../shared/file-uri-path'
import { isWindowsAbsolutePathLike } from '../../../../shared/cross-platform-path'
import type { OpenHttpLinkOptions } from '@/lib/http-link-routing'
function toFileUrl(filePath: string): string {
return filesystemPathToFileUri(filePath)
@@ -105,6 +106,28 @@ export function isMarkdownPreviewOpenModifier(
return isMac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey
}
export function isMarkdownPreviewSystemBrowserModifier(
event: Pick<MouseEvent, 'metaKey' | 'ctrlKey' | 'shiftKey'>,
isMac: boolean
): boolean {
return event.shiftKey && (isMac ? event.metaKey : event.ctrlKey)
}
// Why: Cmd/Ctrl+Shift-click is the escape hatch that forces the OS default
// browser; every other click routes through openHttpLink so the "open links in
// Orca" setting (and remote-runtime state) decides the destination. Mac uses
// metaKey, Linux/Windows use ctrlKey per AGENTS.md.
export function resolveMarkdownPreviewHttpOpenOptions(
event: Pick<MouseEvent, 'metaKey' | 'ctrlKey' | 'shiftKey'>,
isMac: boolean,
worktreeId: string | null
): OpenHttpLinkOptions {
if (isMarkdownPreviewSystemBrowserModifier(event, isMac)) {
return { forceSystemBrowser: true }
}
return { worktreeId }
}
/**
* Resolves a relative image src against the markdown file path to produce an
* absolute filesystem path. Returns null for external URLs (http, https, data,