@skyhook-io/radar-app 1.17.1 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/package.json +9 -9
  2. package/src/App.tsx +14 -30
  3. package/src/api/client.gitopsPoll.test.ts +99 -0
  4. package/src/api/client.helmPreview.test.tsx +48 -0
  5. package/src/api/client.resourceAvailability.test.ts +24 -0
  6. package/src/api/client.ts +337 -87
  7. package/src/api/client.workloadRuns.test.ts +53 -0
  8. package/src/api/config.test.ts +23 -1
  9. package/src/api/config.ts +7 -3
  10. package/src/api/diagnose.ts +4 -1
  11. package/src/api/drain-plan.test.ts +70 -40
  12. package/src/api/policy.ts +5 -5
  13. package/src/api/radarFeatures.ts +1 -0
  14. package/src/api/traffic.scope.render.test.tsx +60 -0
  15. package/src/api/traffic.ts +3 -1
  16. package/src/components/cnpg/CNPGSummaryHost.tsx +4 -3
  17. package/src/components/diagnose/DiagnoseSurface.tsx +3 -3
  18. package/src/components/diagnose/InvestigationChangesEvidence.test.tsx +352 -0
  19. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +101 -0
  20. package/src/components/diagnose/InvestigationView.tsx +2 -1
  21. package/src/components/diagnose/investigationEvidence/adapters/changes.test.ts +123 -0
  22. package/src/components/diagnose/investigationEvidence/adapters/changes.ts +192 -3
  23. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +73 -51
  24. package/src/components/diagnose/investigationEvidence/adapters/prometheus.ts +64 -2
  25. package/src/components/diagnose/investigationEvidence/adapters/resource.test.ts +37 -0
  26. package/src/components/diagnose/investigationEvidence/adapters/testdata/get-changes-created.json +323 -0
  27. package/src/components/diagnose/investigationEvidence/bodies/streams.tsx +144 -15
  28. package/src/components/diagnose/investigationEvidence/observations.ts +20 -0
  29. package/src/components/diagnose/investigationEvidence/parse.ts +57 -1
  30. package/src/components/diagnose/investigationEvidence/projection.test.ts +107 -0
  31. package/src/components/diagnose/investigationEvidence/types.ts +11 -0
  32. package/src/components/diagnose/investigationEvidencePresentation.test.ts +18 -0
  33. package/src/components/diagnose/investigationState.test.ts +36 -1
  34. package/src/components/diagnose/investigationState.ts +8 -0
  35. package/src/components/diagnose/launch.ts +2 -2
  36. package/src/components/dock/BottomDock.tsx +6 -3
  37. package/src/components/dock/WorkloadLogsTab.tsx +3 -0
  38. package/src/components/execution/BatchExecutionView.render.test.tsx +29 -1
  39. package/src/components/execution/BatchExecutionView.tsx +23 -8
  40. package/src/components/execution/cluster-template-runs.render.test.tsx +42 -0
  41. package/src/components/gitops/GitOpsView.tsx +7 -0
  42. package/src/components/helm/HelmReleaseDrawer.tsx +139 -55
  43. package/src/components/helm/HelmReleaseNotes.test.tsx +42 -0
  44. package/src/components/helm/HelmReleaseNotes.tsx +26 -0
  45. package/src/components/helm/OwnedResources.tsx +2 -2
  46. package/src/components/helm/TrackChartSourceDialog.render.test.tsx +76 -4
  47. package/src/components/helm/TrackChartSourceDialog.test.ts +3 -2
  48. package/src/components/helm/TrackChartSourceDialog.tsx +41 -15
  49. package/src/components/helm/ValuesDiffPreview.tsx +4 -1
  50. package/src/components/home/ClusterHealthCard.tsx +4 -4
  51. package/src/components/home/CostCard.test.tsx +100 -0
  52. package/src/components/home/CostCard.tsx +2 -2
  53. package/src/components/home/HelmSummary.tsx +2 -2
  54. package/src/components/home/HomeView.tsx +15 -6
  55. package/src/components/home/MCPSetupDialog.test.tsx +30 -0
  56. package/src/components/home/MCPSetupDialog.tsx +13 -6
  57. package/src/components/home/ProblemsPanel.test.tsx +1 -0
  58. package/src/components/home/mcpToolCatalog.ts +18 -2
  59. package/src/components/issues/IssuesPane.render.test.tsx +21 -0
  60. package/src/components/issues/IssuesPane.tsx +31 -7
  61. package/src/components/issues/UncheckedSourceHelp.test.tsx +42 -0
  62. package/src/components/issues/UncheckedSourceHelp.tsx +24 -0
  63. package/src/components/issues/uncheckedSources.test.ts +43 -0
  64. package/src/components/issues/uncheckedSources.ts +58 -5
  65. package/src/components/logs/ScheduledWorkloadLogsViewer.tsx +4 -2
  66. package/src/components/resources/ImageFilesystemModal.test.tsx +68 -0
  67. package/src/components/resources/ImageFilesystemModal.tsx +11 -4
  68. package/src/components/resources/PodFilesystemModal.tsx +2 -2
  69. package/src/components/resources/ResourcesView.scope.render.test.tsx +58 -0
  70. package/src/components/resources/ResourcesView.tsx +18 -3
  71. package/src/components/resources/renderers/FluxHelmReleaseRenderer.test.tsx +111 -0
  72. package/src/components/resources/renderers/FluxHelmReleaseRenderer.tsx +67 -0
  73. package/src/components/resources/renderers/KyvernoPolicyCoverage.scope.render.test.tsx +64 -0
  74. package/src/components/resources/renderers/KyvernoPolicyCoverage.tsx +6 -7
  75. package/src/components/settings/SettingsDialog.tsx +21 -15
  76. package/src/components/traffic/TrafficFilterSidebar.test.tsx +77 -0
  77. package/src/components/traffic/TrafficFilterSidebar.tsx +42 -31
  78. package/src/components/traffic/TrafficView.tsx +12 -12
  79. package/src/components/traffic/trafficFilters.test.ts +20 -1
  80. package/src/components/traffic/trafficFilters.ts +13 -0
  81. package/src/components/ui/Omnibar.tsx +13 -2
  82. package/src/components/ui/Toast.tsx +1 -1
  83. package/src/components/ui/omnibar-match.test.ts +30 -0
  84. package/src/components/ui/omnibar-match.ts +18 -0
  85. package/src/components/workload/CronJobSchedulingEvidence.test.tsx +35 -0
  86. package/src/components/workload/CronJobSchedulingEvidence.tsx +37 -0
  87. package/src/components/workload/NodeDrainStatus.test.tsx +253 -0
  88. package/src/components/workload/NodeDrainStatus.tsx +55 -0
  89. package/src/components/workload/WorkloadView.tsx +37 -5
  90. package/src/context/ConnectionContext.test.ts +27 -1
  91. package/src/context/ConnectionContext.tsx +17 -7
  92. package/src/integrations/resourceHosts.test.tsx +1 -0
  93. package/src/integrations/resourceHosts.tsx +2 -0
  94. package/src/utils/navigation.ts +14 -0
  95. package/src/utils/wails-clipboard.ts +4 -2
@@ -1,9 +1,10 @@
1
1
  import { useState, useMemo, useCallback } from 'react'
2
2
  import { useLocation, useNavigate } from 'react-router-dom'
3
3
  import { useQuery } from '@tanstack/react-query'
4
- import { ApiError, debugNamespaceLog, fetchJSON, isForbiddenError, isKindSyncFailed, isStillLoadingError, useCapabilities, useNamespaceCapabilities, useResources, useSecretCertExpiry, useTopPodMetrics, useTopNodeMetrics, useBulkDeleteResources, useBulkRestartWorkloads, useBulkScaleWorkloads, useAudit } from '../../api/client'
4
+ import { ApiError, debugNamespaceLog, fetchJSON, isForbiddenError, isKindSyncFailed, isStillLoadingError, useCapabilities, useNamespaceCapabilities, useResources, useSecretCertExpiry, useTopPodMetrics, useTopNodeMetrics, useBulkDeleteResources, useBulkRestartWorkloads, useBulkScaleWorkloads, useAudit, useIssues } from '../../api/client'
5
5
  import { isBadgeWorthy } from '../../utils/auditBadges'
6
- import type { AuditBadgeMessage } from '@skyhook-io/k8s-ui'
6
+ import { ISSUE_SEVERITY_RANK } from '@skyhook-io/k8s-ui'
7
+ import type { Issue, AuditBadgeMessage } from '@skyhook-io/k8s-ui'
7
8
  import { apiUrl, getAuthHeaders, getCredentialsMode, stripBasename } from '../../api/config'
8
9
  import { readErrorBody } from '../../api/httpErrors'
9
10
  import { useAPIResources } from '../../api/apiResources'
@@ -111,6 +112,18 @@ export function ResourcesView({ namespaces, selectedResource, onResourceClick, o
111
112
 
112
113
  // Track the selected kind from the k8s-ui component
113
114
  const [selectedKind, setSelectedKind] = useState<SelectedKindInfo>(null)
115
+ const { data: issuesData } = useIssues(namespaces, selectedKind?.group === 'batch' && selectedKind?.name === 'cronjobs', 'CronJob')
116
+ const operationalIssues = useMemo(() => {
117
+ const result: Record<string, Issue> = {}
118
+ for (const issue of issuesData?.issues ?? []) {
119
+ if (issue.kind !== 'CronJob' || issue.group !== 'batch') continue
120
+ const key = `${issue.namespace ?? ''}/${issue.name}`
121
+ const previous = result[key]
122
+ if (!previous || ISSUE_SEVERITY_RANK[issue.severity] > ISSUE_SEVERITY_RANK[previous.severity] ||
123
+ (issue.severity === previous.severity && issue.id < previous.id)) result[key] = issue
124
+ }
125
+ return result
126
+ }, [issuesData])
114
127
  const cnpgSidebarWorkspace = useCNPGSidebarWorkspace({ apiResources, namespaces, withMetrics: selectedKind?.group === 'postgresql.cnpg.io' })
115
128
  const workloadWrites = namespaces.length === 0
116
129
  ? capabilities?.workloadWrites
@@ -314,7 +327,7 @@ export function ResourcesView({ namespaces, selectedResource, onResourceClick, o
314
327
  const { data: topNodeMetrics } = useTopNodeMetrics({ enabled: topNodeMetricsEnabled })
315
328
 
316
329
  // Certificate expiry
317
- const { data: certExpiry, isError: certExpiryError } = useSecretCertExpiry()
330
+ const { data: certExpiry, isError: certExpiryError } = useSecretCertExpiry(namespaces)
318
331
 
319
332
  // An ExternalSecret names a store; only the store says which backend it reads
320
333
  // from. Two list calls per page beat one lookup per row, and the column shows
@@ -426,6 +439,8 @@ export function ResourcesView({ namespaces, selectedResource, onResourceClick, o
426
439
  certExpiry={certExpiry}
427
440
  storeProviders={storeProviders}
428
441
  certExpiryError={certExpiryError}
442
+ operationalIssues={operationalIssues}
443
+ operationalIssuesIncomplete={Boolean(issuesData && (issuesData.total_matched ?? issuesData.total ?? issuesData.issues.length) > issuesData.issues.length)}
429
444
  auditBadges={auditBadges}
430
445
  // Pinned kinds
431
446
  pinned={pinned}
@@ -0,0 +1,111 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5
+ import type { FluxValuesReference } from '@skyhook-io/k8s-ui/components/resources/renderers/FluxHelmReleaseRenderer'
6
+ import { FluxHelmReleaseRenderer } from './FluxHelmReleaseRenderer'
7
+
8
+ const query = vi.hoisted(() => ({
9
+ data: undefined as 'present' | 'missing' | 'unchecked' | undefined,
10
+ error: null as Error & { status?: number } | null,
11
+ isLoading: false,
12
+ isFetching: false,
13
+ refetch: vi.fn(),
14
+ }))
15
+ const lookup = vi.hoisted(() => vi.fn())
16
+ vi.mock('../../../api/client', () => ({
17
+ useResourceAvailability: (...args: unknown[]) => { lookup(...args); return query },
18
+ isForbiddenError: (error: unknown) => error instanceof Error && 'status' in error && error.status === 403,
19
+ }))
20
+
21
+ let container: HTMLDivElement
22
+ let root: Root
23
+ const navigate = vi.fn()
24
+
25
+ beforeEach(() => {
26
+ container = document.createElement('div')
27
+ document.body.append(container)
28
+ root = createRoot(container)
29
+ Object.assign(query, { data: undefined, error: null, isLoading: false, isFetching: false })
30
+ vi.clearAllMocks()
31
+ })
32
+ afterEach(async () => {
33
+ await act(async () => root.unmount())
34
+ container.remove()
35
+ })
36
+
37
+ async function render(reference: FluxValuesReference = { name: 'overrides', optional: true }) {
38
+ await act(async () => root.render(<FluxHelmReleaseRenderer
39
+ data={{ metadata: { namespace: 'apps' }, spec: { valuesFrom: [reference] } }}
40
+ onNavigate={navigate}
41
+ />))
42
+ }
43
+
44
+ function referenceButton() {
45
+ return [...container.querySelectorAll('button')].find(button => button.textContent === 'overrides')
46
+ }
47
+
48
+ describe('Flux Helm values references', () => {
49
+ it.each(['ConfigMap', 'Secret'] as const)('labels an absent optional %s and does not link it', async kind => {
50
+ query.data = 'missing'
51
+ await render({ name: 'overrides', kind, optional: true })
52
+ expect(container.textContent).toContain('Optional')
53
+ expect(container.textContent).toContain('Not found - skipped by Flux')
54
+ expect(referenceButton()).toBeUndefined()
55
+ expect(lookup).toHaveBeenCalledWith(kind === 'Secret' ? 'secrets' : 'configmaps', 'apps', 'overrides')
56
+ })
57
+
58
+ it('marks an absent required reference as required', async () => {
59
+ query.data = 'missing'
60
+ await render({ name: 'overrides' })
61
+ expect(container.textContent).toContain('Not found - required by Flux')
62
+ expect(container.textContent).not.toContain('Optional')
63
+ expect(referenceButton()).toBeUndefined()
64
+ })
65
+
66
+ it.each([403, 404, 500])('does not mistake HTTP %s for an absent optional reference', async status => {
67
+ query.error = Object.assign(new Error('read failed'), { status })
68
+ await render()
69
+ expect(container.textContent).toContain(status === 403 ? 'Access denied' : 'Could not check availability')
70
+ expect(container.textContent).not.toContain('skipped by Flux')
71
+ expect(referenceButton()).toBeUndefined()
72
+ })
73
+
74
+ it('waits for availability before offering navigation', async () => {
75
+ query.isLoading = true
76
+ await render()
77
+ expect(container.textContent).toContain('Checking availability')
78
+ expect(referenceButton()).toBeUndefined()
79
+ })
80
+
81
+ it('rechecks a missing reference and links it once available', async () => {
82
+ query.data = 'missing'
83
+ await render()
84
+ const retry = container.querySelector<HTMLButtonElement>('[aria-label="Check overrides again"]')
85
+ expect(retry).not.toBeNull()
86
+ await act(async () => retry?.click())
87
+ expect(query.refetch).toHaveBeenCalledOnce()
88
+ query.error = null
89
+ query.data = 'present'
90
+ await render()
91
+ expect(container.textContent).not.toContain('Not found')
92
+ await act(async () => referenceButton()?.click())
93
+ expect(navigate).toHaveBeenCalledWith({ kind: 'configmaps', namespace: 'apps', name: 'overrides', group: undefined })
94
+ })
95
+
96
+ it('does not trust stale successful data after a failed refresh', async () => {
97
+ query.data = 'present'
98
+ query.error = Object.assign(new Error('forbidden'), { status: 403 })
99
+ await render()
100
+ expect(container.textContent).toContain('Access denied')
101
+ expect(referenceButton()).toBeUndefined()
102
+ })
103
+
104
+ it('keeps navigation when the connected Radar cannot check availability', async () => {
105
+ query.data = 'unchecked'
106
+ await render()
107
+ expect(container.textContent).toContain('Availability not checked')
108
+ expect(referenceButton()).toBeDefined()
109
+ expect(container.textContent).not.toContain('Not found')
110
+ })
111
+ })
@@ -0,0 +1,67 @@
1
+ import { FluxHelmReleaseRenderer as BaseFluxHelmReleaseRenderer, type FluxValuesReference } from '@skyhook-io/k8s-ui/components/resources/renderers/FluxHelmReleaseRenderer'
2
+ import { AlertBanner, ResourceLink } from '@skyhook-io/k8s-ui/components/ui/drawer-components'
3
+ import type { ResourceRef } from '@skyhook-io/k8s-ui'
4
+ import { isForbiddenError, useResourceAvailability } from '../../../api/client'
5
+
6
+ interface FluxHelmReleaseData {
7
+ metadata?: { namespace?: string }
8
+ spec?: { valuesFrom?: FluxValuesReference[] }
9
+ }
10
+
11
+ export function FluxHelmReleaseRenderer({ data, onNavigate }: {
12
+ data: FluxHelmReleaseData
13
+ onNavigate?: (ref: ResourceRef) => void
14
+ }) {
15
+ return <BaseFluxHelmReleaseRenderer
16
+ data={data}
17
+ onNavigate={onNavigate}
18
+ renderValuesReference={reference => <ValuesReference
19
+ reference={reference}
20
+ namespace={data.metadata?.namespace ?? ''}
21
+ onNavigate={onNavigate}
22
+ />}
23
+ />
24
+ }
25
+
26
+ function ValuesReference({ reference, namespace, onNavigate }: {
27
+ reference: FluxValuesReference
28
+ namespace: string
29
+ onNavigate?: (ref: ResourceRef) => void
30
+ }) {
31
+ const kind = reference.kind === 'Secret' ? 'secrets' : 'configmaps'
32
+ const query = useResourceAvailability(kind, namespace, reference.name)
33
+
34
+ if ((query.data === 'present' || query.data === 'unchecked') && !query.error) {
35
+ return <>
36
+ <ResourceLink name={reference.name} kind={kind} namespace={namespace} onNavigate={onNavigate} />
37
+ {query.data === 'unchecked' && <span className="text-theme-text-tertiary text-xs">Availability not checked</span>}
38
+ </>
39
+ }
40
+
41
+ const missing = query.data === 'missing' && !query.error
42
+ const message = query.isLoading ? 'Checking availability…'
43
+ : missing ? reference.optional ? 'Not found - skipped by Flux' : 'Not found - required by Flux'
44
+ : isForbiddenError(query.error) ? 'Access denied - cannot check availability'
45
+ : 'Could not check availability'
46
+
47
+ const retry = !query.isLoading && <button
48
+ type="button"
49
+ onClick={() => { void query.refetch() }}
50
+ disabled={query.isFetching}
51
+ aria-label={`Check ${reference.name} again`}
52
+ className="text-xs text-theme-text-secondary hover:text-theme-text-primary disabled:opacity-50"
53
+ >Check again</button>
54
+
55
+ return <>
56
+ <span className="text-theme-text-secondary">{reference.name}</span>
57
+ {query.isLoading || (missing && reference.optional) ? <>
58
+ <span className="text-theme-text-tertiary text-xs">{message}</span>
59
+ {retry}
60
+ </> : <AlertBanner
61
+ variant={missing ? 'error' : 'unknown'}
62
+ title={message}
63
+ action={retry}
64
+ className="w-full"
65
+ />}
66
+ </>
67
+ }
@@ -0,0 +1,64 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { MemoryRouter } from 'react-router-dom'
5
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
6
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
7
+ import { KyvernoPolicyCoverage } from './KyvernoPolicyCoverage'
8
+
9
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
10
+
11
+ const requested: URL[] = []
12
+ let root: ReturnType<typeof createRoot>
13
+ let client: QueryClient
14
+
15
+ beforeEach(() => {
16
+ requested.length = 0
17
+ vi.stubGlobal('fetch', vi.fn((input: RequestInfo | URL) => {
18
+ requested.push(new URL(String(input), 'http://radar.invalid'))
19
+ return new Promise<Response>(() => {})
20
+ }))
21
+ root = createRoot(document.createElement('div'))
22
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
23
+ })
24
+
25
+ afterEach(async () => {
26
+ await act(async () => root.unmount())
27
+ client.clear()
28
+ vi.unstubAllGlobals()
29
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
30
+ })
31
+
32
+ async function coverageRequest(policy: object, url: string) {
33
+ await act(async () => {
34
+ root.render(
35
+ <QueryClientProvider client={client}>
36
+ <MemoryRouter initialEntries={[url]}>
37
+ <KyvernoPolicyCoverage data={policy} />
38
+ </MemoryRouter>
39
+ </QueryClientProvider>,
40
+ )
41
+ })
42
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)) })
43
+ const coverage = requested.find((u) => u.pathname.includes('/policy/policies/'))
44
+ if (!coverage) throw new Error(`no coverage request: ${requested.map(String).join(', ')}`)
45
+ return { namespace: coverage.searchParams.get('namespace'), namespaces: coverage.searchParams.get('namespaces') }
46
+ }
47
+
48
+ it("narrows a ClusterPolicy's subjects to the namespaces in view", async () => {
49
+ const clusterPolicy = { kind: 'ClusterPolicy', metadata: { name: 'require-limits' } }
50
+ expect(await coverageRequest(clusterPolicy, '/resources/clusterpolicies?namespaces=team-a,team-b'))
51
+ .toEqual({ namespace: null, namespaces: 'team-a,team-b' })
52
+ })
53
+
54
+ it('lists every namespace when the view covers all', async () => {
55
+ const clusterPolicy = { kind: 'ClusterPolicy', metadata: { name: 'require-limits' } }
56
+ expect(await coverageRequest(clusterPolicy, '/resources/clusterpolicies'))
57
+ .toEqual({ namespace: null, namespaces: null })
58
+ })
59
+
60
+ it("keeps a namespaced Policy on its own namespace", async () => {
61
+ const policy = { kind: 'Policy', metadata: { name: 'require-limits', namespace: 'team-a' } }
62
+ expect(await coverageRequest(policy, '/resources/policies?namespaces=team-b'))
63
+ .toEqual({ namespace: 'team-a', namespaces: null })
64
+ })
@@ -3,6 +3,7 @@ import { useLocation } from 'react-router-dom'
3
3
  import { PolicyCoverageSection } from '@skyhook-io/k8s-ui/components/resources/renderers/PolicyCoverageSection'
4
4
  import type { PolicyCoverageSubject, ResourceRef } from '@skyhook-io/k8s-ui'
5
5
  import { usePolicyCoverage } from '../../../api/policy'
6
+ import { namespacesFromSearch } from '../../../utils/navigation'
6
7
 
7
8
  /** Mirrors maxPolicyCoverageSubjectsHard in internal/server/policy_handlers.go —
8
9
  * asking for more than the server will send just returns the same list. */
@@ -32,13 +33,11 @@ export function KyvernoPolicyCoverage({
32
33
  // ceiling — past which the response says what it could not send.
33
34
  const [limit, setLimit] = useState<number | undefined>(undefined)
34
35
 
35
- // The header's namespace filter is applied SERVER-side from session state, so
36
- // the same URL returns a different body once it changes and nothing in the
37
- // request distinguishes the two. Without it in the cache key, a policy opened
38
- // under "All namespaces" keeps serving that body after the filter narrows —
39
- // the view then shows other people's namespaces under your scope, and which
40
- // behaviour you get depends on where you navigated from.
41
- const viewFilter = useLocation().search
36
+ // A ClusterPolicy's subjects are narrowed to the header's namespace filter,
37
+ // which the server applies only when the request names it. A namespaced
38
+ // Policy's own namespace is its filter.
39
+ const viewNamespaces = namespacesFromSearch(new URLSearchParams(useLocation().search))
40
+ const viewFilter = namespace ? [] : viewNamespaces
42
41
  const query = usePolicyCoverage(name, namespace || undefined, !!name, limit, viewFilter)
43
42
 
44
43
  return (
@@ -10,7 +10,7 @@ import { clsx } from 'clsx'
10
10
  import { useQueryClient } from '@tanstack/react-query'
11
11
  import { useAnimatedUnmount } from '../../hooks/useAnimatedUnmount'
12
12
  import { TRANSITION_BACKDROP, TRANSITION_PANEL, overlayExitMs, overlayTransitionStyle } from '../../utils/animation'
13
- import { apiUrl, getApiBase, getAuthHeaders, getCredentialsMode, routePath } from '../../api/config'
13
+ import { apiUrl, getApiBase, getAuthHeaders, getCredentialsMode, mcpEndpointUrl } from '../../api/config'
14
14
  import {
15
15
  useCloudRole, useVersionCheck, useClusterInfo, usePrometheusStatus, useArgoStatus,
16
16
  useOpenCostSummary,
@@ -46,10 +46,6 @@ import { OperatorManagedNotice } from './OperatorManagedNotice'
46
46
  import { FormSaveActions } from './FormSaveActions'
47
47
  export type { SettingsSectionId } from './settings-state'
48
48
 
49
- function mcpEndpointUrl(): string {
50
- return `${window.location.origin}${routePath('/mcp')}`
51
- }
52
-
53
49
  interface Config {
54
50
  kubeconfig?: string
55
51
  kubeconfigDirs?: string[]
@@ -68,6 +64,7 @@ interface Config {
68
64
  argoCdUrl?: string
69
65
  argoCdInsecureTls?: boolean
70
66
  mcp?: boolean | null
67
+ mcpReadOnly?: boolean | null
71
68
  restoreLastDesktopContext?: boolean | null
72
69
  }
73
70
 
@@ -134,6 +131,7 @@ function normalizeStartup(c: Config) {
134
131
  timelineDbPath: c.timelineDbPath ?? '',
135
132
  historyLimit: c.historyLimit ?? null,
136
133
  mcp: c.mcp ?? true,
134
+ mcpReadOnly: c.mcpReadOnly ?? false,
137
135
  restoreLastDesktopContext: c.restoreLastDesktopContext ?? true,
138
136
  }
139
137
  }
@@ -242,7 +240,7 @@ export function SettingsDialog({
242
240
  edN.restoreLastDesktopContext !== svN.restoreLastDesktopContext
243
241
  const serverDirty =
244
242
  edN.port !== svN.port || edN.noBrowser !== svN.noBrowser || edN.browser !== svN.browser
245
- const mcpDirty = edN.mcp !== svN.mcp
243
+ const mcpDirty = edN.mcp !== svN.mcp || edN.mcpReadOnly !== svN.mcpReadOnly
246
244
  const timelineDirty =
247
245
  edN.timelineStorage !== svN.timelineStorage ||
248
246
  edN.timelineDbPath !== svN.timelineDbPath ||
@@ -950,7 +948,9 @@ export function SettingsDialog({
950
948
  <SubHeading>MCP</SubHeading>
951
949
  <MCPSection
952
950
  mcpEnabled={editedConfig.mcp ?? true}
953
- onToggle={(v) => updateConfigField('mcp', v)}
951
+ onToggle={(v) => setEditedConfig((c) => ({ ...c, mcp: v, mcpReadOnly: v && (c.mcpReadOnly ?? false) }))}
952
+ readOnly={editedConfig.mcpReadOnly ?? false}
953
+ onReadOnlyChange={(v) => updateConfigField('mcpReadOnly', v)}
954
954
  isDesktop={isDesktop}
955
955
  portPinned={editedConfig.port != null && editedConfig.port > 0}
956
956
  onPinPort={(port) => updateConfigField('port', port)}
@@ -1235,7 +1235,7 @@ function OperatorSettingsSummary({ section, config }: { section: SettingsSection
1235
1235
  break
1236
1236
  case 'advanced':
1237
1237
  rows = [
1238
- ['MCP', c.mcp ? 'Enabled' : 'Disabled'],
1238
+ ['MCP', c.mcp ? (c.mcpReadOnly ? 'Read-only' : 'Enabled') : 'Disabled'],
1239
1239
  ['Timeline storage', c.timelineStorage || 'Memory'],
1240
1240
  ['Event history limit', c.historyLimit ?? '—'],
1241
1241
  ]
@@ -1305,7 +1305,7 @@ function OverviewPanel({ active, onNavigate }: { active: boolean; onNavigate: (s
1305
1305
  const agentLabel =
1306
1306
  diag.agents.find((a) => a.name === diag.selectedAgent)?.label ?? diag.agents[0]?.label
1307
1307
  const mcpOn = capabilities.mcpEnabled
1308
- const mcpUrl = mcpEndpointUrl()
1308
+ const mcpUrl = mcpEndpointUrl(capabilities.mcpReadOnly)
1309
1309
  const costMissing = cost?.reason === 'no_prometheus' || cost?.reason === 'no_cost_source' || cost?.reason === 'no_metrics'
1310
1310
  const costUnavailableDetail = cost?.reason === 'no_prometheus'
1311
1311
  ? 'Connect OpenCost metrics in Metrics.'
@@ -1351,7 +1351,7 @@ function OverviewPanel({ active, onNavigate }: { active: boolean; onNavigate: (s
1351
1351
  {
1352
1352
  id: 'advanced', icon: Zap, label: 'MCP',
1353
1353
  tone: mcpOn ? 'ok' : 'off',
1354
- value: mcpOn ? 'On' : 'Off',
1354
+ value: mcpOn ? (capabilities.mcpReadOnly ? 'Read-only' : 'On') : 'Off',
1355
1355
  detail: mcpOn ? mcpUrl : undefined,
1356
1356
  copyable: mcpOn,
1357
1357
  },
@@ -2096,12 +2096,16 @@ function CostSection({
2096
2096
 
2097
2097
  function MCPSection({
2098
2098
  mcpEnabled,
2099
+ readOnly,
2100
+ onReadOnlyChange,
2099
2101
  onToggle,
2100
2102
  isDesktop,
2101
2103
  portPinned,
2102
2104
  onPinPort,
2103
2105
  }: {
2104
2106
  mcpEnabled: boolean
2107
+ readOnly: boolean
2108
+ onReadOnlyChange: (value: boolean) => void
2105
2109
  onToggle: (value: boolean) => void
2106
2110
  isDesktop: boolean
2107
2111
  portPinned: boolean
@@ -2110,7 +2114,8 @@ function MCPSection({
2110
2114
  const [copied, setCopied] = useState(false)
2111
2115
 
2112
2116
  const currentPort = Number(window.location.port) || 80
2113
- const mcpUrl = mcpEndpointUrl()
2117
+ const capabilities = useCapabilitiesContext()
2118
+ const mcpUrl = mcpEndpointUrl(capabilities.mcpReadOnly)
2114
2119
 
2115
2120
  const handleCopy = () => {
2116
2121
  navigator.clipboard.writeText(mcpUrl)
@@ -2125,8 +2130,8 @@ function MCPSection({
2125
2130
  return (
2126
2131
  <div className="space-y-3">
2127
2132
  <p className="text-xs text-theme-text-tertiary">
2128
- Lets AI tools (Claude Code, Cursor, …) query and act on this cluster through Radar over the
2129
- Model Context Protocol. Point your agent at the endpoint below.
2133
+ Lets AI tools query this cluster through Radar over the Model Context Protocol.
2134
+ Full mode also allows changes. Settings take effect after restarting Radar.
2130
2135
  </p>
2131
2136
  <ConfigToggle
2132
2137
  label="MCP Server"
@@ -2134,10 +2139,11 @@ function MCPSection({
2134
2139
  onChange={onToggle}
2135
2140
  />
2136
2141
 
2137
- {mcpEnabled && (
2142
+ {mcpEnabled && <ConfigToggle label="Read-only MCP" value={readOnly} onChange={onReadOnlyChange} />}
2143
+ {mcpEnabled && capabilities.mcpEnabled && (
2138
2144
  <div className="space-y-2 pl-0.5">
2139
2145
  <div>
2140
- <label className="block text-xs text-theme-text-secondary mb-1">MCP Endpoint</label>
2146
+ <label className="block text-xs text-theme-text-secondary mb-1">Running MCP Endpoint</label>
2141
2147
  <div className="flex items-center gap-2">
2142
2148
  <code className="flex-1 px-2.5 py-1.5 text-xs font-mono bg-theme-elevated border border-theme-border rounded-md text-theme-text-primary truncate">
2143
2149
  {mcpUrl}
@@ -0,0 +1,77 @@
1
+ // @vitest-environment jsdom
2
+ import { act, type ComponentProps } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5
+ import { TrafficFilterSidebar } from './TrafficFilterSidebar'
6
+
7
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
8
+
9
+ type Props = ComponentProps<typeof TrafficFilterSidebar>
10
+
11
+ const props = (overrides: Partial<Props>): Props => ({
12
+ hideSystem: true, setHideSystem: vi.fn(),
13
+ hideExternal: false, setHideExternal: vi.fn(),
14
+ minConnections: 0, setMinConnections: vi.fn(),
15
+ showNamespaceGroups: true, setShowNamespaceGroups: vi.fn(),
16
+ collapseInternet: true, setCollapseInternet: vi.fn(),
17
+ groupByWorkload: true, setGroupByWorkload: vi.fn(),
18
+ addonMode: 'show', setAddonMode: vi.fn(),
19
+ aggregateExternal: true, setAggregateExternal: vi.fn(),
20
+ detectServices: true, setDetectServices: vi.fn(),
21
+ timeRange: '5m', setTimeRange: vi.fn(),
22
+ l7Protocol: 'all', setL7Protocol: vi.fn(),
23
+ l7Methods: new Set(), onToggleL7Method: vi.fn(),
24
+ l7StatusRanges: new Set(), onToggleL7StatusRange: vi.fn(),
25
+ verdicts: new Set(), onToggleVerdict: vi.fn(),
26
+ dnsPattern: '', setDnsPattern: vi.fn(),
27
+ namespaces: [{ name: 'demo', nodeCount: 3 }],
28
+ hiddenNamespaces: new Set(), onToggleNamespace: vi.fn(),
29
+ ...overrides,
30
+ })
31
+
32
+ let container: HTMLDivElement
33
+ let root: Root
34
+
35
+ beforeEach(() => {
36
+ container = document.createElement('div')
37
+ document.body.appendChild(container)
38
+ root = createRoot(container)
39
+ })
40
+
41
+ afterEach(() => {
42
+ act(() => root.unmount())
43
+ container.remove()
44
+ })
45
+
46
+ const button = (label: string) =>
47
+ Array.from(container.querySelectorAll('button')).find((b) => b.textContent === label)
48
+
49
+ describe('TrafficFilterSidebar verdict filter', () => {
50
+ it('offers the verdicts on L4-only traffic, where there is no L7 section', () => {
51
+ const onToggleVerdict = vi.fn()
52
+ act(() => root.render(
53
+ <TrafficFilterSidebar {...props({ showL7Filters: false, availableVerdicts: ['forwarded', 'dropped'], onToggleVerdict })} />,
54
+ ))
55
+
56
+ expect(container.textContent).not.toContain('L7 Filters')
57
+ expect(button('forwarded')).toBeDefined()
58
+ expect(button('error')).toBeUndefined()
59
+
60
+ act(() => button('dropped')!.click())
61
+ expect(onToggleVerdict).toHaveBeenCalledWith('dropped')
62
+ })
63
+
64
+ it('marks the selected verdict as pressed', () => {
65
+ act(() => root.render(
66
+ <TrafficFilterSidebar {...props({ availableVerdicts: ['forwarded', 'dropped'], verdicts: new Set(['dropped']) })} />,
67
+ ))
68
+ expect(button('dropped')!.getAttribute('aria-pressed')).toBe('true')
69
+ expect(button('forwarded')!.getAttribute('aria-pressed')).toBe('false')
70
+ })
71
+
72
+ it('shows no verdict control when there are no verdict choices', () => {
73
+ act(() => root.render(<TrafficFilterSidebar {...props({ showL7Filters: true, availableVerdicts: [] })} />))
74
+ expect(container.textContent).toContain('L7 Filters')
75
+ expect(container.textContent).not.toContain('Verdict')
76
+ })
77
+ })
@@ -11,6 +11,7 @@ import {
11
11
  Info,
12
12
  Puzzle,
13
13
  Boxes,
14
+ ShieldAlert,
14
15
  } from 'lucide-react'
15
16
  import { clsx } from 'clsx'
16
17
  import { SEVERITY_BADGE } from '@skyhook-io/k8s-ui/utils/badge-colors'
@@ -57,7 +58,7 @@ interface TrafficFilterSidebarProps {
57
58
  timeRange: string
58
59
  setTimeRange: (v: string) => void
59
60
 
60
- // L7 filters (Hubble-only)
61
+ // L7 filters
61
62
  /** Whether the flows carry any L7 detail at all. Not "is this Hubble": Beyla and
62
63
  * Istio report L7 too, and gating on the source name hid these filters from them. */
63
64
  showL7Filters?: boolean
@@ -77,8 +78,8 @@ interface TrafficFilterSidebarProps {
77
78
  onToggleL7Method: (method: string) => void
78
79
  l7StatusRanges: Set<string>
79
80
  onToggleL7StatusRange: (range: string) => void
80
- l7Verdicts: Set<string>
81
- onToggleL7Verdict: (verdict: string) => void
81
+ verdicts: Set<string>
82
+ onToggleVerdict: (verdict: string) => void
82
83
  dnsPattern: string
83
84
  setDnsPattern: (v: string) => void
84
85
 
@@ -178,8 +179,8 @@ export const TrafficFilterSidebar = memo(function TrafficFilterSidebar({
178
179
  onToggleL7Method,
179
180
  l7StatusRanges,
180
181
  onToggleL7StatusRange,
181
- l7Verdicts,
182
- onToggleL7Verdict,
182
+ verdicts,
183
+ onToggleVerdict,
183
184
  dnsPattern,
184
185
  setDnsPattern,
185
186
  namespaces,
@@ -284,6 +285,42 @@ export const TrafficFilterSidebar = memo(function TrafficFilterSidebar({
284
285
  ))}
285
286
  </div>
286
287
  </div>
288
+
289
+ {/* Verdict. Shown whenever the flows say something other than forwarded,
290
+ whether or not they carry L7 detail: Hubble reports drops on plain
291
+ L4 flows. */}
292
+ {availableVerdicts.length > 0 && (
293
+ <div className="mt-2 pt-2 border-t border-theme-border/50">
294
+ <div className="flex items-center gap-2 mb-1.5">
295
+ <ShieldAlert className="w-3.5 h-3.5 text-theme-text-tertiary" />
296
+ <span className="text-xs text-theme-text-primary">Verdict</span>
297
+ <Tooltip content="What happened to the traffic, as the traffic source reports it. Pick one or more to show only those flows." position="right">
298
+ <Info className="w-3 h-3 text-theme-text-tertiary hover:text-theme-text-secondary cursor-help" />
299
+ </Tooltip>
300
+ </div>
301
+ <div className="flex flex-wrap gap-1">
302
+ {([
303
+ { label: 'forwarded', active: SEVERITY_BADGE.success },
304
+ { label: 'dropped', active: SEVERITY_BADGE.error },
305
+ { label: 'error', active: SEVERITY_BADGE.warning },
306
+ ] as const).filter(({ label }) => availableVerdicts.includes(label)).map(({ label, active }) => (
307
+ <button
308
+ key={label}
309
+ onClick={() => onToggleVerdict(label)}
310
+ aria-pressed={verdicts.has(label)}
311
+ className={clsx(
312
+ 'px-1.5 py-0.5 rounded text-[10px] font-medium capitalize transition-colors',
313
+ verdicts.has(label)
314
+ ? active
315
+ : 'bg-theme-elevated text-theme-text-tertiary hover:text-theme-text-secondary'
316
+ )}
317
+ >
318
+ {label}
319
+ </button>
320
+ ))}
321
+ </div>
322
+ </div>
323
+ )}
287
324
  </div>
288
325
 
289
326
  {/* Display */}
@@ -439,32 +476,6 @@ export const TrafficFilterSidebar = memo(function TrafficFilterSidebar({
439
476
  </div>
440
477
  )}
441
478
 
442
- {/* Verdict, limited to the verdicts the data actually contains. */}
443
- {availableVerdicts.length > 0 && (
444
- <div>
445
- <div className="text-[10px] text-theme-text-tertiary mb-1">Verdict</div>
446
- <div className="flex flex-wrap gap-1">
447
- {([
448
- { label: 'forwarded', active: SEVERITY_BADGE.success },
449
- { label: 'dropped', active: SEVERITY_BADGE.error },
450
- { label: 'error', active: SEVERITY_BADGE.warning },
451
- ] as const).filter(({ label }) => availableVerdicts.includes(label)).map(({ label, active }) => (
452
- <button
453
- key={label}
454
- onClick={() => onToggleL7Verdict(label)}
455
- className={clsx(
456
- 'px-1.5 py-0.5 rounded text-[10px] font-medium capitalize transition-colors',
457
- l7Verdicts.has(label)
458
- ? active
459
- : 'bg-theme-elevated text-theme-text-tertiary hover:text-theme-text-secondary'
460
- )}
461
- >
462
- {label}
463
- </button>
464
- ))}
465
- </div>
466
- </div>
467
- )}
468
479
  </div>
469
480
  )}
470
481