Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(studio): advisor signal items for banned IPs (#44372)

Danny Whiteb721a2d78080
diff --git a/apps/studio/components/interfaces/ProjectHome/AdvisorSection.tsx b/apps/studio/components/interfaces/ProjectHome/AdvisorSection.tsx
index 9201ae2a27d..2875d292ac5 100644
--- a/apps/studio/components/interfaces/ProjectHome/AdvisorSection.tsx
+++ b/apps/studio/components/interfaces/ProjectHome/AdvisorSection.tsx
@@ -1,7 +1,7 @@
import { useParams } from 'common'
import { BarChart, Shield } from 'lucide-react'
import { useCallback, useMemo } from 'react'
-import { AiIconAnimation, Button, Card, CardContent, CardHeader, CardTitle } from 'ui'
+import { AiIconAnimation, Badge, Button, Card, CardContent, CardHeader, CardTitle, cn } from 'ui'
import { Row } from 'ui-patterns'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
@@ -9,8 +9,18 @@ import { Markdown } from '../Markdown'
import { LINTER_LEVELS } from '@/components/interfaces/Linter/Linter.constants'
import { createLintSummaryPrompt } from '@/components/interfaces/Linter/Linter.utils'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
+import type { AdvisorItem } from '@/components/ui/AdvisorPanel/AdvisorPanel.types'
+import {
+ createAdvisorLintItems,
+ getAdvisorItemDisplayTitle,
+ MAX_HOMEPAGE_ADVISOR_ITEMS,
+ severityBadgeVariants,
+ severityColorClasses,
+ sortAdvisorItems,
+} from '@/components/ui/AdvisorPanel/AdvisorPanel.utils'
+import { useAdvisorSignals } from '@/components/ui/AdvisorPanel/useAdvisorSignals'
import { AiAssistantDropdown } from '@/components/ui/AiAssistantDropdown'
-import { Lint, useProjectLintsQuery } from '@/data/lint/lint-query'
+import { useProjectLintsQuery } from '@/data/lint/lint-query'
import { useTrack } from '@/lib/telemetry/track'
import { useAdvisorStateSnapshot } from '@/state/advisor-state'
import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
@@ -18,54 +28,82 @@ import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
export const AdvisorSection = ({ showEmptyState = false }: { showEmptyState?: boolean }) => {
const { ref: projectRef } = useParams()
- const { data: lints, isPending: isLoadingLints } = useProjectLintsQuery(
- {
- projectRef,
- },
- {
- enabled: !showEmptyState,
- }
- )
const track = useTrack()
const snap = useAiAssistantStateSnapshot()
const { openSidebar } = useSidebarManagerSnapshot()
const { setSelectedItem } = useAdvisorStateSnapshot()
- const errorLints: Lint[] = useMemo(() => {
- return lints?.filter((lint) => lint.level === LINTER_LEVELS.ERROR) ?? []
- }, [lints])
+ const { data: lints, isLoading: isLoadingLints } = useProjectLintsQuery(
+ { projectRef },
+ { enabled: !showEmptyState }
+ )
+
+ const { data: signalItems } = useAdvisorSignals({ projectRef, enabled: !showEmptyState })
- const totalErrors = errorLints.length
+ const advisorItems = useMemo<AdvisorItem[]>(() => {
+ const criticalLintItems = createAdvisorLintItems(lints).filter(
+ (item) => item.source === 'lint' && item.original.level === LINTER_LEVELS.ERROR
+ )
+
+ return sortAdvisorItems([...criticalLintItems, ...signalItems])
+ }, [lints, signalItems])
+
+ const visibleAdvisorItems = useMemo(
+ () => advisorItems.slice(0, MAX_HOMEPAGE_ADVISOR_ITEMS),
+ [advisorItems]
+ )
+
+ const totalIssues = advisorItems.length
+ const hiddenIssuesCount = totalIssues - visibleAdvisorItems.length
const titleContent = useMemo(() => {
- if (totalErrors === 0) return <h2>Advisor found no issues</h2>
- const issuesText = totalErrors === 1 ? 'issue' : 'issues'
- const numberDisplay = totalErrors.toString()
+ if (totalIssues === 0) return <h2>Advisor found no issues</h2>
+ const issuesText = totalIssues === 1 ? 'issue' : 'issues'
+ const numberDisplay = totalIssues.toString()
return (
<h2>
Advisor found {numberDisplay} {issuesText}
</h2>
)
- }, [totalErrors])
+ }, [totalIssues])
const handleAskAssistant = useCallback(() => {
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
track('advisor_assistant_button_clicked', {
origin: 'homepage',
- issuesCount: totalErrors,
+ issuesCount: totalIssues,
})
- }, [track, openSidebar, totalErrors])
+ }, [track, openSidebar, totalIssues])
const handleCardClick = useCallback(
- (lint: Lint) => {
- setSelectedItem(lint.cache_key, 'lint')
+ (item: AdvisorItem) => {
+ setSelectedItem(item.id, item.source)
openSidebar(SIDEBAR_KEYS.ADVISOR_PANEL)
+
+ const advisorCategory =
+ item.source === 'lint'
+ ? item.original.categories.includes('SECURITY')
+ ? 'SECURITY'
+ : item.original.categories.includes('PERFORMANCE')
+ ? 'PERFORMANCE'
+ : undefined
+ : item.source === 'signal'
+ ? 'SECURITY'
+ : undefined
+ const advisorType =
+ item.source === 'signal'
+ ? item.type
+ : item.source === 'lint'
+ ? item.original.name
+ : item.title
+ const advisorLevel = item.source === 'lint' ? item.original.level : undefined
+
track('advisor_detail_opened', {
origin: 'homepage',
- advisorSource: 'lint',
- advisorCategory: lint.categories[0],
- advisorType: lint.name,
- advisorLevel: lint.level,
+ advisorSource: item.source,
+ advisorCategory,
+ advisorType,
+ advisorLevel,
})
},
[track, setSelectedItem, openSidebar]
@@ -75,6 +113,9 @@ export const AdvisorSection = ({ showEmptyState = false }: { showEmptyState?: bo
return <EmptyState />
}
+ // [Joshen] Note that we're intentionally (for now) not waiting for advisor signals to load
+ // render main content as long as the main lints have been fetched
+
return (
<div>
{isLoadingLints ? (
@@ -87,73 +128,111 @@ export const AdvisorSection = ({ showEmptyState = false }: { showEmptyState?: bo
</Button>
</div>
)}
+
{isLoadingLints ? (
- <div className="flex flex-col p-4 gap-2">
+ <div className="flex flex-col gap-2">
<ShimmeringLoader />
<ShimmeringLoader className="w-3/4" />
<ShimmeringLoader className="w-1/2" />
</div>
- ) : errorLints.length > 0 ? (
+ ) : visibleAdvisorItems.length > 0 ? (
<>
<Row maxColumns={4} minWidth={280}>
- {errorLints.map((lint) => {
+ {visibleAdvisorItems.map((item) => {
+ const isLint = item.source === 'lint'
+ const categoryLabel = item.tab === 'performance' ? 'PERFORMANCE' : 'SECURITY'
+ const title = getAdvisorItemDisplayTitle(item)
+ const description =
+ item.source === 'signal' ? item.summary : isLint ? item.original.detail : ''
+ const cardClasses =
+ item.severity === 'critical'
+ ? 'border-destructive-400'
+ : item.severity === 'warning'
+ ? 'border-warning-400'
+ : ''
+
return (
<Card
- key={lint.cache_key}
- className="min-h-full flex flex-col items-stretch cursor-pointer h-64"
+ key={`${item.source}-${item.id}`}
+ className={cn(
+ 'min-h-full flex flex-col items-stretch cursor-pointer h-64',
+ cardClasses
+ )}
onClick={() => {
- handleCardClick(lint)
+ handleCardClick(item)
}}
>
<CardHeader className="border-b-0 shrink-0 flex flex-row gap-2 space-y-0 justify-between items-center">
<div className="flex flex-row items-center gap-3">
- {lint.categories[0] === 'SECURITY' ? (
- <Shield size={16} strokeWidth={1.5} className="text-foreground-muted" />
+ {item.tab === 'security' ? (
+ <Shield
+ size={16}
+ strokeWidth={1.5}
+ className={severityColorClasses[item.severity]}
+ />
) : (
- <BarChart size={16} strokeWidth={1.5} className="text-foreground-muted" />
+ <BarChart
+ size={16}
+ strokeWidth={1.5}
+ className={severityColorClasses[item.severity]}
+ />
)}
- <CardTitle className="text-foreground-light">{lint.categories[0]}</CardTitle>
+ <CardTitle className="text-foreground-light">{categoryLabel}</CardTitle>
</div>
- <div
- onClick={(e) => {
- e.stopPropagation()
- e.preventDefault()
- }}
- >
- <AiAssistantDropdown
- label="Ask Assistant"
- iconOnly
- tooltip="Help me fix this issue"
- buildPrompt={() => createLintSummaryPrompt(lint)}
- onOpenAssistant={() => {
- openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
- snap.newChat({
- name: 'Summarize lint',
- initialInput: createLintSummaryPrompt(lint),
- })
- track('advisor_assistant_button_clicked', {
- origin: 'homepage',
- advisorCategory: lint.categories[0],
- advisorType: lint.name,
- advisorLevel: lint.level,
- })
- }}
- telemetrySource="advisor_section"
- type="text"
- className="w-7 h-7"
- />
+ <div className="flex items-center gap-2">
+ <Badge variant={severityBadgeVariants[item.severity]} className="w-fit">
+ {item.severity.toUpperCase()}
+ </Badge>
+ {isLint && (
+ <div
+ onClick={(e) => {
+ e.stopPropagation()
+ e.preventDefault()
+ }}
+ >
+ <AiAssistantDropdown
+ label="Ask Assistant"
+ iconOnly
+ tooltip="Help me fix this issue"
+ buildPrompt={() => createLintSummaryPrompt(item.original)}
+ onOpenAssistant={() => {
+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
+ snap.newChat({
+ name: 'Summarise lint',
+ initialInput: createLintSummaryPrompt(item.original),
+ })
+ track('advisor_assistant_button_clicked', {
+ origin: 'homepage',
+ advisorCategory: item.original.categories[0],
+ advisorType: item.original.name,
+ advisorLevel: item.original.level,
+ })
+ }}
+ telemetrySource="advisor_section"
+ type="text"
+ className="w-7 h-7"
+ />
+ </div>
+ )}
</div>
</CardHeader>
<CardContent className="p-6 pt-16 flex flex-col justify-end flex-1 overflow-auto">
- <h3 className="mb-1">{lint.title}</h3>
+ <h3 className="mb-1">{title}</h3>
<Markdown className="leading-6 text-sm text-foreground-light">
- {lint.detail && lint.detail.replace(/\\`/g, '`')}
+ {description && description.replace(/\\`/g, '`')}
</Markdown>
</CardContent>
</Card>
)
})}
</Row>
+ {hiddenIssuesCount > 0 && (
+ <div className="mt-4 flex justify-end">
+ <Button type="text" onClick={() => openSidebar(SIDEBAR_KEYS.ADVISOR_PANEL)}>
+ View {hiddenIssuesCount} more issue{hiddenIssuesCount !== 1 ? 's' : ''} in Advisor
+ </Button>
+ </div>
+ )}
</>
) : (
<EmptyState />
@@ -168,7 +247,7 @@ function EmptyState() {
<CardContent className="flex flex-col items-center justify-center gap-2 p-16 h-full">
<Shield size={20} strokeWidth={1.5} className="text-foreground-muted" />
<p className="text-sm text-foreground-light text-center">
- No security or performance errors found
+ No security or performance issues found
</p>
</CardContent>
</Card>
diff --git a/apps/studio/components/layouts/AppLayout/AdvisorButton.test.tsx b/apps/studio/components/layouts/AppLayout/AdvisorButton.test.tsx
new file mode 100644
index 00000000000..9f722d69f86
--- /dev/null
+++ b/apps/studio/components/layouts/AppLayout/AdvisorButton.test.tsx
@@ -0,0 +1,163 @@
+import { screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { AdvisorButton } from '@/components/layouts/AppLayout/AdvisorButton'
+import { render } from '@/tests/helpers'
+
+const {
+ mockUseProjectLintsQuery,
+ mockUseNotificationsV2Query,
+ mockUseAdvisorSignals,
+ mockToggleSidebar,
+} = vi.hoisted(() => ({
+ mockUseProjectLintsQuery: vi.fn(),
+ mockUseNotificationsV2Query: vi.fn(),
+ mockUseAdvisorSignals: vi.fn(),
+ mockToggleSidebar: vi.fn(),
+}))
+
+vi.mock('@/data/lint/lint-query', () => ({
+ useProjectLintsQuery: mockUseProjectLintsQuery,
+}))
+
+vi.mock('@/data/notifications/notifications-v2-query', () => ({
+ useNotificationsV2Query: mockUseNotificationsV2Query,
+}))
+
+vi.mock('@/components/ui/AdvisorPanel/useAdvisorSignals', () => ({
+ useAdvisorSignals: mockUseAdvisorSignals,
+}))
+
+vi.mock('@/lib/constants', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/constants')>()),
+ IS_PLATFORM: true,
+}))
+
+vi.mock('@/state/sidebar-manager-state', () => ({
+ useSidebarManagerSnapshot: () => ({
+ toggleSidebar: mockToggleSidebar,
+ activeSidebar: undefined,
+ }),
+}))
+
+describe('AdvisorButton', () => {
+ beforeEach(() => {
+ mockUseProjectLintsQuery.mockReturnValue({ data: [], isPending: false, isError: false })
+ mockUseNotificationsV2Query.mockReturnValue({
+ data: { pages: [[]] },
+ isPending: false,
+ isError: false,
+ })
+ mockUseAdvisorSignals.mockReturnValue({
+ data: [],
+ isPending: false,
+ isError: false,
+ dismissSignal: vi.fn(),
+ })
+ })
+
+ afterEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('shows a warning dot when advisor signals are present', () => {
+ mockUseAdvisorSignals.mockReturnValue({
+ data: [
+ {
+ id: 'signal-1',
+ fingerprint: 'signal:banned-ip:203.0.113.10:v1',
+ source: 'signal',
+ signalType: 'banned-ip',
+ severity: 'warning',
+ tab: 'security',
+ title: 'Banned IP address',
+ description: 'Signal',
+ actions: [],
+ sourceData: {
+ type: 'banned-ip',
+ ip: '203.0.113.10',
+ },
+ },
+ ],
+ isPending: false,
+ isError: false,
+ dismissSignal: vi.fn(),
+ })
+
+ const { container } = render(<AdvisorButton projectRef="project-ref" />)
+
+ expect(container.querySelector('.bg-warning')).toBeInTheDocument()
+ expect(container.querySelector('.bg-destructive')).not.toBeInTheDocument()
+ expect(container.querySelector('.bg-brand')).not.toBeInTheDocument()
+ })
+
+ it('keeps the destructive dot when a critical issue is present', () => {
+ mockUseProjectLintsQuery.mockReturnValue({
+ data: [
+ {
+ cache_key: 'lint-1',
+ name: 'unknown_lint',
+ detail: 'Critical lint detail',
+ description: 'Description',
+ level: 'ERROR',
+ categories: ['SECURITY'],
+ metadata: {},
+ },
+ ],
+ isPending: false,
+ isError: false,
+ })
+ mockUseAdvisorSignals.mockReturnValue({
+ data: [
+ {
+ id: 'signal-1',
+ fingerprint: 'signal:banned-ip:203.0.113.10:v1',
+ source: 'signal',
+ signalType: 'banned-ip',
+ severity: 'warning',
+ tab: 'security',
+ title: 'Banned IP address',
+ description: 'Signal',
+ actions: [],
+ sourceData: {
+ type: 'banned-ip',
+ ip: '203.0.113.10',
+ },
+ },
+ ],
+ isPending: false,
+ isError: false,
+ dismissSignal: vi.fn(),
+ })
+
+ const { container } = render(<AdvisorButton projectRef="project-ref" />)
+
+ expect(container.querySelector('.bg-destructive')).toBeInTheDocument()
+ expect(container.querySelector('.bg-warning')).not.toBeInTheDocument()
+ })
+
+ it('falls back to the brand dot for unread notifications when there are no issues', () => {
+ mockUseNotificationsV2Query.mockReturnValue({
+ data: {
+ pages: [
+ [
+ {
+ id: 'notif-1',
+ status: 'new',
+ priority: 'Info',
+ },
+ ],
+ ],
+ },
+ isPending: false,
+ isError: false,
+ })
+
+ const { container } = render(<AdvisorButton projectRef="project-ref" />)
+
+ expect(container.querySelector('.bg-brand')).toBeInTheDocument()
+ expect(container.querySelector('.bg-warning')).not.toBeInTheDocument()
+ expect(container.querySelector('.bg-destructive')).not.toBeInTheDocument()
+ expect(screen.getByRole('button')).toBeInTheDocument()
+ })
+})
diff --git a/apps/studio/components/layouts/AppLayout/AdvisorButton.tsx b/apps/studio/components/layouts/AppLayout/AdvisorButton.tsx
index 24783838552..1cd70691b72 100644
--- a/apps/studio/components/layouts/AppLayout/AdvisorButton.tsx
+++ b/apps/studio/components/layouts/AppLayout/AdvisorButton.tsx
@@ -3,6 +3,7 @@ import { useMemo } from 'react'
import { cn } from 'ui'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
+import { useAdvisorSignals } from '@/components/ui/AdvisorPanel/useAdvisorSignals'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { useProjectLintsQuery } from '@/data/lint/lint-query'
import { useNotificationsV2Query } from '@/data/notifications/notifications-v2-query'
@@ -12,6 +13,7 @@ export const AdvisorButton = ({ projectRef }: { projectRef?: string }) => {
const { toggleSidebar, activeSidebar } = useSidebarManagerSnapshot()
const { data: lints } = useProjectLintsQuery({ projectRef })
+ const { data: signalItems } = useAdvisorSignals({ projectRef })
const { data: notificationsData } = useNotificationsV2Query({
filters: {},
@@ -22,10 +24,14 @@ export const AdvisorButton = ({ projectRef }: { projectRef?: string }) => {
}, [notificationsData?.pages])
const hasUnreadNotifications = notifications.some((x) => x?.status === 'new')
const hasCriticalNotifications = notifications.some((x) => x?.priority === 'Critical')
+ const hasSignals = signalItems.length > 0
+ const hasCriticalSignals = signalItems.some((item) => item.severity === 'critical')
const hasCriticalIssues =
hasCriticalNotifications ||
+ hasCriticalSignals ||
(Array.isArray(lints) && lints.some((lint) => lint.level === 'ERROR'))
+ const hasWarningIssues = hasSignals && !hasCriticalIssues
const isOpen = activeSidebar?.id === SIDEBAR_KEYS.ADVISOR_PANEL
@@ -61,6 +67,8 @@ export const AdvisorButton = ({ projectRef }: { projectRef?: string }) => {
</ButtonTooltip>
{hasCriticalIssues ? (
<span className="absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-destructive" />
+ ) : hasWarningIssues ? (
+ <span className="absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-warning" />
) : hasUnreadNotifications ? (
<span className="absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-brand" />
) : null}
diff --git a/apps/studio/components/ui/AdvisorPanel/AdvisorDetail.tsx b/apps/studio/components/ui/AdvisorPanel/AdvisorDetail.tsx
index b0ee6244653..e18c77e43d0 100644
--- a/apps/studio/components/ui/AdvisorPanel/AdvisorDetail.tsx
+++ b/apps/studio/components/ui/AdvisorPanel/AdvisorDetail.tsx
@@ -1,10 +1,11 @@
import { noop } from 'lodash'
import type { AdvisorItem } from './AdvisorPanel.types'
+import { AdvisorSignalDetail } from './AdvisorSignalDetail'
import { NotificationDetail } from './NotificationDetail'
import LintDetail from '@/components/interfaces/Linter/LintDetail'
-import { Lint } from '@/data/lint/lint-query'
-import { Notification } from '@/data/notifications/notifications-v2-query'
+import type { Lint } from '@/data/lint/lint-query'
+import type { Notification } from '@/data/notifications/notifications-v2-query'
interface AdvisorDetailProps {
item: AdvisorItem
@@ -26,6 +27,14 @@ export const AdvisorDetail = ({
)
}
+ if (item.source === 'signal') {
+ return (
+ <div className="px-6 py-6">
+ <AdvisorSignalDetail item={item} />
+ </div>
+ )
+ }
+
if (item.source === 'notification') {
const notification = item.original as Notification
return (
diff --git a/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.tsx b/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.tsx
index 66aa88d8e37..6694bbbc7b1 100644
--- a/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.tsx
+++ b/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.tsx
@@ -1,53 +1,26 @@
-import dayjs from 'dayjs'
import { useMemo, useRef } from 'react'
import { AdvisorDetail } from './AdvisorDetail'
import { AdvisorFilters } from './AdvisorFilters'
import type { AdvisorItem } from './AdvisorPanel.types'
+import {
+ createAdvisorLintItems,
+ createAdvisorNotificationItems,
+ sortAdvisorItems,
+} from './AdvisorPanel.utils'
import { AdvisorPanelBody } from './AdvisorPanelBody'
import { AdvisorPanelHeader } from './AdvisorPanelHeader'
+import { useAdvisorSignals } from './useAdvisorSignals'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
-import { Lint, useProjectLintsQuery } from '@/data/lint/lint-query'
-import {
- Notification,
- NotificationData,
- useNotificationsV2Query,
-} from '@/data/notifications/notifications-v2-query'
+import { useProjectLintsQuery } from '@/data/lint/lint-query'
+import { Notification, useNotificationsV2Query } from '@/data/notifications/notifications-v2-query'
import { useNotificationsV2UpdateMutation } from '@/data/notifications/notifications-v2-update-mutation'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { IS_PLATFORM } from '@/lib/constants'
import { useTrack } from '@/lib/telemetry/track'
-import { AdvisorSeverity, AdvisorTab, useAdvisorStateSnapshot } from '@/state/advisor-state'
+import { AdvisorTab, useAdvisorStateSnapshot } from '@/state/advisor-state'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
-const severityOrder: Record<AdvisorSeverity, number> = {
- critical: 0,
- warning: 1,
- info: 2,
-}
-
-const lintLevelToSeverity = (level: Lint['level']): AdvisorSeverity => {
- switch (level) {
- case 'ERROR':
- return 'critical'
- case 'WARN':
- return 'warning'
- default:
- return 'info'
- }
-}
-
-const notificationPriorityToSeverity = (priority: string | null | undefined): AdvisorSeverity => {
- switch (priority) {
- case 'Critical':
- return 'critical'
- case 'Warning':
- return 'warning'
- default:
- return 'info'
- }
-}
-
export const AdvisorPanel = () => {
const track = useTrack()
const {
@@ -70,15 +43,18 @@ export const AdvisorPanel = () => {
const isSidebarOpen = activeSidebar?.id === SIDEBAR_KEYS.ADVISOR_PANEL
const markedRead = useRef<string[]>([])
const hasProjectRef = !!project?.ref
+ const shouldLoadProjectAdvisorData = isSidebarOpen && hasProjectRef && activeTab !== 'messages'
const {
data: lintData,
isPending: isLintsLoading,
isError: isLintsError,
- } = useProjectLintsQuery(
- { projectRef: project?.ref },
- { enabled: isSidebarOpen && hasProjectRef && activeTab !== 'messages' }
- )
+ } = useProjectLintsQuery({ projectRef: project?.ref }, { enabled: shouldLoadProjectAdvisorData })
+
+ const { data: signalItems, isPending: isSignalsPending } = useAdvisorSignals({
+ projectRef: project?.ref,
+ enabled: shouldLoadProjectAdvisorData,
+ })
// Notifications should always load when sidebar is open (shown in both 'all' and 'messages' tabs)
const shouldLoadNotifications = isSidebarOpen && IS_PLATFORM
@@ -126,61 +102,17 @@ export const AdvisorPanel = () => {
}
const lintItems = useMemo<AdvisorItem[]>(() => {
- if (!lintData) return []
-
- return lintData
- .map((lint): AdvisorItem | null => {
- const categories = lint.categories || []
- const tab = categories.includes('SECURITY')
- ? ('security' as const)
- : categories.includes('PERFORMANCE')
- ? ('performance' as const)
- : undefined
-
- if (!tab) return null
-
- return {
- id: lint.cache_key,
- title: lint.detail,
- severity: lintLevelToSeverity(lint.level),
- createdAt: undefined,
- tab,
- source: 'lint' as const,
- original: lint,
- }
- })
- .filter((item): item is AdvisorItem => item !== null)
+ return createAdvisorLintItems(lintData)
}, [lintData])
const notificationItems = useMemo<AdvisorItem[]>(() => {
if (!IS_PLATFORM) return []
- return notifications?.map((notification): AdvisorItem => {
- const data = notification.data as NotificationData
- return {
- id: notification.id,
- title: data.title,
- severity: notificationPriorityToSeverity(notification.priority),
- createdAt: dayjs(notification.inserted_at).valueOf(),
- tab: 'messages' as const,
- source: 'notification' as const,
- original: notification,
- }
- })
+ return createAdvisorNotificationItems(notifications)
}, [notifications])
const combinedItems = useMemo<AdvisorItem[]>(() => {
- const all = [...lintItems, ...notificationItems]
-
- return all.sort((a, b) => {
- const severityDiff = severityOrder[a.severity] - severityOrder[b.severity]
- if (severityDiff !== 0) return severityDiff
-
- const createdDiff = (b.createdAt ?? 0) - (a.createdAt ?? 0)
- if (createdDiff !== 0) return createdDiff
-
- return a.title.localeCompare(b.title)
- })
- }, [lintItems, notificationItems])
+ return sortAdvisorItems([...lintItems, ...signalItems, ...notificationItems])
+ }, [lintItems, signalItems, notificationItems])
const filteredItems = useMemo<AdvisorItem[]>(() => {
return combinedItems.filter((item) => {
@@ -223,10 +155,13 @@ export const AdvisorPanel = () => {
const isDetailView = !!selectedItem
// Only show loading state if the query is actually enabled
- const isLintsActuallyLoading =
- isSidebarOpen && hasProjectRef && activeTab !== 'messages' && isLintsLoading
+ const isLintsActuallyLoading = shouldLoadProjectAdvisorData && isLintsLoading
const isNotificationsActuallyLoading = shouldLoadNotifications && isNotificationsLoading
- const isLoading = isLintsActuallyLoading || isNotificationsActuallyLoading
+ const isSignalsActuallyLoading = shouldLoadProjectAdvisorData && isSignalsPending
+ const isLoading =
+ isLintsActuallyLoading || isNotificationsActuallyLoading || isSignalsActuallyLoading
+
+ // [Joshen] Opting to ignore error state of advisor signals for now - render lints irregardless of banned ips
const isError = isLintsError || isNotificationsError
const handleTabChange = (tab: string) => {
@@ -255,17 +190,28 @@ export const AdvisorPanel = () => {
}
const advisorCategory =
- item.source === 'lint' && 'categories' in item.original
- ? item.original.categories[0]
- : undefined
- const advisorLevel =
- item.source === 'lint' && 'level' in item.original ? item.original.level : undefined
+ item.source === 'lint'
+ ? item.original.categories.includes('SECURITY')
+ ? 'SECURITY'
+ : item.original.categories.includes('PERFORMANCE')
+ ? 'PERFORMANCE'
+ : undefined
+ : item.source === 'signal'
+ ? 'SECURITY'
+ : undefined
+ const advisorType =
+ item.source === 'signal'
+ ? item.type
+ : item.source === 'lint'
+ ? item.original.name
+ : item.title
+ const advisorLevel = item.source === 'lint' ? item.original.level : undefined
track('advisor_detail_opened', {
origin: 'advisor_panel',
advisorCategory,
advisorSource: item.source,
- advisorType: item.original.name,
+ advisorType,
advisorLevel,
})
}
diff --git a/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.types.ts b/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.types.ts
index 24103dcfcf6..c9281727c77 100644
--- a/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.types.ts
+++ b/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.types.ts
@@ -1,13 +1,42 @@
-import { Lint } from '@/data/lint/lint-query'
-import { Notification } from '@/data/notifications/notifications-v2-query'
-import { AdvisorItemSource, AdvisorSeverity } from '@/state/advisor-state'
+import type { Lint } from '@/data/lint/lint-query'
+import type { Notification } from '@/data/notifications/notifications-v2-query'
+import type { AdvisorItemSource, AdvisorSeverity } from '@/state/advisor-state'
-export type AdvisorItem = {
+export type AdvisorSignalType = 'banned-ip'
+
+export type AdvisorSignalAction = {
+ label: string
+ href: string
+}
+
+type AdvisorBaseItem = {
id: string
title: string
severity: AdvisorSeverity
createdAt?: number
tab: 'security' | 'performance' | 'messages'
source: AdvisorItemSource
- original: Lint | Notification
}
+
+export type AdvisorLintItem = AdvisorBaseItem & {
+ source: 'lint'
+ original: Lint
+}
+
+export type AdvisorNotificationItem = AdvisorBaseItem & {
+ source: 'notification'
+ original: Notification
+}
+
+export type AdvisorSignalItem = AdvisorBaseItem & {
+ source: 'signal'
+ type: AdvisorSignalType
+ dismissalKey: string
+ summary: string
+ description?: string
+ docsUrl?: string
+ actions: AdvisorSignalAction[]
+ sourceData: { type: 'banned-ip'; ip: string }
+}
+
+export type AdvisorItem = AdvisorLintItem | AdvisorNotificationItem | AdvisorSignalItem
diff --git a/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.utils.test.ts b/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.utils.test.ts
new file mode 100644
index 00000000000..d9e9eb5eff3
--- /dev/null
+++ b/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.utils.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from 'vitest'
+
+import type { AdvisorSignalItem } from './AdvisorPanel.types'
+import {
+ createAdvisorLintItems,
+ createAdvisorNotificationItems,
+ getAdvisorItemSecondaryText,
+ sortAdvisorItems,
+} from './AdvisorPanel.utils'
+import type { Lint } from '@/data/lint/lint-query'
+import type { Notification } from '@/data/notifications/notifications-v2-query'
+
+const createLint = (overrides: Partial<Lint> = {}): Lint =>
+ ({
+ cache_key: 'lint-1',
+ name: 'unknown_lint',
+ detail: 'Critical lint detail',
+ level: 'ERROR',
+ categories: ['SECURITY'],
+ metadata: {},
+ ...overrides,
+ }) as Lint
+
+const createNotification = (overrides: Partial<Notification> = {}): Notification =>
+ ({
+ id: 'notification-1',
+ inserted_at: '2026-03-01T00:00:00.000Z',
+ priority: 'Info',
+ status: 'seen',
+ data: {
+ title: 'Notification title',
+ message: 'Notification body',
+ actions: [],
+ },
+ ...overrides,
+ }) as Notification
+
+const createBannedIPSignalItem = (ip: string): AdvisorSignalItem => ({
+ id: `signal:banned-ip:${ip}:v1`,
+ dismissalKey: `signal:banned-ip:${ip}:v1`,
+ source: 'signal',
+ type: 'banned-ip',
+ severity: 'warning',
+ tab: 'security',
+ title: 'Banned IP address',
+ summary: `The IP address \`${ip}\` is temporarily blocked.`,
+ docsUrl: 'https://supabase.com/docs/reference/cli/supabase-network-bans',
+ actions: [],
+ sourceData: { type: 'banned-ip', ip },
+})
+
+describe('AdvisorPanel.utils', () => {
+ it('orders mixed lint, signal and notification items by severity and recency', () => {
+ const lintItems = createAdvisorLintItems([
+ createLint({ cache_key: 'lint-critical', detail: 'Critical lint detail' }),
+ ])
+ const signalItems = [createBannedIPSignalItem('203.0.113.10')]
+ const notificationItems = createAdvisorNotificationItems([
+ createNotification({
+ id: 'notification-info',
+ data: { title: 'Notification title', message: 'Body', actions: [] },
+ }),
+ ])
+
+ const sorted = sortAdvisorItems([...notificationItems, ...signalItems, ...lintItems])
+
+ expect(sorted.map((item) => item.source)).toEqual(['lint', 'signal', 'notification'])
+ })
+
+ it('uses database surface-area metadata and the IP address for banned IP signals', () => {
+ const bannedIpSignal = createBannedIPSignalItem('203.0.113.10')
+ expect(getAdvisorItemSecondaryText(bannedIpSignal)).toBe('Database · 203.0.113.10')
+ })
+})
diff --git a/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.utils.ts b/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.utils.ts
index e740a405294..61e35f26298 100644
--- a/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.utils.ts
+++ b/apps/studio/components/ui/AdvisorPanel/AdvisorPanel.utils.ts
@@ -1,10 +1,103 @@
import dayjs from 'dayjs'
import { Gauge, Inbox, Shield } from 'lucide-react'
+import type { ElementType } from 'react'
-import type { AdvisorItem } from './AdvisorPanel.types'
+import type { AdvisorItem, AdvisorLintItem, AdvisorNotificationItem } from './AdvisorPanel.types'
import { lintInfoMap } from '@/components/interfaces/Linter/Linter.utils'
-import { Lint } from '@/data/lint/lint-query'
-import { AdvisorSeverity, AdvisorTab } from '@/state/advisor-state'
+import type { Lint } from '@/data/lint/lint-query'
+import type { Notification, NotificationData } from '@/data/notifications/notifications-v2-query'
+import type { AdvisorSeverity, AdvisorTab } from '@/state/advisor-state'
+
+export const MAX_HOMEPAGE_ADVISOR_ITEMS = 4
+
+export const severityOrder: Record<AdvisorSeverity, number> = {
+ critical: 0,
+ warning: 1,
+ info: 2,
+}
+
+export const lintLevelToSeverity = (level: Lint['level']): AdvisorSeverity => {
+ switch (level) {
+ case 'ERROR':
+ return 'critical'
+ case 'WARN':
+ return 'warning'
+ default:
+ return 'info'
+ }
+}
+
+export const notificationPriorityToSeverity = (
+ priority: string | null | undefined
+): AdvisorSeverity => {
+ switch (priority) {
+ case 'Critical':
+ return 'critical'
+ case 'Warning':
+ return 'warning'
+ default:
+ return 'info'
+ }
+}
+
+export const createAdvisorLintItems = (lintData?: Lint[]): AdvisorLintItem[] => {
+ if (!lintData) return []
+
+ return lintData
+ .map((lint): AdvisorLintItem | null => {
+ const categories = lint.categories || []
+ const tab = categories.includes('SECURITY')
+ ? ('security' as const)
+ : categories.includes('PERFORMANCE')
+ ? ('performance' as const)
+ : undefined
+
+ if (!tab) return null
+
+ return {
+ id: lint.cache_key,
+ title: lint.detail,
+ severity: lintLevelToSeverity(lint.level),
+ createdAt: undefined,
+ tab,
+ source: 'lint',
+ original: lint,
+ }
+ })
+ .filter((item): item is AdvisorLintItem => item !== null)
+}
+
+export const createAdvisorNotificationItems = (
+ notifications?: Notification[]
+): AdvisorNotificationItem[] => {
+ if (!notifications) return []
+
+ return notifications.map((notification) => {
+ const data = notification.data as NotificationData
+
+ return {
+ id: notification.id,
+ title: data.title,
+ severity: notificationPriorityToSeverity(notification.priority),
+ createdAt: dayjs(notification.inserted_at).valueOf(),
+ tab: 'messages' as const,
+ source: 'notification' as const,
+ original: notification,
+ }
+ })
+}
+
+export const sortAdvisorItems = <T extends AdvisorItem>(items: T[]) => {
+ return [...items].sort((a, b) => {
+ const severityDiff = severityOrder[a.severity] - severityOrder[b.severity]
+ if (severityDiff !== 0) return severityDiff
+
+ const createdDiff = (b.createdAt ?? 0) - (a.createdAt ?? 0)
+ if (createdDiff !== 0) return createdDiff
+
+ return getAdvisorItemDisplayTitle(a).localeCompare(getAdvisorItemDisplayTitle(b))
+ })
+}
export const formatItemDate = (timestamp: number): string => {
const daysFromNow = dayjs().diff(dayjs(timestamp), 'day')
@@ -15,15 +108,40 @@ export const formatItemDate = (timestamp: number): string => {
export const getAdvisorItemDisplayTitle = (item: AdvisorItem): string => {
if (item.source === 'lint') {
- const lint = item.original as Lint
return (
- lintInfoMap.find((info) => info.name === lint.name)?.title || item.title.replace(/[`\\]/g, '')
+ lintInfoMap.find((info) => info.name === item.original.name)?.title ||
+ item.title.replace(/[`\\]/g, '')
)
}
+
+ if (item.source === 'signal') {
+ return `${item.title}`
+ }
+
return item.title.replace(/[`\\]/g, '')
}
-export const tabIconMap: Record<Exclude<AdvisorTab, 'all'>, React.ElementType> = {
+export const getAdvisorPanelItemDisplayTitle = (item: AdvisorItem): string => {
+ if (item.source === 'signal') {
+ return item.title
+ }
+
+ return getAdvisorItemDisplayTitle(item)
+}
+
+export const getAdvisorItemSecondaryText = (item: AdvisorItem): string | undefined => {
+ if (item.source === 'lint') {
+ return getLintEntityString(item.original)
+ }
+
+ if (item.source === 'signal') {
+ return `Database · ${item.sourceData.ip}`
+ }
+
+ return undefined
+}
+
+export const tabIconMap: Record<Exclude<AdvisorTab, 'all'>, ElementType> = {
security: Shield,
performance: Gauge,
messages: Inbox,
diff --git a/apps/studio/components/ui/AdvisorPanel/AdvisorPanelBody.tsx b/apps/studio/components/ui/AdvisorPanel/AdvisorPanelBody.tsx
index b3a190826dd..e08eeeb6d45 100644
--- a/apps/studio/components/ui/AdvisorPanel/AdvisorPanelBody.tsx
+++ b/apps/studio/components/ui/AdvisorPanel/AdvisorPanelBody.tsx
@@ -5,17 +5,16 @@ import { GenericSkeletonLoader } from 'ui-patterns'
import type { AdvisorItem } from './AdvisorPanel.types'
import {
formatItemDate,
- getAdvisorItemDisplayTitle,
- getLintEntityString,
+ getAdvisorItemSecondaryText,
+ getAdvisorPanelItemDisplayTitle,
severityBadgeVariants,
severityColorClasses,
severityLabels,
tabIconMap,
} from './AdvisorPanel.utils'
import { EmptyAdvisor } from './EmptyAdvisor'
-import { Lint } from '@/data/lint/lint-query'
-import { Notification } from '@/data/notifications/notifications-v2-query'
-import { AdvisorSeverity, AdvisorTab } from '@/state/advisor-state'
+import type { Notification } from '@/data/notifications/notifications-v2-query'
+import type { AdvisorSeverity, AdvisorTab } from '@/state/advisor-state'
const NoProjectNotice = () => {
return (
@@ -71,10 +70,12 @@ export const AdvisorPanelBody = ({
if (isError) {
return (
- <div className="my-8 mx-4 flex flex-col items-center gap-2">
+ <div className="h-full mx-4 flex flex-col items-center justify-center gap-y-2">
<AlertTriangle className="text-destructive" />
- <h2 className="text-base text-foreground-light">Error loading advisories</h2>
- <p className="text-sm text-foreground-lighter">Please try again later.</p>
+ <div className="flex flex-col items-center justify-center">
+ <h4 className="text-base font-normal text-foreground-light">Error loading advisories</h4>
+ <p className="text-sm text-foreground-lighter">Please try again later.</p>
+ </div>
</div>
)
}
@@ -98,14 +99,14 @@ export const AdvisorPanelBody = ({
const isNotification = item.source === 'notification'
const notification = isNotification ? (item.original as Notification) : null
const isUnread = notification?.status === 'new'
- const lint = !isNotification ? (item.original as Lint) : null
-
- // Primary text: issue type for lint items, title for notifications
- const primaryText = getAdvisorItemDisplayTitle(item)
- // Secondary text: entity for lint items when no date, date for notifications
- const hasDate = !!item.createdAt
- const entityString = getLintEntityString(lint)
+ const primaryText = getAdvisorPanelItemDisplayTitle(item)
+ const secondaryText = getAdvisorItemSecondaryText(item)
+ const metadataText =
+ secondaryText ?? (item.createdAt ? formatItemDate(item.createdAt) : undefined)
+ // Date strings (e.g. "a few seconds ago") come from formatItemDate and
+ // need sentence-case capitalisation; entity strings (lint / signal) don't.
+ const metadataCapitalize = secondaryText === undefined && item.createdAt !== undefined
return (
<div key={`${item.source}-${item.id}`} className="border-b">
@@ -126,16 +127,14 @@ export const AdvisorPanelBody = ({
/>
<div className="text-left flex flex-col gap-0.5 truncate flex-1 min-w-0">
<div className="truncate">{primaryText}</div>
- {hasDate ? (
- <span className="text-xs text-foreground-light capitalize-sentence">
- {formatItemDate(item.createdAt!)}
- </span>
- ) : (
- entityString && (
- <div className="flex items-center gap-1 text-xs text-foreground-light">
- <span className="truncate">{entityString}</span>
- </div>
- )
+ {metadataText && (
+ <div className="flex items-center gap-1 text-xs text-foreground-light">
+ <span
+ className={cn('truncate', metadataCapitalize && 'capitalize-sentence')}
+ >
+ {metadataText}
+ </span>
+ </div>
)}
</div>
</div>
diff --git a/apps/studio/components/ui/AdvisorPanel/AdvisorPanelHeader.tsx b/apps/studio/components/ui/AdvisorPanel/AdvisorPanelHeader.tsx
index 42f73d1a5c2..f4c43c01843 100644
--- a/apps/studio/components/ui/AdvisorPanel/AdvisorPanelHeader.tsx
+++ b/apps/studio/components/ui/AdvisorPanel/AdvisorPanelHeader.tsx
@@ -4,7 +4,8 @@ import { Badge } from 'ui'
import type { AdvisorItem } from './AdvisorPanel.types'
import {
formatItemDate,
- getAdvisorItemDisplayTitle,
+ getAdvisorItemSecondaryText,
+ getAdvisorPanelItemDisplayTitle,
severityBadgeVariants,
severityLabels,
} from './AdvisorPanel.utils'
@@ -17,7 +18,18 @@ interface AdvisorPanelHeaderProps {
}
export const AdvisorPanelHeader = ({ selectedItem, onBack, onClose }: AdvisorPanelHeaderProps) => {
- const displayTitle = selectedItem ? getAdvisorItemDisplayTitle(selectedItem) : undefined
+ const displayTitle = selectedItem ? getAdvisorPanelItemDisplayTitle(selectedItem) : undefined
+ const secondaryText = selectedItem ? getAdvisorItemSecondaryText(selectedItem) : undefined
+ const metadataText = selectedItem
+ ? (secondaryText ??
+ (selectedItem.createdAt ? formatItemDate(selectedItem.createdAt) : undefined))
+ : undefined
+ // Only capitalize date strings (e.g. "a few seconds ago"); entity strings
+ // like "public.users" must not be case-altered.
+ const metadataCapitalize =
+ selectedItem !== undefined &&
+ secondaryText === undefined &&
+ selectedItem.createdAt !== undefined
return (
<div className="border-b px-4 py-3 flex items-center gap-3">
@@ -29,11 +41,13 @@ export const AdvisorPanelHeader = ({ selectedItem, onBack, onClose }: AdvisorPan
tooltip={{ content: { side: 'bottom', text: 'Back to list' } }}
/>
<div className="flex items-center gap-2 overflow-hidden flex-1">
- <div className="flex-1 flex flex-col gap-0.5">
+ <div className="flex-1 flex flex-col">
<span className="heading-default">{displayTitle}</span>
- {selectedItem?.createdAt && (
- <span className="text-xs text-foreground-light capitalize-sentence">
- {formatItemDate(selectedItem.createdAt)}
+ {metadataText && (
+ <span
+ className={`text-xs text-foreground-light${metadataCapitalize ? ' capitalize-sentence' : ''}`}
+ >
+ {metadataText}
</span>
)}
</div>
diff --git a/apps/studio/components/ui/AdvisorPanel/AdvisorSignalDetail.tsx b/apps/studio/components/ui/AdvisorPanel/AdvisorSignalDetail.tsx
new file mode 100644
index 00000000000..2e6127b13df
--- /dev/null
+++ b/apps/studio/components/ui/AdvisorPanel/AdvisorSignalDetail.tsx
@@ -0,0 +1,107 @@
+import { useParams } from 'common'
+import { EyeOff, Globe } from 'lucide-react'
+import Link from 'next/link'
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+
+import type { AdvisorSignalItem } from './AdvisorPanel.types'
+import { useAdvisorSignals } from './useAdvisorSignals'
+import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
+import { AiAssistantDropdown } from '@/components/ui/AiAssistantDropdown'
+import { InlineLink } from '@/components/ui/InlineLink'
+import { useAdvisorStateSnapshot } from '@/state/advisor-state'
+import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
+import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
+
+interface AdvisorSignalDetailProps {
+ item: AdvisorSignalItem
+}
+
+const buildSignalAssistantPrompt = (item: AdvisorSignalItem) => {
+ return [
+ `I'm reviewing an Advisor signal for a banned IP address: ${item.sourceData.ip}.`,
+ item.description ?? item.summary,
+ 'Help me assess whether this ban should remain in place, what I should investigate before removing it, and what the safest next step is.',
+ 'Please include when it is reasonable to dismiss this signal versus remove the ban.',
+ ].join('\n\n')
+}
+
+export const AdvisorSignalDetail = ({ item }: AdvisorSignalDetailProps) => {
+ const { ref: projectRef } = useParams()
+
+ const snap = useAiAssistantStateSnapshot()
+ const { openSidebar } = useSidebarManagerSnapshot()
+ const { setSelectedItem } = useAdvisorStateSnapshot()
+ const { dismissSignal } = useAdvisorSignals({ projectRef })
+
+ const issueDescription = (
+ <>
+ The IP address <code className="text-code-inline">{item.sourceData.ip}</code> is temporarily
+ blocked because of suspicious traffic or repeated failed password attempts. If this block is
+ expected, you can dismiss this signal or remove the ban.
+ </>
+ )
+
+ const handleAskAssistant = () => {
+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
+ snap.newChat({
+ name: `Review ${item.title.toLowerCase()}`,
+ initialInput: buildSignalAssistantPrompt(item),
+ })
+ }
+
+ const onDismissSignal = () => {
+ dismissSignal(item.dismissalKey)
+ setSelectedItem(undefined)
+ }
+
+ return (
+ <div>
+ <h3 className="text-sm mb-2">Entity</h3>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="flex items-center gap-2 px-2 py-0.5 bg-surface-200 border rounded-lg text-sm mb-6 w-fit">
+ <span className="flex items-center text-foreground-muted" aria-hidden="true">
+ <Globe size={15} className="text-foreground-muted" />
+ </span>
+ <span>{item.sourceData.ip}</span>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">IP address currently blocked by network bans</TooltipContent>
+ </Tooltip>
+
+ <h3 className="text-sm mb-2">Issue</h3>
+ <p className="text-sm text-foreground-light mb-6">
+ {issueDescription}{' '}
+ {item.docsUrl !== undefined && (
+ <>
+ <InlineLink href={item.docsUrl}>Learn more</InlineLink>.
+ </>
+ )}
+ </p>
+
+ <h3 className="text-sm mb-2">Resolve</h3>
+ <div className="flex items-center gap-2">
+ <AiAssistantDropdown
+ label="Ask Assistant"
+ buildPrompt={() => buildSignalAssistantPrompt(item)}
+ onOpenAssistant={handleAskAssistant}
+ telemetrySource="advisor_signal_detail"
+ />
+ {item.actions.map((action) => (
+ <Button key={`${item.dismissalKey}-${action.href}`} type="default" asChild>
+ <Link href={action.href}>
+ <span className="flex items-center gap-2">{action.label}</span>
+ </Link>
+ </Button>
+ ))}
+ <Button
+ type="default"
+ icon={<EyeOff size={14} strokeWidth={1.5} />}
+ onClick={onDismissSignal}
+ >
+ Dismiss
+ </Button>
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/ui/AdvisorPanel/AdvisorSignals.integration.test.tsx b/apps/studio/components/ui/AdvisorPanel/AdvisorSignals.integration.test.tsx
new file mode 100644
index 00000000000..f8f84356d00
--- /dev/null
+++ b/apps/studio/components/ui/AdvisorPanel/AdvisorSignals.integration.test.tsx
@@ -0,0 +1,280 @@
+import { screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { AdvisorSection } from '@/components/interfaces/ProjectHome/AdvisorSection'
+import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
+import { AdvisorPanel } from '@/components/ui/AdvisorPanel/AdvisorPanel'
+import { advisorState } from '@/state/advisor-state'
+import { sidebarManagerState } from '@/state/sidebar-manager-state'
+import { render } from '@/tests/helpers'
+
+const {
+ mockUseProjectLintsQuery,
+ mockUseBannedIPsQuery,
+ mockUseSelectedProjectQuery,
+ mockUseNotificationsV2Query,
+ mockUseNotificationsV2UpdateMutation,
+ mockUseTrack,
+} = vi.hoisted(() => ({
+ mockUseProjectLintsQuery: vi.fn(),
+ mockUseBannedIPsQuery: vi.fn(),
+ mockUseSelectedProjectQuery: vi.fn(),
+ mockUseNotificationsV2Query: vi.fn(),
+ mockUseNotificationsV2UpdateMutation: vi.fn(),
+ mockUseTrack: vi.fn(),
+}))
+
+vi.mock('common', async () => {
+ const actual = await vi.importActual<typeof import('common')>('common')
+
+ return {
+ ...actual,
+ useParams: () => ({ ref: 'project-ref' }),
+ }
+})
+
+vi.mock('@/data/lint/lint-query', () => ({
+ useProjectLintsQuery: mockUseProjectLintsQuery,
+}))
+
+vi.mock('@/data/banned-ips/banned-ips-query', () => ({
+ useBannedIPsQuery: mockUseBannedIPsQuery,
+}))
+
+vi.mock('@/hooks/misc/useSelectedProject', () => ({
+ useSelectedProjectQuery: mockUseSelectedProjectQuery,
+}))
+
+vi.mock('@/data/notifications/notifications-v2-query', () => ({
+ useNotificationsV2Query: mockUseNotificationsV2Query,
+}))
+
+vi.mock('@/data/notifications/notifications-v2-update-mutation', () => ({
+ useNotificationsV2UpdateMutation: mockUseNotificationsV2UpdateMutation,
+}))
+
+vi.mock('@/lib/constants', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/constants')>()),
+ IS_PLATFORM: true,
+}))
+
+vi.mock('@/lib/telemetry/track', () => ({
+ useTrack: mockUseTrack,
+}))
+
+vi.mock('@/state/ai-assistant-state', () => ({
+ useAiAssistantStateSnapshot: () => ({
+ newChat: vi.fn(),
+ }),
+}))
+
+vi.mock('@/components/ui/AiAssistantDropdown', () => ({
+ AiAssistantDropdown: () => <div data-testid="advisor-assistant-dropdown" />,
+}))
+
+vi.mock('./AdvisorFilters', () => ({
+ AdvisorFilters: () => <div data-testid="advisor-filters" />,
+}))
+
+vi.mock('./AdvisorPanelHeader', () => ({
+ AdvisorPanelHeader: () => <div data-testid="advisor-panel-header" />,
+}))
+
+describe('Advisor signals integration', () => {
+ beforeEach(() => {
+ window.localStorage.clear()
+ advisorState.reset()
+ sidebarManagerState.unregisterSidebar(SIDEBAR_KEYS.ADVISOR_PANEL)
+ sidebarManagerState.registerSidebar(SIDEBAR_KEYS.ADVISOR_PANEL, () => null)
+ sidebarManagerState.clearActiveSidebar()
+
+ mockUseTrack.mockReturnValue(vi.fn())
+ mockUseSelectedProjectQuery.mockReturnValue({
+ data: { ref: 'project-ref' },
+ })
+ mockUseProjectLintsQuery.mockImplementation((_variables, options) => {
+ if (options?.enabled === false) {
+ return {
+ data: undefined,
+ isPending: false,
+ isError: false,
+ }
+ }
+
+ return {
+ data: [
+ {
+ cache_key: 'lint-1',
+ name: 'unknown_lint',
+ detail: 'Critical lint detail',
+ level: 'ERROR',
+ categories: ['SECURITY'],
+ metadata: {},
+ },
+ ],
+ isPending: false,
+ isError: false,
+ }
+ })
+ mockUseBannedIPsQuery.mockImplementation((_variables, options) => {
+ if (options?.enabled === false) {
+ return {
+ data: undefined,
+ isPending: false,
+ isError: false,
+ }
+ }
+
+ return {
+ data: {
+ banned_ipv4_addresses: ['203.0.113.10'],
+ },
+ isPending: false,
+ isError: false,
+ }
+ })
+ mockUseNotificationsV2Query.mockReturnValue({
+ data: { pages: [[]] },
+ isPending: false,
+ isError: false,
+ })
+ mockUseNotificationsV2UpdateMutation.mockReturnValue({
+ mutate: vi.fn(),
+ })
+ })
+
+ afterEach(() => {
+ advisorState.reset()
+ sidebarManagerState.unregisterSidebar(SIDEBAR_KEYS.ADVISOR_PANEL)
+ sidebarManagerState.clearActiveSidebar()
+ vi.clearAllMocks()
+ })
+
+ it('renders signal items and dismisses them across the homepage and panel', async () => {
+ render(
+ <>
+ <AdvisorSection />
+ <AdvisorPanel />
+ </>
+ )
+
+ expect(screen.getByText('Advisor found 2 issues')).toBeInTheDocument()
+ expect(screen.getByText('Banned IP address')).toBeInTheDocument()
+ expect(screen.getAllByText('Critical lint detail').length).toBeGreaterThan(0)
+ expect(
+ screen.getAllByText((_, node) =>
+ Boolean(
+ node?.textContent?.includes(
+ 'The IP address 203.0.113.10 is temporarily blocked because of suspicious traffic or repeated failed password attempts.'
+ )
+ )
+ ).length
+ ).toBeGreaterThan(0)
+
+ await userEvent.click(screen.getByText('Banned IP address'))
+
+ expect(screen.getByText('Entity')).toBeInTheDocument()
+ expect(screen.getByText('Issue')).toBeInTheDocument()
+ expect(screen.getByText('Resolve')).toBeInTheDocument()
+ expect(screen.getAllByTestId('advisor-assistant-dropdown').length).toBeGreaterThan(0)
+ expect(
+ screen.getAllByText((_, node) =>
+ Boolean(
+ node?.textContent?.includes(
+ 'The IP address 203.0.113.10 is temporarily blocked because of suspicious traffic or repeated failed password attempts.'
+ )
+ )
+ ).length
+ ).toBeGreaterThan(0)
+ expect(screen.getByRole('link', { name: 'Learn more' })).toHaveAttribute(
+ 'href',
+ 'https://supabase.com/docs/reference/cli/supabase-network-bans'
+ )
+
+ expect(screen.getAllByText('Banned IP address').length).toBeGreaterThan(0)
+
+ await userEvent.click(screen.getByRole('button', { name: 'Dismiss' }))
+
+ await waitFor(() => {
+ expect(screen.queryByText('Banned IP address')).not.toBeInTheDocument()
+ })
+
+ expect(screen.getAllByText('Critical lint detail').length).toBeGreaterThan(0)
+ })
+
+ it('shows an overflow affordance when the homepage cap hides additional issues', () => {
+ mockUseProjectLintsQuery.mockImplementation((_variables, options) => {
+ if (options?.enabled === false) {
+ return {
+ data: undefined,
+ isPending: false,
+ isError: false,
+ }
+ }
+
+ return {
+ data: [
+ {
+ cache_key: 'lint-1',
+ name: 'unknown_lint',
+ detail: 'Critical lint detail 1',
+ level: 'ERROR',
+ categories: ['SECURITY'],
+ metadata: {},
+ },
+ {
+ cache_key: 'lint-2',
+ name: 'unknown_lint',
+ detail: 'Critical lint detail 2',
+ level: 'ERROR',
+ categories: ['SECURITY'],
+ metadata: {},
+ },
+ {
+ cache_key: 'lint-3',
+ name: 'unknown_lint',
+ detail: 'Critical lint detail 3',
+ level: 'ERROR',
+ categories: ['SECURITY'],
+ metadata: {},
+ },
+ {
+ cache_key: 'lint-4',
+ name: 'unknown_lint',
+ detail: 'Critical lint detail 4',
+ level: 'ERROR',
+ categories: ['SECURITY'],
+ metadata: {},
+ },
+ ],
+ isPending: false,
+ isError: false,
+ }
+ })
+
+ render(<AdvisorSection />)
+
+ expect(screen.getByText('Advisor found 5 issues')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'View 1 more issue in Advisor' })).toBeInTheDocument()
+ expect(screen.queryByText('Banned IP address')).not.toBeInTheDocument()
+ })
+
+ it('does not block the homepage while signal items are pending', () => {
+ mockUseProjectLintsQuery.mockReturnValue({
+ data: [],
+ isPending: false,
+ isError: false,
+ })
+ mockUseBannedIPsQuery.mockReturnValue({
+ data: undefined,
+ isPending: true,
+ isError: false,
+ })
+
+ render(<AdvisorSection />)
+
+ // Lints have loaded — homepage renders without being blocked by signal loading
+ expect(screen.getByText('Advisor found no issues')).toBeInTheDocument()
+ })
+})
diff --git a/apps/studio/components/ui/AdvisorPanel/EmptyAdvisor.tsx b/apps/studio/components/ui/AdvisorPanel/EmptyAdvisor.tsx
index 5032cea79c4..509dec8e1b7 100644
--- a/apps/studio/components/ui/AdvisorPanel/EmptyAdvisor.tsx
+++ b/apps/studio/components/ui/AdvisorPanel/EmptyAdvisor.tsx
@@ -1,7 +1,7 @@
import { TextSearch } from 'lucide-react'
import { Button } from 'ui'
-import { AdvisorTab } from '@/state/advisor-state'
+import type { AdvisorTab } from '@/state/advisor-state'
interface EmptyAdvisorProps {
activeTab: AdvisorTab
@@ -41,11 +41,11 @@ export const EmptyAdvisor = ({ activeTab, hasFilters, onClearFilters }: EmptyAdv
}
return (
- <div className="absolute top-28 px-6 flex flex-col items-center justify-center w-full gap-y-2">
+ <div className="h-full px-6 flex flex-col items-center justify-center w-full gap-y-2">
<TextSearch className="text-foreground-muted" strokeWidth={1} />
- <div className="text-center">
- <p className="heading-default">{getHeading()}</p>
- <p className="text-foreground-light text-sm">{getMessage()}</p>
+ <div className="flex flex-col items-center gap-y-0.5 text-center">
+ <h3 className="heading-default">{getHeading()}</h3>
+ <p className="text-foreground-light text-sm text-balance">{getMessage()}</p>
</div>
{hasFilters && (
<Button type="outline" onClick={onClearFilters}>
diff --git a/apps/studio/components/ui/AdvisorPanel/useAdvisorSignals.test.tsx b/apps/studio/components/ui/AdvisorPanel/useAdvisorSignals.test.tsx
new file mode 100644
index 00000000000..b14381b259f
--- /dev/null
+++ b/apps/studio/components/ui/AdvisorPanel/useAdvisorSignals.test.tsx
@@ -0,0 +1,79 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { PropsWithChildren } from 'react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { useAdvisorSignals } from './useAdvisorSignals'
+
+const { mockUseBannedIPsQuery } = vi.hoisted(() => ({
+ mockUseBannedIPsQuery: vi.fn(),
+}))
+
+vi.mock('@/data/banned-ips/banned-ips-query', () => ({
+ useBannedIPsQuery: mockUseBannedIPsQuery,
+}))
+
+const createWrapper = () => {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
+ })
+
+ return function Wrapper({ children }: PropsWithChildren) {
+ return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ }
+}
+
+describe('useAdvisorSignals', () => {
+ beforeEach(() => {
+ window.localStorage.clear()
+ vi.clearAllMocks()
+ })
+
+ it('resurfaces a dismissed banned-IP signal after the IP disappears and is banned again', async () => {
+ let bannedIPs = ['203.0.113.10']
+
+ mockUseBannedIPsQuery.mockImplementation(() => ({
+ data: {
+ banned_ipv4_addresses: bannedIPs,
+ },
+ isPending: false,
+ isError: false,
+ }))
+
+ const { result, rerender } = renderHook(
+ () => useAdvisorSignals({ projectRef: 'project-ref' }),
+ {
+ wrapper: createWrapper(),
+ }
+ )
+
+ expect(result.current.data).toHaveLength(1)
+
+ act(() => {
+ result.current.dismissSignal('signal:banned-ip:203.0.113.10:v1')
+ })
+
+ await waitFor(() => {
+ expect(result.current.data).toEqual([])
+ })
+
+ bannedIPs = []
+ rerender()
+
+ await waitFor(() => {
+ expect(window.localStorage.getItem('advisor-signal-dismissals:project-ref')).toBe('[]')
+ })
+
+ bannedIPs = ['203.0.113.10']
+ rerender()
+
+ await waitFor(() => {
+ expect(result.current.data).toHaveLength(1)
+ expect(result.current.data[0].sourceData.ip).toBe('203.0.113.10')
+ })
+ })
+})
diff --git a/apps/studio/components/ui/AdvisorPanel/useAdvisorSignals.ts b/apps/studio/components/ui/AdvisorPanel/useAdvisorSignals.ts
new file mode 100644
index 00000000000..d5ea84f9e42
--- /dev/null
+++ b/apps/studio/components/ui/AdvisorPanel/useAdvisorSignals.ts
@@ -0,0 +1,100 @@
+import { useCallback, useEffect, useMemo } from 'react'
+
+import type { AdvisorSignalItem } from './AdvisorPanel.types'
+import { useBannedIPsQuery } from '@/data/banned-ips/banned-ips-query'
+import type { IPData } from '@/data/banned-ips/banned-ips-query'
+import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
+
+const createDismissalStorageKey = (projectRef: string) => `advisor-signal-dismissals:${projectRef}`
+
+const createBannedIPDismissalKey = (ip: string) => `signal:banned-ip:${ip}:v1`
+
+const createBannedIPSignalItems = ({
+ projectRef,
+ bannedIPsData,
+}: {
+ projectRef?: string
+ bannedIPsData?: IPData
+}): AdvisorSignalItem[] => {
+ if (!projectRef) return []
+
+ const bannedIPs = bannedIPsData?.banned_ipv4_addresses ?? []
+
+ return bannedIPs.map((ip) => ({
+ id: createBannedIPDismissalKey(ip),
+ dismissalKey: createBannedIPDismissalKey(ip),
+ source: 'signal' as const,
+ type: 'banned-ip' as const,
+ severity: 'warning' as const,
+ tab: 'security' as const,
+ title: 'Banned IP address',
+ summary: `The IP address \`${ip}\` is temporarily blocked because of suspicious traffic or repeated failed password attempts.`,
+ description:
+ 'This IP address is temporarily blocked because of suspicious traffic or repeated failed password attempts. If this block is expected, you can dismiss this signal or remove the ban.',
+ docsUrl: 'https://supabase.com/docs/reference/cli/supabase-network-bans',
+ actions: [
+ {
+ label: 'Edit network bans',
+ href: `/project/${projectRef}/database/settings#banned-ips`,
+ },
+ ],
+ sourceData: { type: 'banned-ip' as const, ip },
+ }))
+}
+
+interface UseAdvisorSignalsOptions {
+ projectRef?: string
+ enabled?: boolean
+}
+
+export const useAdvisorSignals = ({ projectRef, enabled = true }: UseAdvisorSignalsOptions) => {
+ const { data, isPending, isError } = useBannedIPsQuery({ projectRef }, { enabled })
+
+ const storageKey = projectRef
+ ? createDismissalStorageKey(projectRef)
+ : 'advisor-signal-dismissals:unknown-project'
+
+ const [dismissedKeys, setDismissedKeys] = useLocalStorageQuery<string[]>(storageKey, [])
+
+ const dismissedKeySet = useMemo(() => new Set(dismissedKeys), [dismissedKeys])
+
+ const dismissSignal = useCallback(
+ (dismissalKey: string) => {
+ setDismissedKeys((current) =>
+ current.includes(dismissalKey) ? current : [...current, dismissalKey]
+ )
+ },
+ [setDismissedKeys]
+ )
+
+ const signalItems = useMemo(
+ () => createBannedIPSignalItems({ projectRef, bannedIPsData: data }),
+ [projectRef, data]
+ )
+
+ // Prune stale dismissals when the active signal list changes (e.g. an IP was unbanned)
+ useEffect(() => {
+ if (!data) return
+
+ const activeKeys = new Set(signalItems.map((item) => item.dismissalKey))
+
+ setDismissedKeys((current) => {
+ const next = current.filter((key) =>
+ key.startsWith('signal:banned-ip:') ? activeKeys.has(key) : true
+ )
+ return next.length === current.length ? current : next
+ })
+ }, [data, signalItems, setDismissedKeys])
+
+ const formattedData = useMemo(
+ () => signalItems.filter((item) => !dismissedKeySet.has(item.dismissalKey)),
+ [signalItems, dismissedKeySet]
+ )
+
+ return {
+ data: formattedData,
+ dismissSignal,
+ isPending,
+ isError,
+ }
+}
diff --git a/apps/studio/data/banned-ips/banned-ips-query.ts b/apps/studio/data/banned-ips/banned-ips-query.ts
index 93f2d6f2841..13a9f5dbcfc 100644
--- a/apps/studio/data/banned-ips/banned-ips-query.ts
+++ b/apps/studio/data/banned-ips/banned-ips-query.ts
@@ -1,17 +1,13 @@
import { useQuery } from '@tanstack/react-query'
+import { IS_PLATFORM } from 'common'
import { BannedIPKeys } from './keys'
import { handleError, post } from '@/data/fetchers'
import type { ResponseError, UseCustomQueryOptions } from '@/types'
-export type BannedIPVariables = {
- projectRef?: string
-}
-
-export type BannedIPsData = BannedIPVariables[]
-export type BannedIPsError = ResponseError
+type BannedIPVariables = { projectRef?: string }
-export async function getBannedIPs({ projectRef }: BannedIPVariables, signal?: AbortSignal) {
+export async function getBannedIPs({ projectRef }: BannedIPVariables, signal: AbortSignal) {
if (!projectRef) throw new Error('projectRef is required')
const { data, error } = await post(`/v1/projects/{ref}/network-bans/retrieve`, {
@@ -33,6 +29,9 @@ export const useBannedIPsQuery = <TData = IPData>(
useQuery<IPData, IPError, TData>({
queryKey: BannedIPKeys.list(projectRef),
queryFn: ({ signal }) => getBannedIPs({ projectRef }, signal),
- enabled: enabled && typeof projectRef !== 'undefined',
+ enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined',
+ retry: false,
+ refetchOnWindowFocus: false,
+ staleTime: 60_000,
...options,
})
diff --git a/apps/studio/hooks/misc/__tests__/useLocalStorageQuery.test.ts b/apps/studio/hooks/misc/__tests__/useLocalStorageQuery.test.ts
new file mode 100644
index 00000000000..44b163141a3
--- /dev/null
+++ b/apps/studio/hooks/misc/__tests__/useLocalStorageQuery.test.ts
@@ -0,0 +1,113 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import React from 'react'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+
+import { useLocalStorageQuery } from '../useLocalStorage'
+import { customRenderHook } from '@/tests/lib/custom-render'
+
+function makeQueryClient() {
+ return new QueryClient({ defaultOptions: { queries: { retry: false } } })
+}
+
+function makeWrapper(queryClient: QueryClient) {
+ return ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client: queryClient }, children)
+}
+
+describe('useLocalStorageQuery', () => {
+ beforeEach(() => {
+ window.localStorage.clear()
+ })
+
+ afterEach(() => {
+ window.localStorage.clear()
+ })
+
+ it('returns initialValue when localStorage has no entry for the key', async () => {
+ const { result } = customRenderHook(() => useLocalStorageQuery('test-key', 'default'))
+
+ await waitFor(() => expect(result.current[2].isSuccess).toBe(true))
+ expect(result.current[0]).toBe('default')
+ })
+
+ it('returns the stored value from localStorage on mount', async () => {
+ window.localStorage.setItem('test-key', JSON.stringify('persisted'))
+
+ const { result } = customRenderHook(() => useLocalStorageQuery('test-key', 'default'))
+
+ await waitFor(() => expect(result.current[0]).toBe('persisted'))
+ })
+
+ it('updates the value in state and localStorage when setValue is called', async () => {
+ const { result } = customRenderHook(() => useLocalStorageQuery('test-key', 'default'))
+ await waitFor(() => expect(result.current[2].isSuccess).toBe(true))
+
+ act(() => {
+ result.current[1]('updated')
+ })
+
+ await waitFor(() => expect(result.current[0]).toBe('updated'))
+ expect(window.localStorage.getItem('test-key')).toBe(JSON.stringify('updated'))
+ })
+
+ it('supports a function updater that receives the current value', async () => {
+ window.localStorage.setItem('count', JSON.stringify(5))
+
+ const { result } = customRenderHook(() => useLocalStorageQuery('count', 0))
+ await waitFor(() => expect(result.current[0]).toBe(5))
+
+ act(() => {
+ result.current[1]((prev: number) => prev + 1)
+ })
+
+ await waitFor(() => expect(result.current[0]).toBe(6))
+ expect(window.localStorage.getItem('count')).toBe(JSON.stringify(6))
+ })
+
+ it('works with object values', async () => {
+ const stored = { count: 3, label: 'hello' }
+ window.localStorage.setItem('obj-key', JSON.stringify(stored))
+
+ const { result } = customRenderHook(() =>
+ useLocalStorageQuery('obj-key', { count: 0, label: '' })
+ )
+
+ await waitFor(() => expect(result.current[0]).toEqual(stored))
+ })
+
+ it('syncs two hooks sharing the same key via the same QueryClient', async () => {
+ const queryClient = makeQueryClient()
+
+ const { result } = renderHook(
+ () => ({
+ a: useLocalStorageQuery('shared-key', 'initial'),
+ b: useLocalStorageQuery('shared-key', 'initial'),
+ }),
+ { wrapper: makeWrapper(queryClient) }
+ )
+
+ await waitFor(() => expect(result.current.a[2].isSuccess).toBe(true))
+
+ act(() => {
+ result.current.a[1]('from-a')
+ })
+
+ await waitFor(() => {
+ expect(result.current.a[0]).toBe('from-a')
+ expect(result.current.b[0]).toBe('from-a')
+ })
+ })
+
+ it('uses the initialValue as fallback when the function updater runs before any stored value', async () => {
+ const { result } = customRenderHook(() => useLocalStorageQuery('new-key', 10))
+ await waitFor(() => expect(result.current[2].isSuccess).toBe(true))
+
+ act(() => {
+ result.current[1]((prev: number) => prev * 2)
+ })
+
+ await waitFor(() => expect(result.current[0]).toBe(20))
+ expect(window.localStorage.getItem('new-key')).toBe(JSON.stringify(20))
+ })
+})
diff --git a/apps/studio/hooks/misc/useLongRunningTransitionState.test.ts b/apps/studio/hooks/misc/__tests__/useLongRunningTransitionState.test.ts
similarity index 94%
rename from apps/studio/hooks/misc/useLongRunningTransitionState.test.ts
rename to apps/studio/hooks/misc/__tests__/useLongRunningTransitionState.test.ts
index e3a09d58266..d770446353c 100644
--- a/apps/studio/hooks/misc/useLongRunningTransitionState.test.ts
+++ b/apps/studio/hooks/misc/__tests__/useLongRunningTransitionState.test.ts
@@ -1,7 +1,7 @@
import { act, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { useLongRunningTransitionState } from './useLongRunningTransitionState'
+import { useLongRunningTransitionState } from '../useLongRunningTransitionState'
describe('useLongRunningTransitionState', () => {
beforeEach(() => {
diff --git a/apps/studio/hooks/misc/useTableEditorFiltersSort.test.ts b/apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.test.ts
similarity index 96%
rename from apps/studio/hooks/misc/useTableEditorFiltersSort.test.ts
rename to apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.test.ts
index bd12380c08d..0361f295f33 100644
--- a/apps/studio/hooks/misc/useTableEditorFiltersSort.test.ts
+++ b/apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.test.ts
@@ -3,7 +3,7 @@ import { useRouter } from 'next/router'
import { withNuqsTestingAdapter } from 'nuqs/adapters/testing'
import { beforeAll, describe, expect, it, vi } from 'vitest'
-import { useTableEditorFiltersSort } from './useTableEditorFiltersSort'
+import { useTableEditorFiltersSort } from '../useTableEditorFiltersSort'
beforeAll(() => {
vi.mock('next/router', () => import('next-router-mock'))
diff --git a/apps/studio/hooks/misc/useLocalStorage.ts b/apps/studio/hooks/misc/useLocalStorage.ts
index 9b385839df1..f9fa942195a 100644
--- a/apps/studio/hooks/misc/useLocalStorage.ts
+++ b/apps/studio/hooks/misc/useLocalStorage.ts
@@ -1,7 +1,7 @@
// Reference: https://usehooks.com/useLocalStorage/
import { useQuery, useQueryClient } from '@tanstack/react-query'
-import { Dispatch, SetStateAction, useCallback, useState } from 'react'
+import { Dispatch, SetStateAction, useCallback, useMemo, useState } from 'react'
export function useLocalStorage<T>(key: string, initialValue: T) {
// State to store our value
@@ -56,7 +56,7 @@ export function useLocalStorage<T>(key: string, initialValue: T) {
*/
export function useLocalStorageQuery<T>(key: string, initialValue: T) {
const queryClient = useQueryClient()
- const queryKey = ['localStorage', key]
+ const queryKey = useMemo(() => ['localStorage', key], [key])
const {
error,
@@ -81,16 +81,25 @@ export function useLocalStorageQuery<T>(key: string, initialValue: T) {
},
})
- const setValue: Dispatch<SetStateAction<T>> = (value) => {
- const valueToStore = value instanceof Function ? value(storedValue) : value
+ const setValue: Dispatch<SetStateAction<T>> = useCallback(
+ (value) => {
+ const currentValue = queryClient.getQueryData<T>(queryKey) ?? initialValue
+ const valueToStore = value instanceof Function ? value(currentValue) : value
- if (typeof window !== 'undefined') {
- window.localStorage.setItem(key, JSON.stringify(valueToStore))
- }
+ if (typeof window !== 'undefined') {
+ window.localStorage.setItem(key, JSON.stringify(valueToStore))
+ }
- queryClient.setQueryData(queryKey, valueToStore)
- queryClient.invalidateQueries({ queryKey })
- }
+ queryClient.setQueryData(queryKey, valueToStore)
+ queryClient.invalidateQueries({ queryKey })
+ },
+ // initialValue is intentionally excluded: the function body reads the
+ // current value via queryClient.getQueryData so it doesn't close over
+ // initialValue reactively — including it would cause a new function
+ // reference every render when callers pass an inline literal (e.g. []).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [key, queryKey, queryClient]
+ )
return [storedValue, setValue, { isSuccess, isLoading, isError, error }] as const
}
diff --git a/apps/studio/state/advisor-state.ts b/apps/studio/state/advisor-state.ts
index 809bdfb8180..8bf49ba6a0b 100644
--- a/apps/studio/state/advisor-state.ts
+++ b/apps/studio/state/advisor-state.ts
@@ -2,7 +2,7 @@ import { proxy, snapshot, useSnapshot } from 'valtio'
export type AdvisorTab = 'all' | 'security' | 'performance' | 'messages'
export type AdvisorSeverity = 'critical' | 'warning' | 'info'
-export type AdvisorItemSource = 'lint' | 'notification'
+export type AdvisorItemSource = 'lint' | 'notification' | 'signal'
const initialState = {
activeTab: 'all' as AdvisorTab,
diff --git a/packages/common/telemetry-constants.ts b/packages/common/telemetry-constants.ts
index 44b90962571..7d677fd85b8 100644
--- a/packages/common/telemetry-constants.ts
+++ b/packages/common/telemetry-constants.ts
@@ -2567,7 +2567,7 @@ type AdvisorCategory = 'PERFORMANCE' | 'SECURITY'
type AdvisorLevel = 'ERROR' | 'WARN' | 'INFO'
/**
- * User opened an advisor detail page to view a specific advisor (lint or notification).
+ * User opened an advisor detail page to view a specific advisor (lint, notification, or signal).
* This tracks when users engage with advisor recommendations.
*
* @group Events
@@ -2584,7 +2584,7 @@ export interface AdvisorDetailOpenedEvent {
/**
* Source of the advisor
*/
- advisorSource: 'lint' | 'notification'
+ advisorSource: 'lint' | 'notification' | 'signal'
/**
* Category of the advisor (SECURITY or PERFORMANCE)
*/
@@ -2661,6 +2661,7 @@ export type AiAssistantSource =
| 'branch_review'
| 'log_explorer'
| 'error_code'
+ | 'advisor_signal_detail'
/**
* User copied an AI prompt to clipboard instead of using the built-in assistant.