import { FormEvent, HTMLAttributes, useEffect } from "react" import React from "react" import { useAppTranslation } from "@/i18n/TranslationContext" import { VSCodeCheckbox, VSCodeTextArea } from "@vscode/webview-ui-toolkit/react" import { ListChevronsDownUp } from "lucide-react" import { DEFAULT_DIFF_FUZZY_THRESHOLD } from "@roo-code/types" import { supportPrompt } from "@roo/support-prompt" import { cn } from "@/lib/utils" import { Input, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Slider, Button, StandardTooltip, } from "@/components/ui" import { SetCachedStateField } from "./types" import { SectionHeader } from "./SectionHeader" import { Section } from "./Section" import { SearchableSetting } from "./SearchableSetting" import { useSearchIndexContext } from "./useSettingsSearch" type ContextManagementSettingsProps = HTMLAttributes & { autoCondenseContext: boolean autoCondenseContextPercent: number idleCondenseContext: boolean idleCondenseContextPercent: number idleCondenseTimeInSeconds: number listApiConfigMeta: any[] maxOpenTabsContext: number maxWorkspaceFiles: number showRooIgnoredFiles?: boolean enableSubfolderRules?: boolean maxImageFileSize?: number maxTotalImageSize?: number profileThresholds?: Record profileIdleThresholds?: Record profileIdleCondenseTimes?: Record includeDiagnosticMessages?: boolean maxDiagnosticMessages?: number writeDelayMs: number diffFuzzyThreshold?: number includeCurrentTime?: boolean includeCurrentCost?: boolean maxGitStatusFiles?: number customSupportPrompts: Record setCustomSupportPrompts: (prompts: Record) => void setCachedStateField: SetCachedStateField< | "autoCondenseContext" | "autoCondenseContextPercent" | "idleCondenseContext" | "idleCondenseContextPercent" | "idleCondenseTimeInSeconds" | "profileIdleThresholds" | "profileIdleCondenseTimes" | "maxOpenTabsContext" | "maxWorkspaceFiles" | "showRooIgnoredFiles" | "enableSubfolderRules" | "maxImageFileSize" | "maxTotalImageSize" | "profileThresholds" | "includeDiagnosticMessages" | "maxDiagnosticMessages" | "writeDelayMs" | "diffFuzzyThreshold" | "includeCurrentTime" | "includeCurrentCost" | "maxGitStatusFiles" > } // The toolkit checkbox delivers change events retargeted to its custom-element host, which mirrors // `checked` without being an HTMLInputElement; a directly rendered input is one. Match on the // property so both target shapes update the setting, and decline targets that carry no boolean // `checked` rather than writing `undefined` through the guard. const isCheckboxTarget = (target: EventTarget | null): target is EventTarget & { checked: boolean } => target !== null && "checked" in target && typeof target.checked === "boolean" export const ContextManagementSettings = ({ autoCondenseContext, autoCondenseContextPercent, idleCondenseContext, idleCondenseContextPercent, idleCondenseTimeInSeconds, listApiConfigMeta, maxOpenTabsContext, maxWorkspaceFiles, showRooIgnoredFiles, enableSubfolderRules, setCachedStateField, maxImageFileSize, maxTotalImageSize, profileThresholds = {}, profileIdleThresholds = {}, profileIdleCondenseTimes = {}, includeDiagnosticMessages, maxDiagnosticMessages, writeDelayMs, diffFuzzyThreshold, includeCurrentTime, includeCurrentCost, maxGitStatusFiles, customSupportPrompts, setCustomSupportPrompts, className, ...props }: ContextManagementSettingsProps) => { const { t } = useAppTranslation() const [selectedThresholdProfile, setSelectedThresholdProfile] = React.useState("default") const [selectedIdleProfile, setSelectedIdleProfile] = React.useState("default") const idleTimeLabel = t("settings:contextManagement.idleCondensing.idleTime.label") // Settings search indexes each tab once during an initial cycling phase, // before the user has a chance to enable idle condensing. The idle time // control only renders when idle condensing is enabled, so registering it // only through the rendered SearchableSetting would leave "Idle time" // unsearchable whenever the feature starts out disabled. Register the // label unconditionally here (like SearchableSetting, we never unregister) // so the result is always in the index; the rendered control below still // carries the matching data-setting-id for navigation when it is visible. const searchContext = useSearchIndexContext() useEffect(() => { if (searchContext) { searchContext.registerSetting({ settingId: "context-idle-time", section: "contextManagement", label: idleTimeLabel, }) } }, [searchContext, idleTimeLabel]) // Helper function to get the CONDENSE prompt value const getCondensePromptValue = (): string => { return supportPrompt.get(customSupportPrompts, "CONDENSE") } // Helper function to update the CONDENSE prompt const updateCondensePrompt = (value: string | undefined) => { const updatedPrompts = { ...customSupportPrompts } if (value === undefined) { delete updatedPrompts["CONDENSE"] } else { updatedPrompts["CONDENSE"] = value } setCustomSupportPrompts(updatedPrompts) } // Helper function to reset the CONDENSE prompt to default const handleCondenseReset = () => { const updatedPrompts = { ...customSupportPrompts } delete updatedPrompts["CONDENSE"] setCustomSupportPrompts(updatedPrompts) } // Mirrors computeEffectiveCondenseThreshold in src/core/context-management // (and the MIN/MAX_CONDENSE_THRESHOLD constants in src/core/condense, which // the webview cannot import): -1/undefined inherit the global value, a value // inside [5, 100] overrides it, and anything else (e.g. an invalid imported // override) falls back to the global value, exactly as the runtime does. const MIN_CONDENSE_THRESHOLD = 5 const MAX_CONDENSE_THRESHOLD = 100 const resolveCondensePercent = (globalPercent: number, profileValue: number | undefined): number => { if (profileValue === undefined || profileValue === -1) { return globalPercent } if (profileValue >= MIN_CONDENSE_THRESHOLD && profileValue <= MAX_CONDENSE_THRESHOLD) { return profileValue } return globalPercent } // Helper function to get the current threshold value based on selected profile const getCurrentThresholdValue = () => { if (selectedThresholdProfile === "default") { return autoCondenseContextPercent } return resolveCondensePercent(autoCondenseContextPercent, profileThresholds[selectedThresholdProfile]) } // Lowering the condensing trigger threshold lowers the current idle thresholds // that inherit from it, so the idle threshold never exceeds the trigger // threshold. The idle slider's max stays at 100%. const clampIdleToTrigger = (newValue: number) => { if (idleCondenseContextPercent > newValue) { setCachedStateField("idleCondenseContextPercent", newValue) } const clampedProfileIdleThresholds = { ...profileIdleThresholds } let changed = false for (const [id, idleValue] of Object.entries(profileIdleThresholds)) { if (idleValue === -1) { continue } const profileTrigger = profileThresholds[id] // Only profile idle overrides that inherit the default trigger threshold follow this change. if (profileTrigger !== undefined && profileTrigger !== -1) { continue } if (idleValue > newValue) { clampedProfileIdleThresholds[id] = newValue changed = true } } if (changed) { setCachedStateField("profileIdleThresholds", clampedProfileIdleThresholds) } } // Helper function to handle threshold changes const handleThresholdChange = (value: number) => { if (selectedThresholdProfile === "default") { setCachedStateField("autoCondenseContextPercent", value) clampIdleToTrigger(value) } else { const newThresholds = { ...profileThresholds, [selectedThresholdProfile]: value, } setCachedStateField("profileThresholds", newThresholds) const profileIdle = profileIdleThresholds[selectedThresholdProfile] if (profileIdle !== undefined && profileIdle !== -1 && profileIdle > value) { setCachedStateField("profileIdleThresholds", { ...profileIdleThresholds, [selectedThresholdProfile]: value, }) } } } // Effective main condense threshold for the profile currently selected in // the idle-threshold UI: the idle threshold value may never exceed it, // though the slider's max stays at 100%. Invalid profile overrides resolve // to the global threshold, matching the runtime fallback. const getMainThresholdForIdleProfile = () => { if (selectedIdleProfile === "default") { return autoCondenseContextPercent } return resolveCondensePercent(autoCondenseContextPercent, profileThresholds[selectedIdleProfile]) } // Helper function to get the current idle threshold value based on selected profile. // The displayed value is capped at the profile's effective main threshold to match // the runtime behavior (Task.ts resolves idlePercent = Math.min(idlePercentSetting, // mainPercent)); the inherited setting itself is left unchanged. Invalid profile // overrides display the global idle threshold they fall back to at runtime. const getCurrentIdleThresholdValue = () => { if (selectedIdleProfile === "default") { return Math.min(idleCondenseContextPercent, getMainThresholdForIdleProfile()) } return Math.min( resolveCondensePercent(idleCondenseContextPercent, profileIdleThresholds[selectedIdleProfile]), getMainThresholdForIdleProfile(), ) } // Helper function to handle idle threshold changes (value clamped to the main threshold) const handleIdleThresholdChange = (value: number) => { const clamped = Math.min(value, getMainThresholdForIdleProfile()) if (selectedIdleProfile === "default") { setCachedStateField("idleCondenseContextPercent", clamped) } else { setCachedStateField("profileIdleThresholds", { ...profileIdleThresholds, [selectedIdleProfile]: clamped, }) } } // Helper function to get the current idle time value based on selected profile. // Mirrors resolveIdleCondenseTimeInSeconds in Task.ts: only -1/undefined inherit // and values >= 0 override; anything else falls back to the global value. const getCurrentIdleTimeValue = () => { if (selectedIdleProfile === "default") { return idleCondenseTimeInSeconds } const profileSeconds = profileIdleCondenseTimes[selectedIdleProfile] if (profileSeconds === undefined || profileSeconds === -1) { return idleCondenseTimeInSeconds } if (profileSeconds >= 0) { return profileSeconds } return idleCondenseTimeInSeconds } // Helper function to handle idle time changes const handleIdleTimeChange = (value: number) => { const clamped = Math.max(0, Math.round(value || 0)) if (selectedIdleProfile === "default") { setCachedStateField("idleCondenseTimeInSeconds", clamped) } else { setCachedStateField("profileIdleCondenseTimes", { ...profileIdleCondenseTimes, [selectedIdleProfile]: clamped, }) } } // Reset the selected profile's idle overrides back to inheriting the global values. const handleIdleProfileUseGlobal = () => { if (selectedIdleProfile === "default") { return } setCachedStateField("profileIdleThresholds", { ...profileIdleThresholds, [selectedIdleProfile]: -1 }) setCachedStateField("profileIdleCondenseTimes", { ...profileIdleCondenseTimes, [selectedIdleProfile]: -1 }) } return (
{t("settings:sections.contextManagement")}
{t("settings:contextManagement.openTabs.label")}
setCachedStateField("maxOpenTabsContext", value)} data-testid="open-tabs-limit-slider" /> {maxOpenTabsContext ?? 20}
{t("settings:contextManagement.openTabs.description")}
{t("settings:contextManagement.workspaceFiles.label")}
setCachedStateField("maxWorkspaceFiles", value)} data-testid="workspace-files-limit-slider" /> {maxWorkspaceFiles ?? 200}
{t("settings:contextManagement.workspaceFiles.description")}
{t("settings:contextManagement.maxGitStatusFiles.label")}
setCachedStateField("maxGitStatusFiles", value)} data-testid="max-git-status-files-slider" /> {maxGitStatusFiles ?? 0}
{t("settings:contextManagement.maxGitStatusFiles.description")}
setCachedStateField("showRooIgnoredFiles", e.target.checked)} data-testid="show-rooignored-files-checkbox">
{t("settings:contextManagement.rooignore.description")}
setCachedStateField("enableSubfolderRules", e.target.checked)} data-testid="enable-subfolder-rules-checkbox">
{t("settings:contextManagement.enableSubfolderRules.description")}
{t("settings:contextManagement.maxImageFileSize.label")}
{ const newValue = parseInt(e.target.value, 10) if (!isNaN(newValue) && newValue >= 1 && newValue <= 100) { setCachedStateField("maxImageFileSize", newValue) } }} onClick={(e) => e.currentTarget.select()} data-testid="max-image-file-size-input" /> {t("settings:contextManagement.maxImageFileSize.mb")}
{t("settings:contextManagement.maxImageFileSize.description")}
{t("settings:contextManagement.maxTotalImageSize.label")}
{ const newValue = parseInt(e.target.value, 10) if (!isNaN(newValue) && newValue >= 1 && newValue <= 500) { setCachedStateField("maxTotalImageSize", newValue) } }} onClick={(e) => e.currentTarget.select()} data-testid="max-total-image-size-input" /> {t("settings:contextManagement.maxTotalImageSize.mb")}
{t("settings:contextManagement.maxTotalImageSize.description")}
setCachedStateField("includeDiagnosticMessages", e.target.checked)} data-testid="include-diagnostic-messages-checkbox">
{t("settings:contextManagement.diagnostics.includeMessages.description")}
{t("settings:contextManagement.diagnostics.maxMessages.label")}
{ // When slider reaches 100, set to -1 (unlimited) setCachedStateField("maxDiagnosticMessages", value === 100 ? -1 : value) }} data-testid="max-diagnostic-messages-slider" aria-label={t("settings:contextManagement.diagnostics.maxMessages.label")} aria-valuemin={1} aria-valuemax={100} aria-valuenow={ maxDiagnosticMessages !== undefined && maxDiagnosticMessages <= 0 ? 100 : (maxDiagnosticMessages ?? 50) } aria-valuetext={ (maxDiagnosticMessages !== undefined && maxDiagnosticMessages <= 0) || maxDiagnosticMessages === 100 ? t("settings:contextManagement.diagnostics.maxMessages.unlimitedLabel") : `${maxDiagnosticMessages ?? 50} ${t("settings:contextManagement.diagnostics.maxMessages.label")}` } /> {(maxDiagnosticMessages !== undefined && maxDiagnosticMessages <= 0) || maxDiagnosticMessages === 100 ? t("settings:contextManagement.diagnostics.maxMessages.unlimitedLabel") : (maxDiagnosticMessages ?? 50)}
{t("settings:contextManagement.diagnostics.maxMessages.description")}
{t("settings:contextManagement.diagnostics.delayAfterWrite.label")}
setCachedStateField("writeDelayMs", value)} data-testid="write-delay-slider" /> {t("settings:common.milliseconds", { value: writeDelayMs })}
{t("settings:contextManagement.diagnostics.delayAfterWrite.description")}
{t("settings:contextManagement.fileEdits.diffFuzzyThreshold.label")}
setCachedStateField("diffFuzzyThreshold", value)} data-testid="diff-fuzzy-threshold-slider" /> {((diffFuzzyThreshold ?? DEFAULT_DIFF_FUZZY_THRESHOLD) * 100).toFixed(0)}%
{t("settings:contextManagement.fileEdits.diffFuzzyThreshold.description")}
setCachedStateField("includeCurrentTime", e.target.checked)} data-testid="include-current-time-checkbox">
{t("settings:contextManagement.includeCurrentTime.description")}
setCachedStateField("includeCurrentCost", e.target.checked)} data-testid="include-current-cost-checkbox">
{t("settings:contextManagement.includeCurrentCost.description")}
{/* Context Condensing Prompt Editor */}
{t("prompts:supportPrompts.types.CONDENSE.description")}
{ const value = (e as unknown as CustomEvent)?.detail?.target?.value ?? ((e as any).target as HTMLTextAreaElement).value updateCondensePrompt(value) }} rows={6} className="w-full" data-testid="condense-prompt-textarea" />
{/* Auto Condense Context */} setCachedStateField("autoCondenseContext", e.target.checked)} data-testid="auto-condense-context-checkbox"> {t("settings:contextManagement.autoCondenseContext.name")} {autoCondenseContext && (
{t("settings:contextManagement.condensingThreshold.label")}
{/* Threshold Slider */}
handleThresholdChange(value)} data-testid="condense-threshold-slider" /> {getCurrentThresholdValue()}%
{selectedThresholdProfile === "default" ? t("settings:contextManagement.condensingThreshold.defaultDescription", { threshold: autoCondenseContextPercent, }) : t("settings:contextManagement.condensingThreshold.profileDescription")}
{/* Idle Condensing */} ) => { if (!isCheckboxTarget(e.target)) { return } setCachedStateField("idleCondenseContext", e.target.checked) }} data-testid="idle-condense-context-checkbox"> {t("settings:contextManagement.idleCondensing.name")}
{t("settings:contextManagement.idleCondensing.description")}
{idleCondenseContext && (
{/* Idle Threshold Slider */}
handleIdleThresholdChange(value)} data-testid="idle-condense-threshold-slider" aria-label={t("settings:contextManagement.idleCondensing.name")} /> {getCurrentIdleThresholdValue()}%
{selectedIdleProfile === "default" ? t("settings:contextManagement.idleCondensing.thresholdDescription") : t( "settings:contextManagement.idleCondensing.thresholdProfileDescription", )}
{/* Idle Time Input */}
{idleTimeLabel} // Number (not parseInt) so a pasted value like "1e3" // is read as 1000 instead of stopping at "1". handleIdleTimeChange(Number((e.target as HTMLInputElement).value)) } className="w-24" data-testid="idle-condense-time-input" /> {t("settings:contextManagement.idleCondensing.idleTime.seconds")}
{t("settings:contextManagement.idleCondensing.idleTime.description")}
{selectedIdleProfile !== "default" && (
)}
)}
)}
) }