All files / src/components/mcp/chat-display McpResponseDisplay.tsx

15.97% Statements 27/169
100% Branches 0/0
0% Functions 0/2
15.97% Lines 27/169

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273  1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x                                             1x   1x       1x                         1x   1x 1x           1x           1x                                                                                                                                                                                                                                                                                                                                                                                     1x 1x               1x  
import { McpDisplayMode } from "@shared/McpDisplayMode"
import { VSCodeProgressRing } from "@vscode/webview-ui-toolkit/react"
import React, { useCallback, useEffect, useState } from "react"
import styled from "styled-components"
import ChatErrorBoundary from "@/components/chat/ChatErrorBoundary"
import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock"
import MarkdownBlock from "@/components/common/MarkdownBlock"
import { DropdownContainer } from "@/components/settings/ApiOptions"
import { updateSetting } from "@/components/settings/utils/settingsHandlers"
import { useExtensionState } from "../../../context/ExtensionStateContext"
import ImagePreview from "./ImagePreview"
import LinkPreview from "./LinkPreview"
import McpDisplayModeDropdown from "./McpDisplayModeDropdown"
import { buildDisplaySegments, DisplaySegment, processResponseUrls, UrlMatch } from "./utils/mcpRichUtil"
 
// Maximum number of URLs to process in total, per response
export const MAX_URLS = 50
 
const ResponseHeader = styled.div`
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 9px 10px;
	color: var(--vscode-descriptionForeground);
	cursor: pointer;
	user-select: none;
	border-bottom: 1px dashed var(--vscode-editorGroup-border);
	margin-bottom: 8px;
 
	.header-title {
		display: flex;
		align-items: center;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		margin-right: 8px;
	}
 
	.header-icon {
		margin-right: 6px;
	}
`
 
const ResponseContainer = styled.div`
	position: relative;
	font-family: var(--vscode-editor-font-family, monospace);
	font-size: var(--vscode-editor-font-size, 12px);
	background-color: ${CODE_BLOCK_BG_COLOR};
	color: var(--vscode-editor-foreground, #d4d4d4);
	border-radius: 3px;
	border: 1px solid var(--vscode-editorGroup-border);
	overflow: hidden;
	z-index: 0;
 
	.response-content {
		overflow-x: auto;
		overflow-y: hidden;
		max-width: 100%;
		padding: 10px;
	}
`
 
// Style for URL text to ensure proper wrapping
const UrlText = styled.div`
	white-space: pre-wrap;
	word-break: break-all;
	overflow-wrap: break-word;
	font-family: var(--vscode-editor-font-family, monospace);
	font-size: var(--vscode-editor-font-size, 12px);
`
 
interface McpResponseDisplayProps {
	responseText: string
}
 
const McpResponseDisplay: React.FC<McpResponseDisplayProps> = ({ responseText }) => {
	const { mcpResponsesCollapsed, mcpDisplayMode } = useExtensionState() // Get setting from context
	const [isExpanded, setIsExpanded] = useState(!mcpResponsesCollapsed) // Initialize with context setting
	const [isLoading, setIsLoading] = useState(false) // Initial loading state for rich content
 
	const [urlMatches, setUrlMatches] = useState<UrlMatch[]>([])
	const [error, setError] = useState<string | null>(null)
 
	const handleDisplayModeChange = useCallback((newMode: McpDisplayMode) => {
		updateSetting("mcpDisplayMode", newMode)
	}, [])
 
	const toggleExpand = useCallback(() => {
		setIsExpanded((prev) => !prev)
	}, [])
 
	// Effect to update isExpanded if mcpResponsesCollapsed changes from context
	useEffect(() => {
		setIsExpanded(!mcpResponsesCollapsed)
	}, [mcpResponsesCollapsed])
 
	// Find all URLs in the text and determine if they're images
	useEffect(() => {
		// Skip all processing if in plain mode or markdown mode
		if (!isExpanded || mcpDisplayMode === "plain" || mcpDisplayMode === "markdown") {
			setIsLoading(false)
			if (urlMatches.length > 0) {
				setUrlMatches([]) // Clear any existing matches when not in rich mode
			}
			return
		}
 
		console.log("Processing MCP response for URL extraction")
		setIsLoading(true)
		setError(null)
 
		// Use the orchestrator function from mcpRichUtil
		const cleanup = processResponseUrls(
			responseText || "",
			MAX_URLS,
			(matches) => {
				setUrlMatches(matches)
				setIsLoading(false)
			},
			(updatedMatches) => {
				setUrlMatches(updatedMatches)
			},
			(errorMessage) => {
				setError(errorMessage)
				setIsLoading(false)
			},
		)
 
		return cleanup
	}, [responseText, mcpDisplayMode, isExpanded])
 
	// Helper function to render a display segment
	const renderSegment = (segment: DisplaySegment): JSX.Element => {
		switch (segment.type) {
			case "text":
			case "url":
				return <UrlText key={segment.key}>{segment.content}</UrlText>
 
			case "image":
				return (
					<div key={segment.key}>
						<ImagePreview url={segment.url!} />
					</div>
				)
 
			case "link":
				return (
					<div key={segment.key} style={{ margin: "10px 0" }}>
						<LinkPreview url={segment.url!} />
					</div>
				)
 
			case "error":
				return (
					<div
						key={segment.key}
						style={{
							margin: "10px 0",
							padding: "8px",
							color: "var(--vscode-errorForeground)",
							border: "1px solid var(--vscode-editorError-foreground)",
							borderRadius: "4px",
							height: "128px",
							overflow: "auto",
						}}>
						{segment.content}
					</div>
				)
 
			default:
				return <React.Fragment key={segment.key} />
		}
	}
 
	// Function to render content based on display mode
	const renderContent = () => {
		if (!isExpanded) {
			return null
		}
 
		if (isLoading && mcpDisplayMode === "rich") {
			return (
				<div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "50px" }}>
					<VSCodeProgressRing />
				</div>
			)
		}
 
		if (mcpDisplayMode === "plain") {
			return <UrlText>{responseText}</UrlText>
		}
 
		if (mcpDisplayMode === "markdown") {
			return <MarkdownBlock markdown={responseText} />
		}
 
		if (error) {
			return (
				<>
					<div style={{ color: "var(--vscode-errorForeground)", marginBottom: "10px" }}>{error}</div>
					<UrlText>{responseText}</UrlText>
				</>
			)
		}
 
		if (mcpDisplayMode === "rich") {
			const segments = buildDisplaySegments(responseText, urlMatches)
			return <>{segments.map(renderSegment)}</>
		}
 
		return null
	}
 
	try {
		return (
			<ResponseContainer>
				<ResponseHeader
					onClick={toggleExpand}
					style={{
						borderBottom: isExpanded ? "1px dashed var(--vscode-editorGroup-border)" : "none",
						marginBottom: isExpanded ? "8px" : "0px",
					}}>
					<div className="header-title">
						<span className={`codicon codicon-chevron-${isExpanded ? "down" : "right"} header-icon`}></span>
						Response
					</div>
					<DropdownContainer
						style={{ minWidth: isExpanded ? "auto" : "0", visibility: isExpanded ? "visible" : "hidden" }}>
						<McpDisplayModeDropdown
							onChange={handleDisplayModeChange}
							onClick={(e) => e.stopPropagation()}
							style={{ minWidth: "120px" }}
							value={mcpDisplayMode}
						/>
					</DropdownContainer>
				</ResponseHeader>
 
				{isExpanded && <div className="response-content">{renderContent()}</div>}
			</ResponseContainer>
		)
	} catch (_error) {
		console.log("Error rendering MCP response - falling back to plain text") // Restored comment
		// Fallback for critical rendering errors
		return (
			<ResponseContainer>
				<ResponseHeader onClick={toggleExpand}>
					<div className="header-title">
						<span className={`codicon codicon-chevron-${isExpanded ? "down" : "right"} header-icon`}></span>
						Response (Error)
					</div>
				</ResponseHeader>
				{isExpanded && (
					<div className="response-content">
						<div style={{ color: "var(--vscode-errorForeground)" }}>Error parsing response:</div>
						<UrlText>{responseText}</UrlText>
					</div>
				)}
			</ResponseContainer>
		)
	}
}
 
// Wrap the entire McpResponseDisplay component with an error boundary
const McpResponseDisplayWithErrorBoundary: React.FC<McpResponseDisplayProps> = (props) => {
	return (
		<ChatErrorBoundary>
			<McpResponseDisplay {...props} />
		</ChatErrorBoundary>
	)
}
 
export default McpResponseDisplayWithErrorBoundary