Files
hapi/web/src/components/assistant-ui/markdown-text.tsx
T

1081 lines
44 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import '@assistant-ui/react-markdown/styles/dot.css'
import type { ComponentPropsWithoutRef, ComponentType, MouseEvent, ReactNode } from 'react'
import { Children, Fragment, cloneElement, isValidElement, useState, useCallback, useEffect, useMemo, createContext, useContext } from 'react'
import {
MarkdownTextPrimitive,
unstable_memoizeMarkdownComponents as memoizeMarkdownComponents,
useIsMarkdownCodeBlock,
type CodeHeaderProps,
} from '@assistant-ui/react-markdown'
import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'
import remarkCjkFriendly from 'remark-cjk-friendly/parseOnly'
import remarkMath from 'remark-math'
import rehypeKatex from 'rehype-katex'
import remarkDisableIndentedCode from '@/lib/remark-disable-indented-code'
import remarkRepairTables from '@/lib/remark-repair-tables'
import remarkLatexBracketMath from '@/lib/remark-latex-bracket-math'
import { useNavigate } from '@tanstack/react-router'
import { PRESERVE_SESSION_SIDEBAR_SCROLL } from '@/lib/sessionNavigation'
import remarkStripCjkAutolink from '@/lib/remark-strip-cjk-autolink'
import remarkNonHttpsAutolink from '@/lib/remark-non-https-autolink'
import { cn, encodeBase64 } from '@/lib/utils'
import { SyntaxHighlighter } from '@/components/assistant-ui/shiki-highlighter'
import { MermaidDiagram } from '@/components/assistant-ui/mermaid-diagram'
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'
import { useCodeWrap } from '@/hooks/useCodeWrap'
import { CopyIcon, CheckIcon, WrapIcon } from '@/components/icons'
import { useTranslation } from '@/lib/use-translation'
import { useOptionalHappyChatContext } from '@/components/AssistantChat/context'
import { decodeFilePathCandidateHref, decodeFilePathHref, remarkFilePathLinks } from '@/lib/remark-file-path-links'
import { classifyNoSchemeHref, resolveMarkdownRelativePath } from '@/lib/markdown-href-policy'
import { useQuery } from '@tanstack/react-query'
import { useAppContext } from '@/lib/app-context'
import { queryKeys } from '@/lib/query-keys'
import { useSessionDirectory } from '@/hooks/queries/useSessionDirectory'
import { resolveImageMimeType } from '@/lib/file-markdown-preview'
import { remarkSessionPathLinks } from '@/lib/remark-session-path-links'
import { buildSessionReferencePath, parseSessionPathHref } from '@/lib/sessionReference'
import { UriConfirmDialog } from '@/components/UriConfirmDialog'
import { DEFAULT_OPEN_EXTERNAL_LINKS_IN_NEW_TAB, useOpenExternalLinksInNewTab } from '@/hooks/useOpenExternalLinksInNewTab'
import { ChatMarkdownImage } from '@/components/assistant-ui/markdown-image'
import {
classifyScheme,
denyOnlyTransform,
hasScheme,
isDeniedScheme,
isExternalHttpHref,
normalizedScheme,
} from '@/lib/markdown-uri-policy'
export { classifyScheme, denyOnlyTransform, isExternalHttpHref } from '@/lib/markdown-uri-policy'
import type { MarkdownTextPrimitiveProps } from '@assistant-ui/react-markdown'
// Session file being previewed; relative links/images resolve against its directory.
// fileSearch carries the preview's browsing context (origin/tab/query) so Back still returns to it.
export type MarkdownFileSearch = { origin?: 'chat'; tab?: 'changes' | 'directories'; query?: string }
export type MarkdownFileBaseValue = {
sessionId: string
filePath: string
workspacePath: string | null
fileSearch: MarkdownFileSearch
}
export const MarkdownFileBaseContext = createContext<MarkdownFileBaseValue | null>(null)
// ── Plugin array ────────────────────────────────────────────────────────────
// Order: remarkGfm → remarkRepairTables → remarkCjkFriendly → remarkLatexBracketMath → remarkNonHttpsAutolink → remarkStripCjkAutolink → remarkMath → remarkDisableIndentedCode → remarkSessionPathLinks → remarkFilePathLinks
// remarkRepairTables must run immediately after remarkGfm — it reads file.value
// (raw source) to pad short separator rows before remark-gfm parses the table.
// remarkCjkFriendly is a parse-time micromark extension
// (commonmark/commonmark-spec#650):
// it lets `**` close before CJK particles that directly follow punctuation
// (e.g. `**...(...)**은`). It stays after remarkRepairTables so the documented
// remarkGfm → remarkRepairTables adjacency is preserved; position in the array
// does not affect parsing, which happens once before any transformer runs.
// remarkNonHttpsAutolink must run BEFORE remarkStripCjkAutolink so that the
// CJK strip plugin sees the new link nodes and can trim trailing CJK punctuation
// from them. Both must come before remarkMath (to avoid treating TeX as URI).
// remarkSessionPathLinks turns bare /sessions/<id> citations into links.
// remarkFilePathLinks runs last to convert file paths → links after all other
// transforms have settled.
//
// remarkMath is configured with `singleDollarTextMath: false` so that prose
// containing currency amounts (e.g. "$200/mo ... $80 bill") is not garbled
// into KaTeX output. Block math `$$...$$` (on its own line) still works.
// This matches GitHub-flavored markdown behavior. The option lives on the
// shared TAIL so both MARKDOWN_PLUGINS (default) and MARKDOWN_PLUGINS_WITH_BREAKS
// (user-prompt rendering with hard breaks) inherit the fix.
const MARKDOWN_PLUGIN_TAIL_HEAD = [
remarkNonHttpsAutolink,
remarkStripCjkAutolink,
[remarkMath, { singleDollarTextMath: false }],
remarkDisableIndentedCode,
] satisfies NonNullable<MarkdownTextPrimitiveProps['remarkPlugins']>
const MARKDOWN_PLUGIN_TAIL = [
...MARKDOWN_PLUGIN_TAIL_HEAD,
remarkSessionPathLinks, // bare /sessions/<id> → clickable session citation
remarkFilePathLinks, // upstream — file path → link conversion, runs last
] satisfies NonNullable<MarkdownTextPrimitiveProps['remarkPlugins']>
// Standalone surfaces (file-preview) render without HappyChatContext, so the
// FilePathAnchor cannot route hapi-file: hrefs — rewriting explicit markdown
// links there would collapse them to plain text. Keep bare-path / inlineCode
// autolinks (already inert on that surface) but disable explicit-link rewrite.
const MARKDOWN_PLUGIN_TAIL_STANDALONE = [
...MARKDOWN_PLUGIN_TAIL_HEAD,
remarkSessionPathLinks,
[remarkFilePathLinks, { rewriteExplicitLinks: false }],
] satisfies NonNullable<MarkdownTextPrimitiveProps['remarkPlugins']>
// A single tilde is common in shell prompts (for example, `user@host:~$`).
// Keep it literal while preserving GFM strikethrough via double tildes.
const REMARK_GFM_PLUGIN = [
remarkGfm,
{ singleTilde: false },
] satisfies NonNullable<MarkdownTextPrimitiveProps['remarkPlugins']>[number]
export const MARKDOWN_PLUGINS = [
REMARK_GFM_PLUGIN,
remarkRepairTables,
remarkCjkFriendly,
remarkLatexBracketMath,
...MARKDOWN_PLUGIN_TAIL,
] satisfies NonNullable<MarkdownTextPrimitiveProps['remarkPlugins']>
export const MARKDOWN_PLUGINS_STANDALONE = [
REMARK_GFM_PLUGIN,
remarkRepairTables,
remarkCjkFriendly,
remarkLatexBracketMath,
...MARKDOWN_PLUGIN_TAIL_STANDALONE,
] satisfies NonNullable<MarkdownTextPrimitiveProps['remarkPlugins']>
// User-authored prompts should preserve Shift+Enter/newline intent without
// changing assistant/tool markdown behavior globally.
export const MARKDOWN_PLUGINS_WITH_BREAKS = [
REMARK_GFM_PLUGIN,
remarkRepairTables,
remarkCjkFriendly,
remarkLatexBracketMath,
remarkBreaks,
...MARKDOWN_PLUGIN_TAIL,
] satisfies NonNullable<MarkdownTextPrimitiveProps['remarkPlugins']>
export const MARKDOWN_PLUGINS_STANDALONE_WITH_BREAKS = [
REMARK_GFM_PLUGIN,
remarkRepairTables,
remarkCjkFriendly,
remarkLatexBracketMath,
remarkBreaks,
...MARKDOWN_PLUGIN_TAIL_STANDALONE,
] satisfies NonNullable<MarkdownTextPrimitiveProps['remarkPlugins']>
export const MARKDOWN_REHYPE_PLUGINS = [rehypeKatex] satisfies NonNullable<MarkdownTextPrimitiveProps['rehypePlugins']>
export const MARKDOWN_CLASSNAME = 'aui-md happy-chat-text min-w-0 max-w-full break-words text-[var(--app-fg)]'
export const MARKDOWN_COMPONENTS_BY_LANGUAGE = {
mermaid: {
SyntaxHighlighter: MermaidDiagram,
},
} satisfies NonNullable<MarkdownTextPrimitiveProps['componentsByLanguage']>
// URI classification and deny-only URL transformation live in
// `markdown-uri-policy.ts` so file assets and chat Markdown share one policy.
/**
* Extract the normalised scheme from a URL string.
*
* Applies up to two rounds of decodeURIComponent so that double-encoded
* bypass attempts (`javascript%253A` → `javascript%3A` → `javascript:`)
* are unwrapped before the scheme is extracted.
*
* After decoding, ASCII control characters (U+0000–U+001F, U+007F) and
* all whitespace are stripped from the extracted scheme string so that
* browsers' built-in normalization — which silently discards \t, \n, \r
* and space from scheme names during navigation — cannot be used to bypass
* the deny list (e.g. `java\nscript:alert(1)` → scheme `"javascript"`).
*
* Returns null when no valid scheme separator is found.
*/
/**
* Classify a URL string by its scheme.
*
* Uses normalizedScheme() so that common bypass patterns — control characters
* spliced into the scheme name, tab/space prefix, single- and double-encoded
* scheme characters — are all caught before the deny/IANA comparison.
*
* @returns 'iana' | 'deny' | 'custom'
*/
/**
* Returns true when href contains a URL scheme (i.e. a "scheme:" prefix that
* appears before any path/query/fragment delimiter).
*
* This distinguishes `mailto:foo@bar` (has scheme → true) from purely relative
* hrefs like `/settings`, `./foo`, `#section`, `?q=1`, or paths that contain a
* colon after a path segment like `/path:colon` (→ false, because `/` appears
* before `:`). Protocol-relative URLs (`//host/path`) have no colon and are
* also treated as scheme-less; browsers navigate them as the current origin's
* protocol, same as a normal relative path would do.
*
* Used by <A> to short-circuit classifyScheme for no-scheme hrefs and treat them
* as 'iana' so the browser/router can handle them normally (fixing the regression
* where relative markdown links were silently blocked by the onClick deny guard).
*/
/**
* True when href is a genuine external http(s) link — as opposed to a
* relative/SPA href (no scheme, e.g. `/settings`) or another scheme
* (`mailto:`, `vscode:`, a Windows drive path like `C:\Users\...`, etc).
*
* Used by <A> to decide whether the "open external links in a new tab"
* setting (Settings > Display > Links) applies — forcing target="_blank" on
* a relative href would open the whole app in a second tab instead of
* navigating in-app, so this must stay scoped to real http(s) URLs.
*/
// ── URL sanitize transform (deny-only) ──────────────────────────────────────
// Passed as urlTransform to MarkdownTextPrimitive. Only deny-listed schemes
// are stripped; every other scheme (IANA + custom) passes through so the
// <a href> is preserved for the onClick layer to handle.
//
// Uses classifyScheme as the single source of truth for scheme extraction so
// that percent-encoded bypass patterns (jav%61script:, %6Aavascript:) are
// caught by the same decoding logic used at click time.
//
// Relative paths (no colon, or colon only in path/query) have no scheme and
// are always passed through — they are safe and used for img src etc.
//
// Known limitation (FIX 5, deferred): data:image/png;base64,... used in
// <img src> is also stripped because DENY_SCHEMES includes 'data'. However,
// react-markdown's own defaultUrlTransform strips all data: URLs identically,
// so this is not a regression introduced by this PR.
// ── Allowed-schemes state (inlined from useAllowedSchemes.ts) ───────────────
const STORAGE_KEY = 'hapi-allowed-schemes'
// Module-level subscriber set for intra-tab cross-provider sync (P7e.1).
//
// `window` `storage` events fire only in OTHER tabs/windows, not in the same
// tab that called setItem. When two <UriConfirmProvider>s exist in the same
// window (e.g. MarkdownText + Reasoning as sibling providers in AssistantMessage),
// clicking "Always allow" in one provider's dialog must immediately update the
// other without waiting for a page reload.
//
// Solution: a module-level Set of subscriber callbacks. writeAllowedToStorage
// calls each subscriber synchronously after writing to localStorage. Each
// useAllowedSchemes instance registers on mount and unregisters on unmount.
// Cross-tab sync continues to use the existing window `storage` event.
type SchemeListener = (schemes: ReadonlySet<string>) => void
const schemeListeners = new Set<SchemeListener>()
function readAllowedFromStorage(): Set<string> {
try {
const raw = localStorage.getItem(STORAGE_KEY)
if (!raw) return new Set()
const parsed = JSON.parse(raw)
if (!Array.isArray(parsed)) return new Set()
return new Set(
parsed
.filter((s): s is string => typeof s === 'string')
.filter((s) => !isDeniedScheme(s))
)
} catch {
return new Set()
}
}
function writeAllowedToStorage(schemes: ReadonlySet<string>): void {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(Array.from(schemes)))
} catch {
// Storage quota exceeded — silently ignore; in-memory set still works.
}
// Notify all same-tab subscribers synchronously so sibling providers
// (e.g. MarkdownText + Reasoning) update in the same React event loop tick.
for (const listener of schemeListeners) {
listener(schemes)
}
}
function useAllowedSchemes() {
const [allowed, setAllowed] = useState<ReadonlySet<string>>(() => readAllowedFromStorage())
useEffect(() => {
// Cross-tab sync: storage event fires in other tabs/windows.
function handleStorage(e: StorageEvent) {
if (e.key !== STORAGE_KEY) return
setAllowed(readAllowedFromStorage())
}
window.addEventListener('storage', handleStorage)
// Intra-tab sync: subscribe to module-level emitter so sibling
// providers in the same window see updates without page reload.
function handleIntraTab(schemes: ReadonlySet<string>) {
setAllowed(new Set(schemes))
}
schemeListeners.add(handleIntraTab)
return () => {
window.removeEventListener('storage', handleStorage)
schemeListeners.delete(handleIntraTab)
}
}, [])
const allow = useCallback((scheme: string) => {
if (isDeniedScheme(scheme)) return
setAllowed((prev) => {
if (prev.has(scheme)) return prev
const next = new Set(prev)
next.add(scheme)
writeAllowedToStorage(next)
return next
})
}, [])
const isAllowed = useCallback(
(scheme: string): boolean => {
if (isDeniedScheme(scheme)) return false
return allowed.has(scheme)
},
[allowed]
)
return { allowed, allow, isAllowed }
}
// ── UriConfirmContext — one dialog per markdown root ────────────────────────
type DialogState = {
url: string
scheme: string
} | null
type UriConfirmContextValue = {
openUri: (url: string, scheme: string) => void
/** Shared isAllowed so all <a> tags in this tree re-render on the same state update. */
isAllowed: (scheme: string) => boolean
/** User preference (Settings > Display > Links): force target="_blank" on external http(s) links. */
openExternalLinksInNewTab: boolean
}
const UriConfirmContext = createContext<UriConfirmContextValue | null>(null)
/**
* Provider that mounts a single <UriConfirmDialog> for all <a> links in its
* subtree. Wrap each MarkdownText / MarkdownRenderer / Reasoning surface with
* this so that only one dialog instance exists per markdown root instead of
* one per <a> tag.
*
* The allowed-schemes state lives here so all child <A> components share the
* same React state — when "Always allow" is clicked, every link in the tree
* re-renders in the same React commit (no cross-tab storage event required).
*/
export function UriConfirmProvider({ children }: { children: ReactNode }) {
const [dialog, setDialog] = useState<DialogState>(null)
const { allow, isAllowed } = useAllowedSchemes()
const { openExternalLinksInNewTab } = useOpenExternalLinksInNewTab()
const openUri = useCallback((url: string, scheme: string) => {
setDialog({ url, scheme })
}, [])
const closeDialog = () => setDialog(null)
const handleOpen = () => {
if (!dialog) return
closeDialog()
window.open(dialog.url, '_blank', 'noopener,noreferrer')
}
const handleAlwaysAllow = (allowedScheme: string) => {
allow(allowedScheme)
closeDialog()
if (dialog) {
window.open(dialog.url, '_blank', 'noopener,noreferrer')
}
}
const contextValue = useMemo(
() => ({ openUri, isAllowed, openExternalLinksInNewTab }),
[openUri, isAllowed, openExternalLinksInNewTab]
)
return (
<UriConfirmContext.Provider value={contextValue}>
{children}
{dialog !== null && (
<UriConfirmDialog
open={true}
url={dialog.url}
scheme={dialog.scheme}
onCancel={closeDialog}
onOpen={handleOpen}
onAlwaysAllow={handleAlwaysAllow}
/>
)}
</UriConfirmContext.Provider>
)
}
// ── Components ───────────────────────────────────────────────────────────────
function CodeHeader(props: CodeHeaderProps) {
const { t } = useTranslation()
const { copied, copy } = useCopyToClipboard()
const { codeWrap, setCodeWrap } = useCodeWrap()
const language = props.language && props.language !== 'unknown' ? props.language : 'text'
return (
<div data-hapi-code-header="true" className="aui-code-shell-header flex items-center justify-between gap-3 rounded-t-xl bg-[var(--app-code-header-bg)] pl-[22px] pr-[10px] py-2 text-[11px] uppercase tracking-[0.08em] text-[var(--app-code-header-fg)]">
<div className="min-w-0 flex-1 truncate font-mono">
{language}
</div>
<div className="flex shrink-0 items-center gap-1">
<button
type="button"
data-hapi-code-wrap-toggle="true"
data-hapi-wrap-enable-label={t('code.wrap.enable')}
data-hapi-wrap-disable-label={t('code.wrap.disable')}
data-hapi-share-export-exclude="true"
onClick={() => setCodeWrap(!codeWrap)}
className={`rounded-md p-1 transition-colors hover:bg-[var(--app-code-copy-hover-bg)] hover:text-[var(--app-fg)] ${codeWrap ? 'text-[var(--app-fg)]' : 'text-[var(--app-code-header-fg)]'}`}
title={t(codeWrap ? 'code.wrap.disable' : 'code.wrap.enable')}
aria-pressed={codeWrap}
>
<WrapIcon className="h-3.5 w-3.5" />
</button>
<button
type="button"
data-hapi-code-copy="true"
data-hapi-copy-label={t('code.copy')}
data-hapi-copied-label={t('message.copied')}
data-hapi-share-export-exclude="true"
onClick={() => copy(props.code)}
className="rounded-md p-1 text-[var(--app-code-header-fg)] transition-colors hover:bg-[var(--app-code-copy-hover-bg)] hover:text-[var(--app-fg)]"
title={t('code.copy')}
>
<span data-hapi-copy-default="true" className={copied ? 'hidden' : ''}>
<CopyIcon className="h-3.5 w-3.5" />
</span>
<span data-hapi-copy-success="true" className={copied ? '' : 'hidden'}>
<CheckIcon className="h-3.5 w-3.5" />
</span>
</button>
</div>
</div>
)
}
function Pre(props: ComponentPropsWithoutRef<'pre'>) {
const { className, style, ...rest } = props
const { codeWrap } = useCodeWrap()
return (
<div className={cn(
'aui-md-pre-wrapper min-w-0 w-full max-w-full overflow-y-hidden',
codeWrap ? '' : 'overflow-x-auto'
)} data-hapi-code-body="true">
<pre
data-hapi-code-grid="true"
{...rest}
className={cn(
'aui-md-pre m-0 rounded-b-xl bg-[var(--app-code-bg)] px-4 py-3 text-sm',
codeWrap ? '' : 'w-max min-w-full',
className
)}
// Inline style, not a `whitespace-pre-wrap` class: index.css
// has an unlayered `.aui-md :where(pre) { white-space: pre }`
// rule that always beats Tailwind's `@layer utilities`
// regardless of specificity (unlayered CSS always outranks
// any `@layer` in the cascade). See shiki-highlighter.tsx
// for the same fix + fuller explanation.
style={codeWrap ? { ...style, whiteSpace: 'pre-wrap', wordBreak: 'break-word' } : style}
/>
</div>
)
}
function Code(props: ComponentPropsWithoutRef<'code'>) {
const isCodeBlock = useIsMarkdownCodeBlock()
if (isCodeBlock) {
return (
<code
{...props}
className={cn('aui-md-codeblockcode font-mono', props.className)}
/>
)
}
return (
<code
{...props}
className={cn(
'aui-md-code break-words rounded-md border border-[var(--app-inline-code-border)] bg-[var(--app-inline-code-bg)] px-[0.38em] py-[0.14em] font-mono text-[0.88em] text-[var(--app-inline-code-fg)]',
props.className
)}
/>
)
}
function FilePathAnchor(props: ComponentPropsWithoutRef<'a'> & {
filePath: string
sessionId: string
fileSearch?: MarkdownFileSearch
}) {
const { filePath, sessionId, fileSearch = { origin: 'chat' }, ...anchorProps } = props
const navigate = useNavigate()
const rel = anchorProps.target === '_blank' ? (anchorProps.rel ?? 'noreferrer') : anchorProps.rel
const fileRouteSearch = { path: encodeBase64(filePath), ...fileSearch }
const search = new URLSearchParams(
Object.entries(fileRouteSearch).filter((entry): entry is [string, string] => entry[1] !== undefined)
).toString()
const href = `/sessions/${encodeURIComponent(sessionId)}/file?${search}`
const handleClick = (event: MouseEvent<HTMLAnchorElement>) => {
anchorProps.onClick?.(event)
if (event.defaultPrevented) return
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
event.preventDefault()
void navigate({
to: '/sessions/$sessionId/file',
params: { sessionId },
search: fileRouteSearch,
...PRESERVE_SESSION_SIDEBAR_SCROLL,
})
}
return (
<a
{...anchorProps}
href={href}
rel={rel}
onClick={handleClick}
className={cn('aui-md-a font-medium text-[var(--app-link)] underline decoration-[color:var(--app-link-muted)] underline-offset-3', anchorProps.className)}
/>
)
}
function SessionPathAnchor(props: ComponentPropsWithoutRef<'a'> & { targetSessionId: string }) {
const { targetSessionId, ...anchorProps } = props
const navigate = useNavigate()
const rel = anchorProps.target === '_blank' ? (anchorProps.rel ?? 'noreferrer') : anchorProps.rel
// Preserve Vite BASE_URL for copy / open-in-new-tab (SPA click uses navigate).
const href = buildSessionReferencePath(props.targetSessionId)
const handleClick = (event: MouseEvent<HTMLAnchorElement>) => {
anchorProps.onClick?.(event)
if (event.defaultPrevented) return
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
event.preventDefault()
void navigate({
to: '/sessions/$sessionId',
params: { sessionId: props.targetSessionId },
...PRESERVE_SESSION_SIDEBAR_SCROLL,
})
}
return (
<a
{...anchorProps}
href={href}
rel={rel}
onClick={handleClick}
className={cn('aui-md-a font-medium text-[var(--app-link)] underline decoration-[color:var(--app-link-muted)] underline-offset-3', props.className)}
/>
)
}
/**
* Anchor component with URI scheme policy enforcement.
*
* - Scheme-less hrefs (#1452 fail-closed): known app routes (`/settings`, `#`,
* `?`, `/sessions/…`) stay SPA-navigable; workspace file targets open via
* FilePathAnchor; any other path-like href renders as inert (non-clickable)
* text so we never paint a blue link that SPA-404s.
* - IANA safe schemes (https/http/mailto/irc/ircs/xmpp): navigate directly.
* - Deny schemes (javascript/data/vbscript/file): silently block. denyOnlyTransform
* already strips the href to "", so href="" in DOM (belt-and-suspenders onClick
* guard also calls preventDefault).
* - Custom schemes, NOT yet allowed by user: href="#" in DOM (not the live URL)
* so middle-click / drag-to-bar cannot bypass the dialog. Dialog opens on left-click
* via the shared UriConfirmContext (single dialog per markdown root).
* - Custom schemes, already allowed by user: live href in DOM; middle-click works.
* - File-path links (decoded by remarkFilePathLinks): delegated to FilePathAnchor
* which uses useNavigate for SPA routing.
* - Session citation paths (`/sessions/<id>`): SessionPathAnchor SPA navigation.
*/
function InertMarkdownHref(props: { href: string; children?: ReactNode; className?: string }) {
// Plain/muted — intentionally not an <a>, so middle-click / copy-link can't
// invent a dead SPA route either.
return (
<span
title={props.href}
className={cn('aui-md-a-inert text-[var(--app-hint)]', props.className)}
>
{props.children}
</span>
)
}
type LinkChildSegment = {
interactiveImage: boolean
children: ReactNode[]
}
type SplitLinkNode = {
interactiveImage: boolean
node: ReactNode
}
function splitInteractiveImageNodes(child: ReactNode, fileBase: MarkdownFileBaseValue | null): SplitLinkNode[] {
if (!isValidElement<{ children?: ReactNode; src?: unknown }>(child)) {
return [{ interactiveImage: false, node: child }]
}
const src = typeof child.props.src === 'string' ? child.props.src : null
if (src) {
const standalonePath = fileBase
? resolveMarkdownRelativePath(fileBase.filePath, src, fileBase.workspacePath)
: null
return [{ interactiveImage: !standalonePath, node: child }]
}
const nestedChildren = Children.toArray(child.props.children)
if (nestedChildren.length === 0) {
return [{ interactiveImage: false, node: child }]
}
const nested = nestedChildren.flatMap((nestedChild) => splitInteractiveImageNodes(nestedChild, fileBase))
if (!nested.some((segment) => segment.interactiveImage)) {
return [{ interactiveImage: false, node: child }]
}
return nested.map((segment, index) => ({
interactiveImage: segment.interactiveImage,
node: cloneElement(
child,
{ key: `${String(child.key ?? 'node')}-${index}` },
segment.node,
),
}))
}
function renderSplitInteractiveImageLink(
children: ReactNode,
fileBase: MarkdownFileBaseValue | null,
renderAnchor: (children: ReactNode, key: string) => ReactNode,
): ReactNode | null {
const segments: LinkChildSegment[] = []
const splitNodes = Children.toArray(children).flatMap((child) => splitInteractiveImageNodes(child, fileBase))
for (const splitNode of splitNodes) {
if (splitNode.interactiveImage) {
segments.push({ interactiveImage: true, children: [splitNode.node] })
continue
}
const previous = segments.at(-1)
if (previous && !previous.interactiveImage) previous.children.push(splitNode.node)
else segments.push({ interactiveImage: false, children: [splitNode.node] })
}
if (!segments.some((segment) => segment.interactiveImage)) return null
return (
<>
{segments.map((segment, index) => segment.interactiveImage
? <Fragment key={`image-${index}`}>{segment.children}</Fragment>
: renderAnchor(segment.children, `link-${index}`))}
</>
)
}
function A(props: ComponentPropsWithoutRef<'a'>) {
const chat = useOptionalHappyChatContext()
// useContext must be called unconditionally before any early return so that
// the Rules of Hooks are satisfied regardless of whether `filePath` is set.
// isAllowed comes exclusively from the shared context. Every call site
// (MarkdownText, Reasoning, MarkdownRenderer) wraps its surface with
// <UriConfirmProvider>, so ctx is always present in production.
//
// The previous localHook fallback instantiated useAllowedSchemes() even
// when ctx was present — 20 anchors → 21 storage listeners per mount.
// Removing it requires tests that render <A> directly to wrap with
// <UriConfirmProvider> (or supply a mock UriConfirmContext.Provider).
const ctx = useContext(UriConfirmContext)
const filePath = typeof props.href === 'string' ? decodeFilePathHref(props.href) : null
const candidatePath =
typeof props.href === 'string' ? decodeFilePathCandidateHref(props.href) : null
const targetSessionId = typeof props.href === 'string' ? parseSessionPathHref(props.href) : null
const fileBase = useContext(MarkdownFileBaseContext)
const rel = props.target === '_blank' ? (props.rel ?? 'noreferrer') : props.rel
if (filePath) {
if (!chat) {
return <>{props.children}</>
}
const split = renderSplitInteractiveImageLink(
props.children,
fileBase,
(children, key) => (
<FilePathAnchor key={key} {...props} filePath={filePath} sessionId={chat.sessionId}>
{children}
</FilePathAnchor>
),
)
if (split) return split
return <FilePathAnchor {...props} filePath={filePath} sessionId={chat.sessionId} />
}
if (targetSessionId) {
const split = renderSplitInteractiveImageLink(
props.children,
fileBase,
(children, key) => (
<SessionPathAnchor key={key} {...props} targetSessionId={targetSessionId}>
{children}
</SessionPathAnchor>
),
)
if (split) return split
return <SessionPathAnchor {...props} targetSessionId={targetSessionId} />
}
const relativeFilePath = fileBase && typeof props.href === 'string'
? resolveMarkdownRelativePath(fileBase.filePath, props.href, fileBase.workspacePath)
: null
if (fileBase && relativeFilePath) {
const split = renderSplitInteractiveImageLink(
props.children,
fileBase,
(children, key) => (
<FilePathAnchor
key={key}
{...props}
filePath={relativeFilePath}
sessionId={fileBase.sessionId}
fileSearch={fileBase.fileSearch}
>
{children}
</FilePathAnchor>
),
)
if (split) return split
return (
<FilePathAnchor
{...props}
filePath={relativeFilePath}
sessionId={fileBase.sessionId}
fileSearch={fileBase.fileSearch}
/>
)
}
const { onClick, href, ...rest } = props
// Windows candidate (or raw / %5C-normalized drive path): classify with workspace
// before painting FilePathAnchor or treating `C:` as a custom URI scheme.
// Candidates are Windows-only; reject empty / non-drive payloads fail-closed
// (do not fall through to custom-scheme confirmation for this scheme).
const isCandidateHref = href ? normalizedScheme(href) === 'hapi-file-candidate' : false
if (isCandidateHref && (!candidatePath || !/^[A-Za-z]:[\\/]/.test(candidatePath))) {
return (
<InertMarkdownHref href={href ?? ''} className={props.className}>
{props.children}
</InertMarkdownHref>
)
}
const windowsPathFromHref = (() => {
if (candidatePath) return candidatePath
if (!href) return null
if (/^[A-Za-z]:[\\/]/.test(href)) return href
// mdast→hast may percent-encode backslashes before props.href arrives.
if (/^[A-Za-z]:(?:%5[Cc]|\/)/.test(href)) {
try {
return decodeURIComponent(href)
} catch {
return null
}
}
return null
})()
if (windowsPathFromHref || (href && !hasScheme(href))) {
const decision = classifyNoSchemeHref(windowsPathFromHref ?? href!, {
workspacePath: chat?.metadata?.path ?? null,
})
if (decision.action === 'file') {
if (!chat) {
return <InertMarkdownHref href={href ?? windowsPathFromHref ?? ''} className={props.className}>{props.children}</InertMarkdownHref>
}
const split = renderSplitInteractiveImageLink(
props.children,
fileBase,
(children, key) => (
<FilePathAnchor key={key} {...props} filePath={decision.path} sessionId={chat.sessionId}>
{children}
</FilePathAnchor>
),
)
if (split) return split
return <FilePathAnchor {...props} filePath={decision.path} sessionId={chat.sessionId} />
}
if (decision.action === 'inert') {
return <InertMarkdownHref href={href ?? windowsPathFromHref ?? ''} className={props.className}>{props.children}</InertMarkdownHref>
}
// action === 'navigate' → fall through (only for non-Windows scheme-less SPA)
}
const isAllowed = ctx?.isAllowed ?? (() => false)
// Relative / no-scheme hrefs that passed fail-closed as SPA-safe must not be
// classified via classifyScheme — it returns 'deny' for inputs with no valid
// scheme, which previously caused the onClick handler to preventDefault and
// silently break all relative markdown links. Treat them as 'iana' so the
// browser or SPA router can navigate normally.
const isRelative = href ? (!hasScheme(href) || Boolean(windowsPathFromHref)) : false
const classification = href && !isRelative ? classifyScheme(href) : 'iana'
const colonIdx = href ? href.indexOf(':') : -1
const scheme = colonIdx > 0 && !isRelative ? href!.slice(0, colonIdx).toLowerCase() : ''
const isCustomAllowed = classification === 'custom' && isAllowed(scheme)
// Settings > Display > Links toggle: force genuine external http(s) links
// to open in a new browser tab instead of navigating same-tab.
const openExternalLinksInNewTab = ctx?.openExternalLinksInNewTab ?? DEFAULT_OPEN_EXTERNAL_LINKS_IN_NEW_TAB
const forceNewTab = openExternalLinksInNewTab && isExternalHttpHref(href)
const target = forceNewTab ? '_blank' : props.target
const effectiveRel = forceNewTab ? (rel ?? 'noopener noreferrer') : rel
const domHref =
classification === 'iana' || isCustomAllowed
? href
: classification === 'custom'
? '#'
: href
const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
const url = href ?? ''
if (!url) {
e.preventDefault()
return
}
if (classification === 'deny') {
e.preventDefault()
return
}
if (classification === 'iana') {
onClick?.(e)
return
}
if (isCustomAllowed) {
onClick?.(e)
return
}
// Unallowed custom scheme: show confirmation dialog via context.
e.preventDefault()
ctx?.openUri(url, scheme)
}
const split = renderSplitInteractiveImageLink(
props.children,
fileBase,
(children, key) => (
<a
key={key}
{...rest}
href={domHref}
target={target}
rel={effectiveRel}
onClick={handleClick}
className={cn('aui-md-a font-medium text-[var(--app-link)] underline decoration-[color:var(--app-link-muted)] underline-offset-3', props.className)}
>
{children}
</a>
),
)
if (split) return split
return (
<a
{...rest}
href={domHref}
target={target}
rel={effectiveRel}
onClick={handleClick}
className={cn('aui-md-a font-medium text-[var(--app-link)] underline decoration-[color:var(--app-link-muted)] underline-offset-3', props.className)}
/>
)
}
function Paragraph(props: ComponentPropsWithoutRef<'p'>) {
return <p {...props} className={cn('aui-md-p my-2.5 leading-7 first:mt-0 last:mb-0', props.className)} />
}
function Blockquote(props: ComponentPropsWithoutRef<'blockquote'>) {
return (
<blockquote
{...props}
className={cn(
'aui-md-blockquote my-3 rounded-r-2xl border-l-[3px] border-[var(--app-md-quote-border)] bg-[var(--app-md-quote-bg)] px-4 py-3 text-[var(--app-md-quote-fg)]',
props.className
)}
/>
)
}
function UnorderedList(props: ComponentPropsWithoutRef<'ul'>) {
return <ul {...props} className={cn('aui-md-ul my-2.5 list-disc pl-6 marker:text-[var(--app-hint)] [&>li]:mt-1.5', props.className)} />
}
function OrderedList(props: ComponentPropsWithoutRef<'ol'>) {
return <ol {...props} className={cn('aui-md-ol my-2.5 list-decimal pl-6 marker:text-[var(--app-hint)] [&>li]:mt-1.5', props.className)} />
}
function ListItem(props: ComponentPropsWithoutRef<'li'>) {
return <li {...props} className={cn('aui-md-li leading-7', props.className)} />
}
function Hr(props: ComponentPropsWithoutRef<'hr'>) {
return <hr {...props} className={cn('aui-md-hr my-4 border-[var(--app-divider)]', props.className)} />
}
function Table(props: ComponentPropsWithoutRef<'table'>) {
const { className, ...rest } = props
return (
<div className="aui-md-table-wrapper my-3 max-w-full overflow-x-auto rounded-xl bg-[var(--app-md-table-bg)]">
<table {...rest} className={cn('aui-md-table w-full border-collapse text-sm', className)} />
</div>
)
}
function Thead(props: ComponentPropsWithoutRef<'thead'>) {
return <thead {...props} className={cn('aui-md-thead bg-[var(--app-md-table-head-bg)]', props.className)} />
}
function Tbody(props: ComponentPropsWithoutRef<'tbody'>) {
return <tbody {...props} className={cn('aui-md-tbody', props.className)} />
}
function Tr(props: ComponentPropsWithoutRef<'tr'>) {
return <tr {...props} className={cn('aui-md-tr border-t border-[var(--app-divider)] first:border-t-0', props.className)} />
}
function Th(props: ComponentPropsWithoutRef<'th'>) {
return (
<th
{...props}
className={cn(
'aui-md-th px-3 py-2 text-left font-semibold text-[var(--app-fg)] [[align=center]]:text-center [[align=right]]:text-right',
props.className
)}
/>
)
}
function Td(props: ComponentPropsWithoutRef<'td'>) {
return <td {...props} className={cn('aui-md-td px-3 py-2 align-top text-[var(--app-fg)] [[align=center]]:text-center [[align=right]]:text-right', props.className)} />
}
function H1(props: ComponentPropsWithoutRef<'h1'>) {
return <h1 {...props} className={cn('aui-md-h1 mt-4 text-[1.05rem] font-semibold tracking-[-0.01em] first:mt-0', props.className)} />
}
function H2(props: ComponentPropsWithoutRef<'h2'>) {
return <h2 {...props} className={cn('aui-md-h2 mt-4 text-base font-semibold tracking-[-0.01em] first:mt-0', props.className)} />
}
function H3(props: ComponentPropsWithoutRef<'h3'>) {
return <h3 {...props} className={cn('aui-md-h3 mt-3 text-[0.95rem] font-semibold first:mt-0', props.className)} />
}
function H4(props: ComponentPropsWithoutRef<'h4'>) {
return <h4 {...props} className={cn('aui-md-h4 mt-3 text-[0.92rem] font-semibold first:mt-0', props.className)} />
}
function H5(props: ComponentPropsWithoutRef<'h5'>) {
return <h5 {...props} className={cn('aui-md-h5 mt-2.5 text-[0.9rem] font-semibold first:mt-0', props.className)} />
}
function H6(props: ComponentPropsWithoutRef<'h6'>) {
return <h6 {...props} className={cn('aui-md-h6 mt-2.5 text-[0.88rem] font-semibold first:mt-0', props.className)} />
}
function Strong(props: ComponentPropsWithoutRef<'strong'>) {
return <strong {...props} className={cn('aui-md-strong font-semibold text-[var(--app-fg)]', props.className)} />
}
function Em(props: ComponentPropsWithoutRef<'em'>) {
return <em {...props} className={cn('aui-md-em italic', props.className)} />
}
// Previews read referenced images automatically; stay well below the hub's RPC payload limit.
const MAX_MARKDOWN_IMAGE_BYTES = 10 * 1024 * 1024
function SessionFileImage(props: ComponentPropsWithoutRef<'img'> & { sessionId: string; path: string }) {
const { sessionId, path, ...imgProps } = props
const { api } = useAppContext()
const mimeType = resolveImageMimeType(path)
const slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))
const directory = useSessionDirectory(api, sessionId, path.slice(0, Math.max(slash, 0)), { enabled: Boolean(mimeType) })
const entry = directory.entries.find((candidate) => candidate.name === path.slice(slash + 1))
const query = useQuery({
queryKey: queryKeys.sessionFile(sessionId, path),
queryFn: async () => await api.readSessionFile(sessionId, path),
enabled: Boolean(mimeType) && entry?.type === 'file' && (entry.size ?? Infinity) <= MAX_MARKDOWN_IMAGE_BYTES,
})
const src = query.data?.success && query.data.content && mimeType
? `data:${mimeType};base64,${query.data.content}`
: undefined
return <img {...imgProps} src={src} className={cn('aui-md-img my-3 max-w-full rounded-xl', props.className)} />
}
function Image(props: ComponentPropsWithoutRef<'img'>) {
const fileBase = useContext(MarkdownFileBaseContext)
const path = fileBase && typeof props.src === 'string'
? resolveMarkdownRelativePath(fileBase.filePath, props.src, fileBase.workspacePath)
: null
if (fileBase && path) {
return <SessionFileImage {...props} sessionId={fileBase.sessionId} path={path} />
}
return <ChatMarkdownImage {...props} />
}
type DefaultComponentsMap = {
[key: string]: ComponentType<any>
code: ComponentType<any>
pre: ComponentType<any>
CodeHeader: ComponentType<any>
SyntaxHighlighter: ComponentType<any>
}
export const defaultComponents: DefaultComponentsMap = memoizeMarkdownComponents({
SyntaxHighlighter,
CodeHeader,
pre: Pre,
code: Code,
h1: H1,
h2: H2,
h3: H3,
h4: H4,
h5: H5,
h6: H6,
a: A,
p: Paragraph,
strong: Strong,
em: Em,
blockquote: Blockquote,
ul: UnorderedList,
ol: OrderedList,
li: ListItem,
hr: Hr,
table: Table,
thead: Thead,
tbody: Tbody,
tr: Tr,
th: Th,
td: Td,
img: Image,
} as const) as unknown as DefaultComponentsMap
export function MarkdownText({ smooth }: { smooth?: boolean } = {}) {
return (
<UriConfirmProvider>
<MarkdownTextPrimitive
smooth={smooth}
remarkPlugins={MARKDOWN_PLUGINS}
rehypePlugins={MARKDOWN_REHYPE_PLUGINS}
components={defaultComponents}
componentsByLanguage={MARKDOWN_COMPONENTS_BY_LANGUAGE}
urlTransform={denyOnlyTransform}
className={cn(MARKDOWN_CLASSNAME)}
/>
</UriConfirmProvider>
)
}