import { useParams } from 'common' import { AlertTriangleIcon, BookOpenIcon, ChartLineIcon, ChevronDownIcon, SparklesIcon, WrenchIcon, } from 'lucide-react' import { Alert, AlertDescription, AlertTitle, Button, cn, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from 'ui' import { DISK_SPACE_EXHAUSTION_DESCRIPTION, isResourceWarningMessageKey, RESOURCE_WARNING_MESSAGES, type ResourceWarningMessageKey, } from './ResourceExhaustionWarningBanner.constants' import { applyResourceList, getResourceWarningAiPrompt, getResourceWarningCorrectionUrl, getTroubleshootItems, getWarningContent, isComputeUpgradeWarning, type TroubleshootItem, } from './ResourceExhaustionWarningBanner.utils' import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider' import { DynamicLink } from '@/components/ui/DynamicLink' import { useResourceWarningsQuery } from '@/data/usage/resource-warnings-query' import { useProjectDiskLimits } from '@/hooks/misc/useProjectDiskLimits' import { useRoutePattern } from '@/hooks/misc/useRoutePattern' import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization' import { useShowDiskIOBurstBalanceChart } from '@/hooks/misc/useShowDiskIOBurstBalanceChart' import { useTrack } from '@/lib/telemetry/track' import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state' import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state' type LinkedTroubleshootItem = Extract type ConfiguredResourceWarning = Exclude const isConfiguredResourceWarning = (property: string): property is ConfiguredResourceWarning => isResourceWarningMessageKey(property) && property !== 'multiple_resource_warnings' const MULTIPLE_RESOURCE_WARNING_NO_AI_DESCRIPTION = 'Use the Troubleshoot menu to review the affected resources and resolve these warnings.' const MULTIPLE_RESOURCE_MIXED_SEVERITY_TITLE = "Resource warnings for {resources} are affecting your project's performance" const TroubleshootMenuItem = ({ item, onTroubleshootClick, onAskAI, }: { item: TroubleshootItem onTroubleshootClick: (item: LinkedTroubleshootItem) => void onAskAI: () => void }) => { if (item.kind === 'ai') { return ( {item.menuLabel} ) } if (item.kind === 'metrics') { return ( onTroubleshootClick(item)}> {item.menuLabel} ) } return ( onTroubleshootClick(item)}> {item.menuLabel} ) } export const ResourceExhaustionWarningBanner = () => { const { ref } = useParams() const routePattern = useRoutePattern() const { data: organization, isLoading: isOrgLoading } = useSelectedOrganizationQuery() const { limits: diskLimits } = useProjectDiskLimits() const diskIoBaselineLabel = typeof diskLimits?.baselineThroughputMBps === 'number' ? `${diskLimits.baselineThroughputMBps} MB/s` : 'its baseline' const applyDiskIoBaseline = (text?: string) => text ? text.replace(/\{baseline\}/g, diskIoBaselineLabel) : text const { openSidebar } = useSidebarManagerSnapshot() const aiSnap = useAiAssistantStateSnapshot() const track = useTrack() const showBurstBalanceChart = useShowDiskIOBurstBalanceChart() const { data: resourceWarnings } = useResourceWarningsQuery({ ref: ref }) // [Joshen Cleanup] JFYI this client side filtering can be cleaned up once BE changes are live which will only return the warnings based on the provided ref const projectResourceWarnings = (resourceWarnings ?? [])?.find( (warning) => warning.project === ref ) // [Joshen] Read only takes higher precedence over multiple resource warnings const activeWarnings: ConfiguredResourceWarning[] = projectResourceWarnings !== undefined ? projectResourceWarnings.is_readonly_mode_enabled ? ['is_readonly_mode_enabled'] : Object.keys(projectResourceWarnings).filter( (property): property is ConfiguredResourceWarning => property !== 'project' && property !== 'is_readonly_mode_enabled' && isConfiguredResourceWarning(property) && projectResourceWarnings[property] !== null ) : [] const hasCriticalWarning = projectResourceWarnings !== undefined ? activeWarnings.some((warningType) => projectResourceWarnings[warningType] === 'critical') : false const hasWarningSeverity = projectResourceWarnings !== undefined ? activeWarnings.some((warningType) => projectResourceWarnings[warningType] === 'warning') : false const hasMixedWarningSeverities = hasCriticalWarning && hasWarningSeverity const isCritical = activeWarnings.includes('is_readonly_mode_enabled') || hasCriticalWarning const warningContent = projectResourceWarnings !== undefined ? getWarningContent(projectResourceWarnings, activeWarnings[0], 'bannerContent') : undefined const aiPrompt = getResourceWarningAiPrompt(activeWarnings) const multipleWarningDescription = aiPrompt === undefined ? MULTIPLE_RESOURCE_WARNING_NO_AI_DESCRIPTION : RESOURCE_WARNING_MESSAGES.multiple_resource_warnings.bannerContent[ hasCriticalWarning ? 'critical' : 'warning' ].description const multipleWarningTitle = hasMixedWarningSeverities ? MULTIPLE_RESOURCE_MIXED_SEVERITY_TITLE : RESOURCE_WARNING_MESSAGES.multiple_resource_warnings.bannerContent[ hasCriticalWarning ? 'critical' : 'warning' ].title const title = applyDiskIoBaseline( applyResourceList( activeWarnings.length > 1 ? multipleWarningTitle : warningContent?.title, activeWarnings ) ) const isFreePlan = organization?.plan?.id === 'free' const diskSpaceDescription = (() => { if (organization === undefined) return warningContent?.description return isFreePlan ? DISK_SPACE_EXHAUSTION_DESCRIPTION.free : DISK_SPACE_EXHAUSTION_DESCRIPTION.paid })() const singleWarningDescription = activeWarnings[0] === 'disk_space_exhaustion' ? diskSpaceDescription : warningContent?.description const description = applyDiskIoBaseline( applyResourceList( activeWarnings.length > 1 ? multipleWarningDescription : singleWarningDescription, activeWarnings ) ) const metric = activeWarnings.length > 1 ? RESOURCE_WARNING_MESSAGES.multiple_resource_warnings.metric : RESOURCE_WARNING_MESSAGES[activeWarnings[0]]?.metric // True for a single compute warning, or when all active warnings are compute-related const isComputeUpgradeMetric = isComputeUpgradeWarning(metric, activeWarnings) const correctionUrl = getResourceWarningCorrectionUrl({ metric, activeWarnings, projectRef: ref, isFreePlan, organizationSlug: organization?.slug, }) const buttonText = (() => { if (isComputeUpgradeMetric) return 'Upgrade compute' return activeWarnings.length > 1 ? RESOURCE_WARNING_MESSAGES.multiple_resource_warnings.buttonText : RESOURCE_WARNING_MESSAGES[activeWarnings[0]]?.buttonText })() const troubleshootItems = getTroubleshootItems({ activeWarnings, projectRef: ref ?? 'default', aiPrompt, showBurstBalanceChart, }) const soleTroubleshootItem = troubleshootItems.length === 1 ? troubleshootItems[0] : undefined const handleAskAI = () => { track('resource_exhaustion_banner_ai_assistant_clicked', { warningTypes: activeWarnings, }) openSidebar(SIDEBAR_KEYS.AI_ASSISTANT) aiSnap.newChat({ initialInput: aiPrompt }) } const handleTroubleshootClick = (item: LinkedTroubleshootItem) => { track('resource_exhaustion_banner_troubleshoot_clicked', { troubleshootAction: item.kind, warningType: item.warningType, warningTypes: activeWarnings, destination: item.href, }) } const hasNoWarnings = activeWarnings.length === 0 const hasNoWarningContent = warningContent === undefined || (!warningContent?.title && !warningContent?.description) const isUsageOrInfraPage = routePattern.endsWith('/usage') || routePattern.endsWith('/infrastructure') // Compute warnings now link to infrastructure, so they should remain visible on usage. const onUsageOrInfraAndNotInReadOnlyMode = isUsageOrInfraPage && !activeWarnings.includes('is_readonly_mode_enabled') && !isComputeUpgradeMetric // Suppress when already on the target page (no-op CTA). Paid-plan compute warnings link to // infrastructure; free-plan links to billing instead, so we keep the banner visible for them. const shouldSuppressOnInfrastructurePage = routePattern.endsWith('settings/infrastructure') && (activeWarnings.includes('is_readonly_mode_enabled') || (isComputeUpgradeMetric && !isFreePlan)) if ( hasNoWarnings || hasNoWarningContent || onUsageOrInfraAndNotInReadOnlyMode || shouldSuppressOnInfrastructurePage ) { return null } return ( svg]:left-6 px-6 [&>svg]:w-[26px] [&>svg]:h-[26px]' )} >
{title} {description}
{troubleshootItems.length >= 2 && ( {troubleshootItems.map((item) => ( ))} )} {soleTroubleshootItem?.kind === 'metrics' && ( )} {soleTroubleshootItem?.kind === 'docs' && ( )} {soleTroubleshootItem?.kind === 'ai' && ( )} {correctionUrl !== undefined && ( )}
) }