Skip to content

Enterprise agent platform for building, deploying, and operating AI teammates.

23.0 KB
Raw Blame
import React, { useEffect, useState } from 'react'
import ReactMarkdown, { defaultUrlTransform } from 'react-markdown'
import remarkGfm from 'remark-gfm'
import rehypeKatex from 'rehype-katex'
import { remarkCurrencySafeMath } from '@/lib/remark-currency-safe-math'
import { remarkPreserveTableContent } from '@/lib/remark-preserve-table-content'
import type { Components, ExtraProps } from 'react-markdown'
import { apiRequest } from '@/lib/api-wrapper'
import { AgentCard } from '@/components/chat/AgentCard'
import { useI18n } from '@/contexts/i18n-context'
import { InlineFilePreview } from '@/components/file/inline-file-preview'
import {
  getInlineFilePreviewKind,
  getInlineFilePreviewMimeType,
  isPreviewableInlineFileKind,
  resolveInlineFileId,
  type PreviewableInlineFileKind,
} from '@/components/file/inline-file-preview-utils'
import { getApiUrl } from '@/lib/utils'
import {
  AgentCardPresentationCapability,
  LinksOpenInNewTabCapability,
  resolveAgentCardPresentationCapability,
} from '@/contexts/presentation-capabilities'
import {
  isManagedFileUrl,
  projectFilesDisabledPresentation,
  sanitizeFilesDisabledPresentationText,
} from '@/lib/files-disabled-presentation'


interface AgentInfo {
  id: number
  name: string
  description?: string
  status: 'draft' | 'published'
  instructions?: string
}

// Enhanced Markdown detection function: covers broader Markdown features not limited to starting with #
const isLikelyMarkdown = (s: string): boolean => {
  const t = s.trim()
  if (!t) return false
  return (
    t.startsWith('#') || // Heading
    s.includes('```') || // Code block
    s.includes('**') || // Bold
    /(\n|^)\s*(-|\*|\d+\.)\s/.test(s) || // List (unordered/ordered)
    (s.includes('|') && s.includes('---')) || // Table
    /\[[^\]]+\]\([^\)]+\)/.test(s) || // Link [text](url)
    /!\[[^\]]*\]\([^\)]+\)/.test(s) || // Image ![alt](url)
    /(\n|^)\s*>\s/.test(s) || // Blockquote
    /(\n|^)\s*---\s*(\n|$)/.test(s) // Horizontal rule
  )
}

const isRecord = (value: unknown): value is Record<string, unknown> => (
  typeof value === 'object' && value !== null && !Array.isArray(value)
)

interface MarkdownRendererProps {
  content: string
  className?: string
  filesDisabled?: boolean
  agentCardsEnabled?: boolean
  onFileClick?: (filePath: string, fileName: string) => void
  onAgentClick?: (agentId: string, agentName: string) => void
}

const safeUrlTransform = (url: string): string => {
  if (!url) return ''
  if (url.startsWith('file:')) return url
  if (url.startsWith('agent:')) return url
  return defaultUrlTransform(url)
}

// Hook to fetch agent details
function useAgentInfo(agentId: string) {
  const [agentInfo, setAgentInfo] = useState<AgentInfo | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    let cancelled = false

    async function fetchAgentInfo() {
      try {
        setLoading(true)
        setError(null)

        const apiUrl = getApiUrl()
        const response = await apiRequest(`${apiUrl}/api/agents/${agentId}`)

        if (!response.ok) {
          throw new Error(`Failed to fetch agent: ${response.statusText}`)
        }

        const data: AgentInfo = await response.json()

        if (!cancelled) {
          setAgentInfo(data)
        }
      } catch (err) {
        if (!cancelled) {
          setError(err as Error)
        }
      } finally {
        if (!cancelled) {
          setLoading(false)
        }
      }
    }

    fetchAgentInfo()

    return () => {
      cancelled = true
    }
  }, [agentId])

  return { agentInfo, loading, error }
}


// Agent Card Container component that fetches data
function AgentCardContainer({
  agentId,
  agentName: initialAgentName,
  onAgentClick,
}: {
  agentId: string
  agentName: string
  onAgentClick?: (agentId: string, agentName: string) => void
}) {
  const { t } = useI18n()
  const { agentInfo, loading, error } = useAgentInfo(agentId)

  // Show loading state
  if (loading) {
    return (
      <div className="inline-flex items-center gap-2 bg-muted/50 border border-border rounded-lg p-3 my-2 max-w-sm">
        <div className="w-8 h-8 rounded-md bg-muted animate-pulse" />
        <div className="flex-1">
          <div className="h-4 bg-muted rounded animate-pulse w-32 mb-1" />
          <div className="h-3 bg-muted rounded animate-pulse w-24" />
        </div>
      </div>
    )
  }

  // Show error state with fallback name
  if (error || !agentInfo) {
    return (
      <AgentCard
        agentId={agentId}
        agentName={initialAgentName}
        description={t("markdownRenderer.loadAgentDetailsFailed")}
        status="draft"
      />
    )
  }

  // Show agent info
  // Don't pass onClick - let AgentCard handle navigation internally based on status
  return (
    <AgentCard
      agentId={agentId}
      agentName={agentInfo.name}
      description={agentInfo.description || agentInfo.instructions}
      status={agentInfo.status}
    />
  )
}

function containsAgentCardElement(children: React.ReactNode): boolean {
  return React.Children.toArray(children).some((child) => {
    if (!React.isValidElement(child)) {
      return false
    }

    if (child.props?.['data-agent-card-wrapper']) {
      return true
    }

    return containsAgentCardElement(child.props?.children)
  })
}

function containsBlockPreviewElement(children: React.ReactNode): boolean {
  return React.Children.toArray(children).some((child) => {
    if (!React.isValidElement(child)) {
      return false
    }

    if (child.props?.['data-inline-file-preview-wrapper']) {
      return true
    }

    return containsBlockPreviewElement(child.props?.children)
  })
}

function hastText(node: any): string {
  if (!node) return ''
  if (typeof node.value === 'string') return node.value
  if (!Array.isArray(node.children)) return ''
  return node.children.map(hastText).join('')
}

const nodeText = (children: React.ReactNode): string => {
  return React.Children.toArray(children)
    .map((child) => {
      if (typeof child === 'string' || typeof child === 'number') {
        return String(child)
      }
      if (React.isValidElement(child)) {
        return nodeText(child.props?.children)
      }
      return ''
    })
    .join('')
}

function resolvePreviewableFileLink({
  fileNameFromPath,
  title,
  visibleText,
}: {
  fileNameFromPath: string
  /**
   * Link title, if any. The backend injects the real filename here
   * precisely so type detection survives when the model rewrites the
   * visible label/alt text into descriptive prose that drops the
   * extension — so this is tried before ``visibleText`` for detection.
   */
  title: string
  /**
   * The model's own label (link) or alt text (image), if any. Preferred
   * over the title for what's *shown* to the user — the title is a
   * detection hint, not display text — and also tried for *detection*
   * whenever the title itself doesn't classify as any previewable kind,
   * so a label that reveals the type (e.g. a plain ``report.mp4``) still
   * classifies correctly when there's no title, or a stale/irrelevant one.
   *
   * Detection tries ``title`` first and stops at the first candidate that
   * classifies to *any* previewable kind — it does not compare the two and
   * prefer visibleText's kind when it differs from title's. This is looser
   * than the backend's own gate for when it injects/overwrites a title
   * (``label_reveals_type`` in file_reference_output_service.py): the
   * backend only touches the title when the label doesn't already reveal a
   * type, so in the reference-generation path the two never disagree in
   * practice. A hand-authored or otherwise unusual reference where both
   * title and label classify, to different kinds, resolves to title's kind
   * here rather than label's -- pinned by the "lets a title that
   * classifies differently than the label win detection" test in
   * markdown-renderer.test.tsx; this component does not attempt to close
   * that edge case.
   */
  visibleText: string
}): { previewKind: PreviewableInlineFileKind; displayFilename: string } | null {
  const displayFilename = visibleText || title || fileNameFromPath

  const pathKind = getInlineFilePreviewKind({ filename: fileNameFromPath })
  if (isPreviewableInlineFileKind(pathKind)) {
    return { previewKind: pathKind, displayFilename }
  }

  for (const candidate of [title, visibleText]) {
    if (!candidate) continue
    const kind = getInlineFilePreviewKind({ filename: candidate })
    if (isPreviewableInlineFileKind(kind)) {
      return { previewKind: kind, displayFilename }
    }
  }

  return null
}

function containsPreviewFileLinkNode(node: any): boolean {
  if (!node) return false
  const href = node.properties?.href
  if (typeof href === 'string' && href.startsWith('file:')) {
    const filePath = href.replace(/^file:/, '')
    const fileNameFromPath = filePath.split('/').pop() || filePath
    const title = typeof node.properties?.title === 'string' ? node.properties.title : ''
    const label = hastText(node)
    if (resolvePreviewableFileLink({ fileNameFromPath, title, visibleText: label })) {
      return true
    }
  }
  const src = node.properties?.src
  if (typeof src === 'string' && src.startsWith('file:')) {
    return true
  }
  if (!Array.isArray(node.children)) return false
  return node.children.some(containsPreviewFileLinkNode)
}

type MarkdownRendererContextValue = {
  filesDisabled: boolean
  agentCardsEnabled: boolean
  linksOpenInNewTab: boolean
  onFileClick?: (filePath: string, fileName: string) => void
  onAgentClick?: (agentId: string, agentName: string) => void
  openLabel: string
  loadErrorText: string
}

type MarkdownComponentProps<Tag extends keyof React.JSX.IntrinsicElements> =
  React.ComponentPropsWithoutRef<Tag> & ExtraProps

const MarkdownRendererContext = React.createContext<MarkdownRendererContextValue | null>(null)

function useMarkdownRendererContext(): MarkdownRendererContextValue {
  const context = React.useContext(MarkdownRendererContext)
  if (!context) {
    throw new Error('Markdown components must be rendered within MarkdownRenderer')
  }
  return context
}

function MarkdownParagraph({
  node,
  children,
  ...props
}: MarkdownComponentProps<'p'>) {
  if (
    containsAgentCardElement(children) ||
    containsBlockPreviewElement(children) ||
    containsPreviewFileLinkNode(node)
  ) {
    return (
      <div className="my-4" {...props}>
        {children}
      </div>
    )
  }

  return <p {...props}>{children}</p>
}

function MarkdownTable({ node: _node, children, ...props }: MarkdownComponentProps<'table'>) {
  const { t } = useI18n()
  return (
    <div
      className="markdown-table-scroll"
      role="region"
      aria-label={t('markdownRenderer.tableScrollLabel')}
      tabIndex={0}
    >
      <table {...props}>{children}</table>
    </div>
  )
}

function MarkdownLink({
  node,
  href,
  title,
  children,
  ...props
}: MarkdownComponentProps<'a'>) {
  const {
    filesDisabled,
    agentCardsEnabled,
    linksOpenInNewTab,
    onFileClick,
    onAgentClick,
    openLabel,
    loadErrorText,
  } =
    useMarkdownRendererContext()
  const linkText = (node ? hastText(node) : nodeText(children)).trim()
  const presentationChildren = filesDisabled
    ? sanitizeFilesDisabledPresentationText(linkText)
    : children
  const presentationTitle = filesDisabled && title
    ? sanitizeFilesDisabledPresentationText(title)
    : title

  if (href && href.startsWith('file:')) {
    const filePath = href.replace(/^file:/, '')
    const fileNameFromPath = filePath.split('/').pop() || filePath
    const preview = resolvePreviewableFileLink({
      fileNameFromPath,
      title: title || '',
      visibleText: linkText,
    })
    const fileId = resolveInlineFileId(filePath)

    if (filesDisabled) {
      return <span>{presentationChildren}</span>
    }

    if (preview) {
      return (
        <InlineFilePreview
          source={{
            fileId,
            filename: preview.displayFilename,
            type: preview.previewKind,
            mimeType: getInlineFilePreviewMimeType(preview.previewKind),
          }}
          openLabel={openLabel}
          loadErrorText={loadErrorText}
          onFileClick={onFileClick}
        />
      )
    }

    const handleClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
      if (onFileClick) {
        event.preventDefault()
        // linkText-first, matching every other display path in this
        // component: title is a detection hint (see resolvePreviewableFileLink
        // above), not the name a user should see in the resulting preview.
        const fallbackTitle = linkText || title || fileNameFromPath
        onFileClick(fileId, fallbackTitle)
      }
    }

    return (
      <a
        href="#"
        data-file-path={filePath}
        className="file-link"
        title={title || undefined}
        onClick={handleClick}
        {...props}
      >
        {children}
      </a>
    )
  }

  if (href && href.startsWith('agent:')) {
    const agentId = href.replace(/^agent:\/\//, '')
    const agentNameFromLink =
      (node ? hastText(node) : nodeText(children)).trim() || `Agent ${agentId}`

    if (!agentCardsEnabled) {
      return <span>{presentationChildren}</span>
    }

    return React.createElement('div', {
      className: 'my-2',
      key: `agent-${agentId}-wrapper`,
      'data-agent-card-wrapper': true,
    }, React.createElement(AgentCardContainer, {
      key: `agent-${agentId}`,
      agentId,
      agentName: agentNameFromLink,
      onAgentClick,
    }))
  }

  if (
    filesDisabled
    && href
    && (
      isManagedFileUrl(href)
      || sanitizeFilesDisabledPresentationText(href) !== href
    )
  ) {
    return <span>{presentationChildren}</span>
  }

  const opensInNewTab = linksOpenInNewTab && !!href
    && !(href.startsWith('#') || href.toLowerCase().startsWith('mailto:'))

  return (
    <a
      {...props}
      href={href || undefined}
      title={presentationTitle || undefined}
      target={opensInNewTab ? '_blank' : undefined}
      rel={opensInNewTab ? 'noopener noreferrer' : undefined}
    >
      {presentationChildren}
    </a>
  )
}

function MarkdownImage({
  node: _node,
  src,
  alt,
  title,
  ...props
}: MarkdownComponentProps<'img'>) {
  const { filesDisabled, onFileClick, openLabel, loadErrorText } =
    useMarkdownRendererContext()
  const resolvedSrc = src || ''
  const presentationAlt = filesDisabled
    ? sanitizeFilesDisabledPresentationText(alt || '')
    : alt || ''
  const presentationTitle = filesDisabled && title
    ? sanitizeFilesDisabledPresentationText(title)
    : title

  if (resolvedSrc.startsWith('file:')) {
    const filePath = resolvedSrc.replace(/^file:/, '')
    const fileNameFromPath = filePath.split('/').pop() || filePath
    const displayName = alt || title || fileNameFromPath
    const preview = resolvePreviewableFileLink({
      fileNameFromPath,
      title: title || '',
      visibleText: alt || '',
    })
    const previewKind = preview?.previewKind ?? 'image'
    if (filesDisabled) {
      // Unreachable via MarkdownRenderer today: sanitizeFilesDisabledPresentationText
      // (see the pre-parse step in MarkdownRenderer below) already converts
      // any ![alt](file:...) node to plain text before ReactMarkdown ever
      // builds this <img>, so a `file:` src can't reach this component
      // while filesDisabled is set. Kept as defense-in-depth -- if that
      // ever changes, falling through to InlineFilePreview below would
      // render an interactive preview despite files being disabled, which
      // is a much worse regression than a display-order nit. displayName
      // is alt-first, matching the rule this component applies everywhere
      // else (the title is a detection hint, not display text).
      return <span>{sanitizeFilesDisabledPresentationText(displayName)}</span>
    }

    return (
      <InlineFilePreview
        source={{
          fileId: resolveInlineFileId(filePath),
          filename: preview?.displayFilename ?? displayName,
          type: previewKind,
          mimeType: getInlineFilePreviewMimeType(previewKind),
        }}
        openLabel={openLabel}
        loadErrorText={loadErrorText}
        onFileClick={onFileClick}
        imageClassName="file-image cursor-pointer"
      />
    )
  }

  if (
    filesDisabled
    && (
      isManagedFileUrl(resolvedSrc)
      || sanitizeFilesDisabledPresentationText(resolvedSrc) !== resolvedSrc
    )
  ) {
    // Rarely (if ever) reached via MarkdownRenderer: the tree-level
    // pre-sanitizer (sanitizeFilesDisabledPresentationText) replaces any
    // image/link node whose url is isInertFileTarget -- which includes the
    // same isManagedFileUrl check this condition duplicates -- with its
    // alt-first plain text before ReactMarkdown ever builds this <img>
    // node. Every straightforward managed-URL shape is intercepted there
    // (no current test reaches this line), but the two checks decode/
    // normalize URLs slightly differently, so an encoding edge case
    // slipping past the tree level while matching here has been reported
    // in review and cannot be ruled out. Alt-first to match the rule this
    // component applies everywhere else: the title can carry a
    // backend-injected filename and must not replace the model's own alt
    // text as visible content.
    return <span>{presentationAlt || presentationTitle}</span>
  }

  return (
    <img
      src={resolvedSrc}
      alt={presentationAlt}
      // Title-first is correct here, unlike the filesDisabled span above:
      // this is the standard <img title> tooltip, where the markdown title
      // is the expected content and the alt text already rides in `alt`.
      title={presentationTitle || presentationAlt}
      {...props}
    />
  )
}

// Keep these component identities stable across chat/trace updates. Replacing
// them makes React remount every custom Markdown node, including a playing
// <audio> element whose playback state would then be lost.
const markdownComponents: Components = {
  p: MarkdownParagraph,
  a: MarkdownLink,
  img: MarkdownImage,
  table: MarkdownTable,
}

export function MarkdownRenderer({
  content,
  className = '',
  filesDisabled = false,
  agentCardsEnabled,
  onFileClick,
  onAgentClick,
}: MarkdownRendererProps) {
  const { t } = useI18n()
  const inheritedAgentCardsEnabled = React.useContext(AgentCardPresentationCapability)
  const resolvedAgentCardsEnabled = resolveAgentCardPresentationCapability(
    filesDisabled,
    agentCardsEnabled,
    inheritedAgentCardsEnabled,
  )
  const linksOpenInNewTab = React.useContext(LinksOpenInNewTabCapability)
  const contextValue = React.useMemo<MarkdownRendererContextValue>(
    () => ({
      filesDisabled,
      agentCardsEnabled: resolvedAgentCardsEnabled,
      linksOpenInNewTab,
      onFileClick,
      onAgentClick,
      openLabel: t('files.previewDialog.buttons.open'),
      loadErrorText: t('files.previewDialog.errors.loadFailed'),
    }),
    [filesDisabled, onFileClick, onAgentClick, resolvedAgentCardsEnabled, linksOpenInNewTab, t]
  )
  const displayContent = filesDisabled
    ? sanitizeFilesDisabledPresentationText(content)
    : content

  return (
    <MarkdownRendererContext.Provider value={contextValue}>
      <div className={`prose prose-invert max-w-none break-words [overflow-wrap:anywhere] ${className}`}>
        <ReactMarkdown
          remarkPlugins={[remarkGfm, remarkCurrencySafeMath, remarkPreserveTableContent]}
          rehypePlugins={[rehypeKatex]}
          components={markdownComponents}
          urlTransform={safeUrlTransform}
        >
          {displayContent}
        </ReactMarkdown>
      </div>
    </MarkdownRendererContext.Provider>
  )
}

interface JsonRendererProps {
  data: any
  className?: string
  filesDisabled?: boolean
  agentCardsEnabled?: boolean
  onFileClick?: (filePath: string, fileName: string) => void
  onAgentClick?: (agentId: string, agentName: string) => void
}

export function JsonRenderer({
  data,
  className = '',
  filesDisabled = false,
  agentCardsEnabled,
  onFileClick,
  onAgentClick,
}: JsonRendererProps) {
  const [expanded, setExpanded] = React.useState(true)

  if (typeof data === 'string') {
    // Try to parse as JSON first
    try {
      const parsed = JSON.parse(data)
      return (
        <JsonRenderer
          data={parsed}
          className={className}
          filesDisabled={filesDisabled}
          agentCardsEnabled={agentCardsEnabled}
          onFileClick={onFileClick}
          onAgentClick={onAgentClick}
        />
      )
    } catch {
      // If not JSON, try to identify Markdown more comprehensively
      const displayText = filesDisabled ? sanitizeFilesDisabledPresentationText(data) : data
      if (isLikelyMarkdown(displayText)) {
        return (
          <MarkdownRenderer
            content={displayText}
            className={className}
            filesDisabled={filesDisabled}
            agentCardsEnabled={agentCardsEnabled}
            onFileClick={onFileClick}
            onAgentClick={onAgentClick}
          />
        )
      }
      // Otherwise display as plain text
      return (
        <pre className={`py-3 rounded text-sm font-mono overflow-x-auto whitespace-pre-wrap ${className}`}>
          {displayText}
        </pre>
      )
    }
  }

  const displayData = filesDisabled ? projectFilesDisabledPresentation(data) : data

  if (typeof displayData === 'object' && displayData !== null) {
    // Check if it's a result object with output that might be markdown
    if (
      isRecord(data) &&
      typeof data.output === 'string' &&
      isLikelyMarkdown(data.output.trim()) &&
      isRecord(displayData) &&
      typeof displayData.output === 'string'
    ) {
      return (
        <div className={`space-y-3 ${className}`}>
          <div className="bg-muted p-3 rounded text-sm font-mono overflow-x-auto whitespace-pre-wrap">
            <div className="text-green-400 mb-2">✅ Task completed successfully</div>
            <div className="text-gray-400">Goal: {displayData.goal as React.ReactNode}</div>
          </div>
          <div className="border-t border-border pt-3">
            <div className="text-sm font-medium text-foreground mb-2">Result:</div>
            <MarkdownRenderer
              content={displayData.output}
              filesDisabled={filesDisabled}
              agentCardsEnabled={agentCardsEnabled}
              onFileClick={onFileClick}
              onAgentClick={onAgentClick}
            />
          </div>
        </div>
      )
    }

    // For other objects, display as formatted JSON
    return (
      <div className={`space-y-2 ${className}`}>
        <button
          onClick={() => setExpanded(!expanded)}
          className="text-xs text-blue-400 hover:text-blue-300 flex items-center gap-1"
        >
          {expanded ? '▼' : '▶'} JSON Data
        </button>
        {expanded && (
          <pre className="bg-muted p-3 rounded text-xs font-mono overflow-x-auto whitespace-pre-wrap">
            {JSON.stringify(displayData, null, 2)}
          </pre>
        )}
      </div>
    )
  }

  // For other types, display as string
  return (
    <pre className={`bg-muted py-3 rounded text-sm font-mono overflow-x-auto whitespace-pre-wrap ${className}`}>
      {String(data)}
    </pre>
  )
}