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 (
{
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 && (
{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")}