All files / src/components/settings/sections BrowserSettingsSection.tsx

0% Statements 0/290
0% Branches 0/1
0% Functions 0/1
0% Lines 0/290

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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { EmptyRequest, StringRequest } from "@shared/proto/cline/common"
import { VSCodeButton, VSCodeCheckbox, VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react"
import React, { useCallback, useEffect, useState } from "react"
import styled from "styled-components"
import { BROWSER_VIEWPORT_PRESETS } from "../../../../../src/shared/BrowserSettings"
import { useExtensionState } from "../../../context/ExtensionStateContext"
import { BrowserServiceClient } from "../../../services/grpc-client"
import CollapsibleContent from "../CollapsibleContent"
import { DebouncedTextField } from "../common/DebouncedTextField"
import Section from "../Section"
import { updateSetting } from "../utils/settingsHandlers"
 
interface BrowserSettingsSectionProps {
	renderSectionHeader: (tabId: string) => JSX.Element | null
}
 
const ConnectionStatusIndicator = ({
	isChecking,
	isConnected,
	remoteBrowserEnabled,
}: {
	isChecking: boolean
	isConnected: boolean | null
	remoteBrowserEnabled?: boolean
}) => {
	if (!remoteBrowserEnabled) {
		return null
	}
 
	return (
		<StatusContainer>
			{isChecking ? (
				<>
					<Spinner />
					<StatusText>Checking connection...</StatusText>
				</>
			) : isConnected === true ? (
				<>
					<CheckIcon className="codicon codicon-check" />
					<StatusText style={{ color: "var(--vscode-terminal-ansiGreen)" }}>Connected</StatusText>
				</>
			) : isConnected === false ? (
				<StatusText style={{ color: "var(--vscode-errorForeground)" }}>Not connected</StatusText>
			) : null}
		</StatusContainer>
	)
}
 
export const BrowserSettingsSection: React.FC<BrowserSettingsSectionProps> = ({ renderSectionHeader }) => {
	const { browserSettings } = useExtensionState()
	const [isCheckingConnection, setIsCheckingConnection] = useState(false)
	const [connectionStatus, setConnectionStatus] = useState<boolean | null>(null)
	const [relaunchResult, setRelaunchResult] = useState<{ success: boolean; message: string } | null>(null)
	const [debugMode, setDebugMode] = useState(false)
	const [isBundled, setIsBundled] = useState(false)
	const [detectedChromePath, setDetectedChromePath] = useState<string | null>(null)
 
	// Auto-clear relaunch result message after 15 seconds
	useEffect(() => {
		if (relaunchResult) {
			const timer = setTimeout(() => {
				setRelaunchResult(null)
			}, 15000)
			return () => clearTimeout(timer)
		}
	}, [relaunchResult])
 
	// Request detected Chrome path on mount
	useEffect(() => {
		BrowserServiceClient.getDetectedChromePath(EmptyRequest.create({}))
			.then((result) => {
				setDetectedChromePath(result.path)
				setIsBundled(result.isBundled)
			})
			.catch((error) => {
				console.error("Error getting detected Chrome path:", error)
			})
	}, [])
 
	// Function to check connection once without changing UI state immediately
	const checkConnectionOnce = useCallback(() => {
		if (browserSettings.remoteBrowserHost) {
			BrowserServiceClient.testBrowserConnection(StringRequest.create({ value: browserSettings.remoteBrowserHost }))
				.then((result) => {
					setConnectionStatus(result.success)
				})
				.catch((error) => {
					console.error("Error testing browser connection:", error)
					setConnectionStatus(false)
				})
		} else {
			BrowserServiceClient.discoverBrowser(EmptyRequest.create({}))
				.then((result) => {
					setConnectionStatus(result.success)
				})
				.catch((error) => {
					console.error("Error discovering browser:", error)
					setConnectionStatus(false)
				})
		}
	}, [browserSettings.remoteBrowserHost])
 
	// Setup continuous polling for connection status when remote browser is enabled
	useEffect(() => {
		if (!browserSettings.remoteBrowserEnabled) {
			setIsCheckingConnection(false)
			return
		}
 
		checkConnectionOnce()
		const pollInterval = setInterval(() => {
			checkConnectionOnce()
		}, 1000)
 
		return () => clearInterval(pollInterval)
	}, [browserSettings.remoteBrowserEnabled, checkConnectionOnce])
 
	const handleViewportChange = (event: Event) => {
		const target = event.target as HTMLSelectElement
		const selectedSize = BROWSER_VIEWPORT_PRESETS[target.value as keyof typeof BROWSER_VIEWPORT_PRESETS]
		if (selectedSize) {
			updateSetting("browserSettings", {
				viewport: {
					width: selectedSize.width,
					height: selectedSize.height,
				},
			})
		}
	}
 
	const relaunchChromeDebugMode = () => {
		setDebugMode(true)
		setRelaunchResult(null)
 
		BrowserServiceClient.relaunchChromeDebugMode(EmptyRequest.create({}))
			.then((result) => {
				setRelaunchResult({
					success: true,
					message: result.value,
				})
				setDebugMode(false)
			})
			.catch((error) => {
				console.error("Error relaunching Chrome:", error)
				setRelaunchResult({
					success: false,
					message: `Error relaunching Chrome: ${error.message}`,
				})
				setDebugMode(false)
			})
	}
 
	// Determine if we should show the relaunch button
	const isRemoteEnabled = Boolean(browserSettings.remoteBrowserEnabled)
	const shouldShowRelaunchButton = isRemoteEnabled && connectionStatus === false
	const isSubSettingsOpen = !(browserSettings.disableToolUse || false)
 
	return (
		<div>
			{renderSectionHeader("browser")}
			<Section>
				<div id="browser-settings-section" style={{ marginBottom: 20 }}>
					{/* Master Toggle */}
					<div style={{ marginBottom: isSubSettingsOpen ? 0 : 10 }}>
						<VSCodeCheckbox
							checked={browserSettings.disableToolUse || false}
							onChange={(e) =>
								updateSetting("browserSettings", { disableToolUse: (e.target as HTMLInputElement).checked })
							}>
							Disable browser tool usage
						</VSCodeCheckbox>
						<p
							style={{
								fontSize: "12px",
								color: "var(--vscode-descriptionForeground)",
								margin: "4px 0 0 0px",
							}}>
							Prevent AI-Hydro from using browser actions (e.g. launch, click, type).
						</p>
					</div>
 
					<CollapsibleContent isOpen={isSubSettingsOpen}>
						<div style={{ marginBottom: 15 }}>
							<div style={{ marginBottom: 8 }}>
								<label style={{ fontWeight: "500", display: "block", marginBottom: 5 }}>Viewport size</label>
								<VSCodeDropdown
									onChange={(event) => handleViewportChange(event as Event)}
									style={{ width: "100%" }}
									value={
										Object.entries(BROWSER_VIEWPORT_PRESETS).find(([_, size]) => {
											const typedSize = size as { width: number; height: number }
											return (
												typedSize.width === browserSettings.viewport.width &&
												typedSize.height === browserSettings.viewport.height
											)
										})?.[0]
									}>
									{Object.entries(BROWSER_VIEWPORT_PRESETS).map(([name]) => (
										<VSCodeOption key={name} value={name}>
											{name}
										</VSCodeOption>
									))}
								</VSCodeDropdown>
							</div>
							<p
								style={{
									fontSize: "12px",
									color: "var(--vscode-descriptionForeground)",
									margin: 0,
								}}>
								Set the size of the browser viewport for screenshots and interactions.
							</p>
						</div>
 
						<div style={{ marginBottom: 0 }}>
							{" "}
							{/* This div now contains Remote Connection & Chrome Path */}
							<div
								style={{
									marginBottom: 4,
									display: "flex",
									alignItems: "center",
									justifyContent: "space-between",
								}}>
								<VSCodeCheckbox
									checked={browserSettings.remoteBrowserEnabled}
									onChange={(e) => {
										const enabled = (e.target as HTMLInputElement).checked
										updateSetting("browserSettings", { remoteBrowserEnabled: enabled })
										// If disabling, also clear the host
										if (!enabled) {
											updateSetting("browserSettings", { remoteBrowserHost: undefined })
										}
									}}>
									Use remote browser connection
								</VSCodeCheckbox>
								<ConnectionStatusIndicator
									isChecking={isCheckingConnection}
									isConnected={connectionStatus}
									remoteBrowserEnabled={browserSettings.remoteBrowserEnabled}
								/>
							</div>
							<p
								style={{
									fontSize: "12px",
									color: "var(--vscode-descriptionForeground)",
									margin: "0 0 6px 0px",
								}}>
								Enable AI-Hydro to use your Chrome
								{isBundled
									? "(not detected on your machine)"
									: detectedChromePath
										? ` (${detectedChromePath})`
										: ""}
								. You can specify a custom path below. Using a remote browser connection requires starting Chrome
								in debug mode
								{browserSettings.remoteBrowserEnabled ? (
									<>
										{" "}
										manually (<code>--remote-debugging-port=9222</code>) or using the button below. Enter the
										host address or leave it blank for automatic discovery.
									</>
								) : (
									"."
								)}
							</p>
							{/* Moved remote-specific settings to appear directly after enabling remote connection */}
							{browserSettings.remoteBrowserEnabled && (
								<div style={{ marginLeft: 0, marginTop: 8 }}>
									<DebouncedTextField
										initialValue={browserSettings.remoteBrowserHost || ""}
										onChange={(value) =>
											updateSetting("browserSettings", { remoteBrowserHost: value || undefined })
										}
										placeholder="http://localhost:9222"
										style={{ width: "100%", marginBottom: 8 }}
									/>
 
									{shouldShowRelaunchButton && (
										<div style={{ display: "flex", gap: "10px", marginBottom: 8, justifyContent: "center" }}>
											<VSCodeButton
												disabled={debugMode}
												onClick={relaunchChromeDebugMode}
												style={{ flex: 1 }}>
												{debugMode ? "Launching Browser..." : "Launch Browser with Debug Mode"}
											</VSCodeButton>
										</div>
									)}
 
									{relaunchResult && (
										<div
											style={{
												padding: "8px",
												marginBottom: "8px",
												backgroundColor: relaunchResult.success
													? "rgba(0, 128, 0, 0.1)"
													: "rgba(255, 0, 0, 0.1)",
												color: relaunchResult.success
													? "var(--vscode-terminal-ansiGreen)"
													: "var(--vscode-terminal-ansiRed)",
												borderRadius: "3px",
												fontSize: "11px",
												whiteSpace: "pre-wrap",
												wordBreak: "break-word",
											}}>
											{relaunchResult.message}
										</div>
									)}
 
									<p
										style={{
											fontSize: "12px",
											color: "var(--vscode-descriptionForeground)",
											margin: 0,
										}}></p>
								</div>
							)}
							{/* Chrome Executable Path section now follows remote-specific settings */}
							<div style={{ marginBottom: 8, marginTop: 8 }}>
								<label
									htmlFor="chrome-executable-path"
									style={{ fontWeight: "500", display: "block", marginBottom: 5 }}>
									Chrome Executable Path (Optional)
								</label>
								<DebouncedTextField
									id="chrome-executable-path"
									initialValue={browserSettings.chromeExecutablePath || ""}
									onChange={(value) => updateSetting("browserSettings", { chromeExecutablePath: value })}
									placeholder="e.g., /usr/bin/google-chrome or C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
									style={{ width: "100%" }}
								/>
								<p
									style={{
										fontSize: "12px",
										color: "var(--vscode-descriptionForeground)",
										margin: "4px 0 0 0",
									}}>
									Leave blank to auto-detect.
								</p>
							</div>
							{/* Custom Browser Arguments section */}
							<div style={{ marginBottom: 8, marginTop: 8 }}>
								<label
									htmlFor="custom-browser-args"
									style={{ fontWeight: "500", display: "block", marginBottom: 5 }}>
									Custom Browser Arguments (Optional)
								</label>
								<DebouncedTextField
									id="custom-browser-args"
									initialValue={browserSettings.customArgs || ""}
									onChange={(value) => updateSetting("browserSettings", { customArgs: value })}
									placeholder="e.g., --no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu --no-first-run --no-zygote"
									style={{ width: "100%" }}
								/>
								<p
									style={{
										fontSize: "12px",
										color: "var(--vscode-descriptionForeground)",
										margin: "4px 0 0 0",
									}}>
									Space-separated arguments to pass to the browser executable.
								</p>
							</div>
						</div>
					</CollapsibleContent>
				</div>
			</Section>
		</div>
	)
}
 
const StatusContainer = styled.div`
	display: flex;
	align-items: center;
	margin-left: 12px;
	height: 20px;
`
 
const StatusText = styled.span`
	font-size: 12px;
	margin-left: 4px;
`
 
const CheckIcon = styled.i`
	color: var(--vscode-terminal-ansiGreen);
	font-size: 14px;
`
 
const Spinner = styled.div`
	width: 14px;
	height: 14px;
	border: 2px solid rgba(255, 255, 255, 0.3);
	border-radius: 50%;
	border-top-color: var(--vscode-progressBar-background);
	animation: spin 1s ease-in-out infinite;
 
	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}
`
 
export default BrowserSettingsSection