Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(web-app): open links in rendered markdown outside the app
James Dam84853e0eb006
diff --git a/web-app/src/containers/RenderMarkdown.tsx b/web-app/src/containers/RenderMarkdown.tsxindex 0a6d95863..0ba2b016c 100644--- a/web-app/src/containers/RenderMarkdown.tsx+++ b/web-app/src/containers/RenderMarkdown.tsx@@ -26,6 +26,7 @@ import { MermaidError } from '@/components/MermaidError'import { CitationLink } from '@/components/CitationLink'import { WebCitationChip } from '@/components/WebCitationChip'import { MarkdownTable } from '@/components/MarkdownTable'+import { externalHref, openExternalUrl } from '@/lib/externalLink'const WEB_CITE_MARKER = /\[\[cite:\s*([^\]\s]+?)\s*\]\]/g@@ -246,7 +247,38 @@ function RenderMarkdownComponent({const url = decodeURIComponent(href.slice('#webcite-'.length))return <WebCitationChip messageId={messageId} url={url} />}- return <a {...props}>{children}</a>+ // Model and tool output decides these hrefs, so a click must never+ // navigate the app window: web and mail links open outside the app,+ // in-page fragments stay, and anything else is inert text.+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ const { node: _node, href: _href, ...rest } = props as typeof props & {+ node?: unknown+ }+ const external = externalHref(href)+ if (external) {+ return (+ <a+ {...rest}+ href={external}+ target="_blank"+ rel="noopener noreferrer"+ onClick={(e) => {+ e.preventDefault()+ openExternalUrl(external)+ }}+ >+ {children}+ </a>+ )+ }+ if (typeof href === 'string' && href.startsWith('#')) {+ return (+ <a {...rest} href={href}>+ {children}+ </a>+ )+ }+ return <a {...rest}>{children}</a>}return { a: Anchor, table: MarkdownTable, ...(components ?? {}) } as Components}, [components, messageId])diff --git a/web-app/src/containers/__tests__/RenderMarkdown.test.tsx b/web-app/src/containers/__tests__/RenderMarkdown.test.tsxindex 1b89c1917..e2c2606fb 100644--- a/web-app/src/containers/__tests__/RenderMarkdown.test.tsx+++ b/web-app/src/containers/__tests__/RenderMarkdown.test.tsx@@ -1,7 +1,19 @@-import { render, waitFor, act, cleanup } from '@testing-library/react'+import {+ render,+ waitFor,+ act,+ cleanup,+ fireEvent,+} from '@testing-library/react'import { describe, it, expect, vi, afterEach } from 'vitest'import { RenderMarkdown } from '../RenderMarkdown'import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'+import { openExternalUrl } from '@/lib/externalLink'++vi.mock('@/lib/externalLink', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/externalLink')>()),+ openExternalUrl: vi.fn(),+}))vi.mock('@i18n/react-i18next-compat', () => ({useTranslation: () => ({@@ -529,5 +541,57 @@ describe('RenderMarkdown', () => {expect(container.textContent).toContain('No citations here.')})})++ describe('links in rendered output', () => {+ afterEach(() => vi.mocked(openExternalUrl).mockClear())++ it('opens a web link outside the app instead of navigating in place', () => {+ const { container } = render(+ <RenderMarkdown content={'See [the docs](https://example.com/a?b=1).'} />+ )+ const link = container.querySelector('a[href="https://example.com/a?b=1"]')+ expect(link).toBeTruthy()+ expect(link?.getAttribute('target')).toBe('_blank')+ // fireEvent returns false when a handler called preventDefault.+ expect(fireEvent.click(link!)).toBe(false)+ expect(openExternalUrl).toHaveBeenCalledWith('https://example.com/a?b=1')+ })++ it('opens a mailto link outside the app', () => {+ const { container } = render(+ <RenderMarkdown content={'[mail](mailto:[email protected])'} />+ )+ const link = container.querySelector('a[href^="mailto:"]')+ expect(link).toBeTruthy()+ expect(fireEvent.click(link!)).toBe(false)+ expect(openExternalUrl).toHaveBeenCalledWith('mailto:[email protected]')+ })++ it.each([+ 'file:///etc/passwd',+ 'asset://localhost/%2Ftmp%2Fx.html',+ '/settings/providers',+ 'tauri://localhost/',+ ])('renders a %s link without a navigable href', (href) => {+ const { container } = render(+ <RenderMarkdown content={`[click me](${href})`} />+ )+ expect(container.textContent).toContain('click me')+ const anchors = Array.from(container.querySelectorAll('a'))+ for (const a of anchors) {+ const target = a.getAttribute('href')+ expect(target === null || target.startsWith('#')).toBe(true)+ }+ for (const a of anchors) fireEvent.click(a)+ expect(openExternalUrl).not.toHaveBeenCalled()+ })++ it('keeps an in-page fragment link', () => {+ const { container } = render(+ <RenderMarkdown content={'[jump](#section-2)'} />+ )+ expect(container.querySelector('a[href="#section-2"]')).toBeTruthy()+ })+ })})diff --git a/web-app/src/lib/externalLink.ts b/web-app/src/lib/externalLink.tsnew file mode 100644index 000000000..46c9c08b4--- /dev/null+++ b/web-app/src/lib/externalLink.ts@@ -0,0 +1,34 @@+import { openUrl } from '@tauri-apps/plugin-opener'+import { isPlatformTauri } from '@/lib/platform/utils'++/** Schemes a link may open, always outside the app. */+const EXTERNAL_PROTOCOLS = new Set(['http:', 'https:', 'mailto:'])++/**+ * The absolute URL `href` names when it should open in the system browser (or+ * mail client), else `null`. Relative paths, fragments and every other scheme+ * (`javascript:`, `file:`, `asset:`, app routes, ...) return `null`.+ */+export function externalHref(href: string | undefined | null): string | null {+ if (!href) return null+ try {+ const url = new URL(href)+ return EXTERNAL_PROTOCOLS.has(url.protocol) ? url.href : null+ } catch {+ return null+ }+}++/**+ * Open a URL outside the app. On desktop this goes through the opener plugin:+ * the app window itself must never navigate away from the app.+ */+export function openExternalUrl(url: string): void {+ if (isPlatformTauri()) {+ void openUrl(url).catch((error) =>+ console.error('Failed to open external URL:', error)+ )+ return+ }+ window.open(url, '_blank', 'noopener,noreferrer')+}diff --git a/web-app/src/lib/service.ts b/web-app/src/lib/service.tsindex c2acc6349..ecdfdf6fe 100644--- a/web-app/src/lib/service.ts+++ b/web-app/src/lib/service.ts@@ -2,6 +2,7 @@ import { CoreRoutes, APIRoutes } from '@janhq/core'import { getServiceHub } from '@/hooks/useServiceHub'import { isPlatformTauri } from '@/lib/platform'import type { InvokeArgs } from '@/services/core/types'+import { openExternalUrl } from '@/lib/externalLink'export const AppRoutes = ['installExtensions',@@ -32,10 +33,8 @@ export const Routes = [...CoreRoutes, ...APIRoutes, ...AppRoutes].map((r) => ({route: r,}))-// Function to open an external URL in a new browser window-export function openExternalUrl(url: string) {- window?.open(url, '_blank')-}+// Re-exported: extensions reach it as `window.core.api.openExternalUrl`.+export { openExternalUrl }export const APIs = {...Object.values(Routes).reduce((acc, proxy) => {