@skyhook-io/radar-app 1.22.0 → 1.22.1

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 (57) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +2 -1
  3. package/src/api/client.ts +12 -0
  4. package/src/api/cnpg-history.ts +3 -3
  5. package/src/api/cnpg-storage.ts +3 -3
  6. package/src/api/diagnose.test.ts +34 -0
  7. package/src/api/diagnose.ts +17 -4
  8. package/src/api/radarFeatures.test.ts +13 -1
  9. package/src/api/radarFeatures.ts +2 -0
  10. package/src/api/resourceActions.test.ts +829 -0
  11. package/src/api/resourceActions.ts +584 -0
  12. package/src/api/resourceActions.ui.test.tsx +1882 -0
  13. package/src/api/reviewedActionMutation.ts +56 -28
  14. package/src/api/substrateHealth.ts +2 -3
  15. package/src/api/traffic.ts +13 -5
  16. package/src/api/workloadMetrics.test.ts +11 -2
  17. package/src/api/workloadMetrics.ts +2 -2
  18. package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
  19. package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
  20. package/src/components/diagnose/DiagnoseContext.tsx +28 -3
  21. package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
  22. package/src/components/diagnose/Home.tsx +3 -0
  23. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
  24. package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
  25. package/src/components/diagnose/InvestigationView.tsx +10 -2
  26. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
  27. package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
  28. package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
  29. package/src/components/diagnose/QuestionComposer.tsx +13 -8
  30. package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
  31. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
  32. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
  33. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
  34. package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
  35. package/src/components/diagnose/launch.ts +1 -1
  36. package/src/components/dock/PodDebugSession.test.tsx +66 -0
  37. package/src/components/dock/PodDebugSession.tsx +3 -1
  38. package/src/components/dock/TerminalTab.test.tsx +43 -3
  39. package/src/components/dock/TerminalTab.tsx +10 -1
  40. package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
  41. package/src/components/helm/InstallWizard.tsx +1 -1
  42. package/src/components/home/mcpToolCatalog.ts +1 -1
  43. package/src/components/resources/PodEvictAction.test.tsx +951 -0
  44. package/src/components/resources/PodEvictAction.tsx +167 -0
  45. package/src/components/resources/ResourcesView.tsx +3 -0
  46. package/src/components/resources/renderers/WorkloadRenderer.tsx +3 -0
  47. package/src/components/settings/LocalConnectionSettings.tsx +4 -4
  48. package/src/components/settings/SettingsDialog.tsx +23 -18
  49. package/src/components/settings/integrationQueries.test.ts +98 -0
  50. package/src/components/settings/integrationQueries.ts +36 -0
  51. package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
  52. package/src/components/traffic/TrafficView.tsx +91 -35
  53. package/src/components/ui/Markdown.test.tsx +37 -0
  54. package/src/components/ui/Markdown.tsx +15 -2
  55. package/src/components/useContextSwitchFlow.test.tsx +27 -2
  56. package/src/components/useContextSwitchFlow.tsx +20 -22
  57. package/src/components/workload/WorkloadView.tsx +16 -3
@@ -0,0 +1,167 @@
1
+ import { useQuery } from '@tanstack/react-query'
2
+ import { LogOut } from 'lucide-react'
3
+ import {
4
+ RESOURCE_ACTION_IDS,
5
+ ReviewedActionDialog,
6
+ useReviewedActionSession,
7
+ type ResourceActionClientAdapter,
8
+ } from '@skyhook-io/k8s-ui'
9
+ import { getApiBase } from '../../api/config'
10
+ import { connectionHeaderValue, useCurrentConnectionId } from '../../api/connectionBinding'
11
+ import { checkResourceActionAccess } from '../../api/resourceActions'
12
+
13
+ const POD_EVICT_ID = RESOURCE_ACTION_IDS.podEvict
14
+ const ACCEPTANCE_NOTE =
15
+ 'API acceptance only confirms Kubernetes accepted the eviction request; termination and controller follow-up happen separately.'
16
+
17
+ /** Exact D4 access verdict at the wiring boundary (`core/Pod/evict/access`). Fails closed unless `'allowed'`. */
18
+ export type PodEvictAccess = 'allowed' | 'denied' | 'unknown' | 'pending'
19
+
20
+ export interface PodEvictTarget {
21
+ apiVersion?: string
22
+ kind?: string
23
+ metadata?: {
24
+ uid?: string
25
+ name?: string
26
+ namespace?: string
27
+ deletionTimestamp?: string
28
+ annotations?: Record<string, string>
29
+ ownerReferences?: Array<{ kind?: string; name?: string; controller?: boolean }>
30
+ }
31
+ spec?: { nodeName?: string; volumes?: Array<{ emptyDir?: unknown }> }
32
+ status?: { phase?: string }
33
+ }
34
+
35
+ export interface PodEvictActionProps {
36
+ pod: PodEvictTarget
37
+ adapter: ResourceActionClientAdapter
38
+ /** Optional pre-resolved exact D4 access verdict; when omitted, queries `core/Pod/evict/access` for this connection + UID. */
39
+ access?: PodEvictAccess
40
+ enabled?: boolean
41
+ }
42
+
43
+ /** Client eligibility mirror of `k8score.AssessPodEviction`; live D4 preview remains authoritative. */
44
+ export function isPodEvictEligible(pod: PodEvictTarget | undefined): boolean {
45
+ if (!pod || pod.apiVersion !== 'v1' || pod.kind !== 'Pod') return false
46
+ const meta = pod.metadata
47
+ if (!meta?.uid?.trim() || !meta.namespace?.trim() || !meta.name?.trim()) return false
48
+ if (meta.deletionTimestamp) return false
49
+ if (pod.status?.phase === 'Succeeded' || pod.status?.phase === 'Failed') return false
50
+ if (meta.annotations?.['kubernetes.io/config.mirror']) return false
51
+ if (!meta.ownerReferences?.some((ref) => ref.controller === true)) return false
52
+ return !pod.spec?.volumes?.some((v) => v.emptyDir !== undefined)
53
+ }
54
+
55
+ export function podEvictAccessKey(
56
+ namespace: string,
57
+ name: string,
58
+ uid: string,
59
+ base = getApiBase(),
60
+ connection = connectionHeaderValue(base),
61
+ ) {
62
+ return ['resource-action-access', POD_EVICT_ID, base, connection ?? '', namespace, name, uid] as const
63
+ }
64
+
65
+ export function usePodEvictAccess(
66
+ pod: PodEvictTarget | undefined,
67
+ adapter: ResourceActionClientAdapter,
68
+ enabled = true,
69
+ ): PodEvictAccess {
70
+ const apiBase = getApiBase()
71
+ const headerConnectionId = useCurrentConnectionId(apiBase)
72
+ const connectionId = adapter.getConnectionId ? adapter.getConnectionId() : headerConnectionId
73
+ const namespace = pod?.metadata?.namespace?.trim() ?? ''
74
+ const name = pod?.metadata?.name?.trim() ?? ''
75
+ const uid = pod?.metadata?.uid?.trim() ?? ''
76
+ const supported = adapter.support === 'supported' && adapter.supportsAction(POD_EVICT_ID)
77
+ const queryEnabled = enabled && supported && isPodEvictEligible(pod)
78
+
79
+ const query = useQuery<Exclude<PodEvictAccess, 'pending'>>({
80
+ queryKey: podEvictAccessKey(namespace, name, uid, apiBase, connectionId),
81
+ queryFn: async ({ signal }) => {
82
+ const resp = await checkResourceActionAccess(
83
+ POD_EVICT_ID,
84
+ { namespace, name },
85
+ { apiBase, connectionId, signal },
86
+ )
87
+ return resp.access
88
+ },
89
+ enabled: queryEnabled,
90
+ staleTime: 15_000,
91
+ retry: false,
92
+ refetchOnWindowFocus: true,
93
+ })
94
+
95
+ if (!queryEnabled) return 'denied'
96
+ if (query.isPending) return 'pending'
97
+ if (query.isError) return 'unknown'
98
+ return query.data ?? 'unknown'
99
+ }
100
+
101
+ export function PodEvictAction({ pod, adapter, access, enabled = true }: PodEvictActionProps) {
102
+ const apiBase = getApiBase()
103
+ const headerConnectionId = useCurrentConnectionId(apiBase)
104
+ const currentConnectionId = adapter.getConnectionId ? adapter.getConnectionId() : headerConnectionId
105
+
106
+ const namespace = pod.metadata?.namespace?.trim() ?? ''
107
+ const name = pod.metadata?.name?.trim() ?? ''
108
+ const podUID = pod.metadata?.uid?.trim() ?? ''
109
+ const supported = adapter.support === 'supported' && adapter.supportsAction(POD_EVICT_ID)
110
+ const queriedAccess = usePodEvictAccess(pod, adapter, enabled && access === undefined)
111
+ const effectiveAccess = access ?? queriedAccess
112
+ const canOffer = enabled && supported && effectiveAccess === 'allowed' && isPodEvictEligible(pod)
113
+
114
+ const activeLocator =
115
+ enabled && namespace && name
116
+ ? JSON.stringify([currentConnectionId ?? '', adapter.context ?? '', namespace, name])
117
+ : null
118
+ const activeIdentity =
119
+ activeLocator && podUID
120
+ ? JSON.stringify([currentConnectionId ?? '', adapter.context ?? '', namespace, name, podUID])
121
+ : null
122
+ const session = useReviewedActionSession(adapter, activeIdentity, activeLocator)
123
+
124
+ const openDialog = () => {
125
+ if (!activeIdentity) return
126
+ session.start({
127
+ slot: 'evict',
128
+ identity: activeIdentity,
129
+ actionId: POD_EVICT_ID,
130
+ kind: 'pods',
131
+ subjectKind: 'Pod',
132
+ namespace,
133
+ name,
134
+ uid: podUID,
135
+ title: 'Evict Pod',
136
+ fallbackEffect: `Review eviction for Pod ${namespace}/${name}. Eviction can interrupt the workload, and its controller determines what happens next.`,
137
+ confirmLabel: 'Evict Pod',
138
+ pendingLabel: 'Evicting…',
139
+ disruptive: true,
140
+ autoExecuteIfClean: false,
141
+ })
142
+ }
143
+
144
+ if (!session.draft && !canOffer) return null
145
+
146
+ return (
147
+ <>
148
+ {canOffer && (
149
+ <button
150
+ type="button"
151
+ onClick={openDialog}
152
+ disabled={session.isBusy('evict')}
153
+ aria-busy={session.isBusy('evict')}
154
+ className="btn-secondary flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium"
155
+ >
156
+ <LogOut className="h-3.5 w-3.5" />
157
+ Evict Pod
158
+ </button>
159
+ )}
160
+ <ReviewedActionDialog
161
+ session={session}
162
+ adapter={adapter}
163
+ notes={session.draft?.preview ? [ACCEPTANCE_NOTE] : undefined}
164
+ />
165
+ </>
166
+ )
167
+ }
@@ -2,6 +2,7 @@ import { useState, useMemo, useCallback } from 'react'
2
2
  import { useLocation, useNavigate } from 'react-router-dom'
3
3
  import { useQuery } from '@tanstack/react-query'
4
4
  import { fetchJSON, useNamespaceScope, isForbiddenError, isKindSyncFailed, isStillLoadingError, useCapabilities, useNamespaceCapabilities, useResources, useSecretCertExpiry, useTopPodMetrics, useTopNodeMetrics, useBulkDeleteResources, useBulkRestartWorkloads, useBulkScaleWorkloads, useAuditBadges, useIssues, fetchResourceList, isListTooLargeError, isUnretryableReadError, useRadarFeature } from '../../api/client'
5
+ import { useResourceActionAdapter } from '../../api/resourceActions'
5
6
  import { isBadgeWorthy } from '../../utils/auditBadges'
6
7
  import { ISSUE_SEVERITY_RANK } from '@skyhook-io/k8s-ui'
7
8
  import type { Issue, AuditBadgeMessage } from '@skyhook-io/k8s-ui'
@@ -358,6 +359,7 @@ export function ResourcesView({ namespaces, selectedResource, onResourceClick, o
358
359
  const bulkDeleteMutation = useBulkDeleteResources()
359
360
  const bulkRestartMutation = useBulkRestartWorkloads()
360
361
  const bulkScaleMutation = useBulkScaleWorkloads()
362
+ const resourceActionAdapter = useResourceActionAdapter()
361
363
 
362
364
  // Navigation adapter. k8s-ui constructs paths from `basePath` (which
363
365
  // includes the router basename so they line up with window.location.pathname
@@ -472,6 +474,7 @@ export function ResourcesView({ namespaces, selectedResource, onResourceClick, o
472
474
  isBulkRestarting={canBulkRestartSelectedKind && bulkRestartMutation.isPending}
473
475
  onBulkScale={canBulkScaleSelectedKind ? (items, replicas, options) => bulkScaleMutation.mutate({ items, replicas }, { onSuccess: options?.onSuccess }) : undefined}
474
476
  isBulkScaling={canBulkScaleSelectedKind && bulkScaleMutation.isPending}
477
+ resourceActionAdapter={resourceActionAdapter}
475
478
  />
476
479
  <CreateResourceDialog
477
480
  open={createDialogOpen}
@@ -1,6 +1,7 @@
1
1
  import { WorkloadRenderer as BaseWorkloadRenderer } from '@skyhook-io/k8s-ui/components/resources/renderers/WorkloadRenderer'
2
2
  import { useNavigate } from 'react-router-dom'
3
3
  import { useScaleWorkload, fetchJSON } from '../../../api/client'
4
+ import { useResourceActionAdapter } from '../../../api/resourceActions'
4
5
  import { useRBACSubject } from '../../../api/rbac'
5
6
  import { usePolicyResource } from '../../../api/policy'
6
7
  import { podLimitRangeNames, useNamespaceLimitRanges } from '../../../api/quotas'
@@ -39,6 +40,7 @@ export function WorkloadRenderer({ kind, data, onNavigate, scaleBlockedBy, workl
39
40
  const navigate = useNavigate()
40
41
  const queryClient = useQueryClient()
41
42
  const scaleMutation = useScaleWorkload()
43
+ const resourceActionAdapter = useResourceActionAdapter()
42
44
 
43
45
  const metadata = data.metadata || {}
44
46
  const viewPodsUrl = `/resources/pods?ownerKind=${encodeURIComponent(getOwnerKind(kind))}&ownerName=${encodeURIComponent(metadata.name || '')}&namespace=${encodeURIComponent(metadata.namespace || '')}`
@@ -119,6 +121,7 @@ export function WorkloadRenderer({ kind, data, onNavigate, scaleBlockedBy, workl
119
121
  })
120
122
  }}
121
123
  isScalePending={scaleMutation.isPending}
124
+ resourceActionAdapter={resourceActionAdapter}
122
125
  onRequestRefresh={() => {
123
126
  queryClient.invalidateQueries({ queryKey: ['resource', kind, metadata.namespace, metadata.name] })
124
127
  }}
@@ -152,7 +152,7 @@ export function LocalConnectionSettings({
152
152
  kind: IntegrationKind
153
153
  profiles: IntegrationProfiles
154
154
  cliSession?: { server: string; user: string; insecure?: boolean }
155
- onChange: (profiles: IntegrationProfiles) => void
155
+ onChange: (profiles: IntegrationProfiles, changed?: IntegrationKind[]) => void
156
156
  onDirtyChange: (dirty: boolean) => void
157
157
  onBusyChange?: (busy: boolean) => void
158
158
  status?: ReactNode
@@ -389,15 +389,15 @@ export function LocalConnectionSettings({
389
389
  }
390
390
  }
391
391
  }
392
- const receive = (data: ConnectionResponse) => {
392
+ const receive = (data: ConnectionResponse, changed?: IntegrationKind[]) => {
393
393
  setSnapshot(data.profiles)
394
394
  setCatalog(data.connections)
395
- onChange(data.profiles)
395
+ onChange(data.profiles, changed)
396
396
  resetDraft(data.profiles[kind])
397
397
  }
398
398
  const save = async (update: Update) => {
399
399
  const data = await fetchConnections(update)
400
- receive(data)
400
+ receive(data, update.action === 'reconfirm' ? update.kinds : [kind])
401
401
  onDirtyChange(false)
402
402
  setConfirmBack(false)
403
403
  setTask('main')
@@ -9,6 +9,7 @@ import {
9
9
  } from 'lucide-react'
10
10
  import { clsx } from 'clsx'
11
11
  import { useQueryClient } from '@tanstack/react-query'
12
+ import { invalidateIntegrationQueries } from './integrationQueries'
12
13
  import { useAnimatedUnmount } from '../../hooks/useAnimatedUnmount'
13
14
  import { TRANSITION_BACKDROP, TRANSITION_PANEL, overlayExitMs, overlayTransitionStyle } from '../../utils/animation'
14
15
  import { apiUrl, getApiBase, getAuthHeaders, getCredentialsMode, mcpEndpointUrl } from '../../api/config'
@@ -179,15 +180,15 @@ export function SettingsDialog({
179
180
  } : value)
180
181
  void queryClient.resetQueries({ queryKey: [previousIntegrationSettingsKey] })
181
182
  }, [queryClient])
182
- const connectionsChanged = useCallback((profiles: IntegrationProfiles) => {
183
+ const connectionsChanged = useCallback((profiles: IntegrationProfiles, changed: IntegrationKind[] = []) => {
183
184
  setConnectionsChangedAt(Date.now())
184
185
  setConfigData(value => value ? { ...value, integrationProfiles: profiles } : value)
185
186
  void queryClient.resetQueries({ queryKey: [previousIntegrationSettingsKey] })
186
- void queryClient.invalidateQueries({ predicate: query => typeof query.queryKey[0] === 'string' && /^(prometheus|opencost|gitops|argo)/.test(query.queryKey[0]) })
187
+ if (changed.length) void invalidateIntegrationQueries(queryClient, changed)
187
188
  }, [queryClient])
188
189
  const openObserveChanged = useCallback(() => {
189
190
  setConnectionsChangedAt(Date.now())
190
- void queryClient.invalidateQueries({ predicate: query => typeof query.queryKey[0] === 'string' && /^(prometheus|opencost)/.test(query.queryKey[0]) })
191
+ void invalidateIntegrationQueries(queryClient, ['metrics'])
191
192
  }, [queryClient])
192
193
 
193
194
  const [configData, setConfigData] = useState<ConfigResponse | null>(null)
@@ -208,7 +209,21 @@ export function SettingsDialog({
208
209
  const argoStatusQuery = useArgoStatus(
209
210
  open && section === 'argocd'
210
211
  )
211
- const { data: argoSectionStatus, refetch: refetchArgoSectionStatus } = argoStatusQuery
212
+ const { data: argoSectionStatus } = argoStatusQuery
213
+ const { data: prometheusStatus } = usePrometheusStatus(open && !!configData?.integrationProfiles)
214
+ const source = prometheusStatus?.source
215
+ const sourceKey = prometheusStatus && JSON.stringify([
216
+ source?.kind, source?.via, source?.pending, source?.matchedBy, source?.unavailable,
217
+ source?.clusterLabel?.name, source?.clusterLabel?.value, source?.dialect,
218
+ ])
219
+ const previousSourceKey = useRef<string | undefined>(undefined)
220
+ useEffect(() => {
221
+ const previous = previousSourceKey.current
222
+ previousSourceKey.current = open ? sourceKey : undefined
223
+ if (open && previous !== undefined && sourceKey !== undefined && previous !== sourceKey) {
224
+ void invalidateIntegrationQueries(queryClient, ['metrics'], { includeStatus: false })
225
+ }
226
+ }, [open, sourceKey, queryClient])
212
227
 
213
228
  // Local AI preferences save independently of the owner-gated server settings.
214
229
  const diag = useDiagnose()
@@ -424,10 +439,7 @@ export function SettingsDialog({
424
439
  ...prev,
425
440
  file: { ...prev.file, opencostCurrency: saved.opencostCurrency },
426
441
  } : prev)
427
- void queryClient.invalidateQueries({
428
- predicate: (query) =>
429
- typeof query.queryKey[0] === 'string' && query.queryKey[0].startsWith('opencost-'),
430
- })
442
+ void invalidateIntegrationQueries(queryClient, ['cost'])
431
443
  } finally {
432
444
  costCurrencySavingRef.current = false
433
445
  setCostCurrencySaving(false)
@@ -787,6 +799,7 @@ export function SettingsDialog({
787
799
  urlFromFlag={configData?.prometheusUrlFromFlag === true}
788
800
  onChange={(v) => updateConfigField('prometheusUrl', v || undefined)}
789
801
  onApplied={(url) => {
802
+ void invalidateIntegrationQueries(queryClient, ['metrics'])
790
803
  setEditedConfig((prev) => ({ ...prev, prometheusUrl: url || undefined }))
791
804
  setConfigData((prev) =>
792
805
  prev ? {
@@ -838,9 +851,7 @@ export function SettingsDialog({
838
851
  file: { ...prev.file, costSource: source, kubecostUrl: url || undefined, kubecostClusterId: clusterId || undefined },
839
852
  kubecostApiKeySet: apiKeySet,
840
853
  } : prev)
841
- void queryClient.invalidateQueries({
842
- predicate: (query) => typeof query.queryKey[0] === 'string' && query.queryKey[0].startsWith('opencost-'),
843
- })
854
+ void invalidateIntegrationQueries(queryClient, ['cost'])
844
855
  }}
845
856
  />
846
857
  </SectionPane>
@@ -880,13 +891,7 @@ export function SettingsDialog({
880
891
  }
881
892
  : prev
882
893
  )
883
- void refetchArgoSectionStatus()
884
- // The GitOps detail page the user came from doesn't poll
885
- // when idle; without this the notice that sent them here
886
- // would still be up when they get back.
887
- void queryClient.invalidateQueries({
888
- predicate: (query) => typeof query.queryKey[0] === 'string' && query.queryKey[0].startsWith('gitops-'),
889
- })
894
+ void invalidateIntegrationQueries(queryClient, ['argocd'])
890
895
  }}
891
896
  />}
892
897
  </SectionPane>
@@ -0,0 +1,98 @@
1
+ import { QueryClient, QueryObserver } from '@tanstack/react-query'
2
+ import { describe, expect, it, vi } from 'vitest'
3
+ import { invalidateIntegrationQueries } from './integrationQueries'
4
+
5
+ describe('invalidateIntegrationQueries', () => {
6
+ it.each(['metrics', 'cost', 'argocd'] as const)('invalidates diagnostics after saving %s', async kind => {
7
+ const client = new QueryClient()
8
+ client.setQueryData(['diagnostics'], 'previous')
9
+
10
+ await invalidateIntegrationQueries(client, [kind])
11
+
12
+ expect(client.getQueryState(['diagnostics'])?.isInvalidated).toBe(true)
13
+ client.clear()
14
+ })
15
+
16
+ it('refreshes metrics dependents and the selected Argo views after reconfirming both', async () => {
17
+ const client = new QueryClient()
18
+ const affected = [
19
+ ['prometheus-status'], ['prometheus-rightsizing-scan'], ['workload-metrics'],
20
+ ['substrate-health'], ['cnpg', 'history'], ['cnpg', 'fleet-metrics'],
21
+ ['cnpg', 'storage'], ['cnpg', 'disk'], ['traffic-sources', 'recent'],
22
+ ['traffic-flows', 'records'], ['traffic-source-active'], ['traffic-connection'],
23
+ ['opencost-application-trend'], ['dashboard'], ['diagnostics'],
24
+ ['argocd-status'], ['gitops-tree'], ['gitops-insights'], ['argo-resource-diff'],
25
+ ['argo-sync-diff'], ['argo-revision-metadata'],
26
+ ]
27
+ const unaffected = [['cnpg', 'workspace'], ['cnpg', 'restore'], ['gitops-destination'], ['resources']]
28
+ for (const key of [...affected, ...unaffected]) client.setQueryData(key, 'cached')
29
+
30
+ await invalidateIntegrationQueries(client, ['metrics', 'argocd'])
31
+
32
+ expect(affected.filter(key => !client.getQueryState(key)?.isInvalidated)).toEqual([])
33
+ expect(unaffected.filter(key => client.getQueryState(key)?.isInvalidated)).toEqual([])
34
+ client.clear()
35
+ })
36
+
37
+ it('refetches an active cost view after a currency or cost-source save', async () => {
38
+ const client = new QueryClient()
39
+ const queryKey = ['opencost-summary']
40
+ client.setQueryData(queryKey, 'previous')
41
+ client.setQueryData(['prometheus-status'], 'previous')
42
+ const queryFn = vi.fn(async () => 'updated')
43
+ const observer = new QueryObserver(client, { queryKey, queryFn, staleTime: Infinity })
44
+ const unsubscribe = observer.subscribe(() => {})
45
+ try {
46
+ await invalidateIntegrationQueries(client, ['cost'])
47
+ expect(queryFn).toHaveBeenCalledTimes(1)
48
+ expect(client.getQueryData(queryKey)).toBe('updated')
49
+ expect(client.getQueryState(['prometheus-status'])?.isInvalidated).toBe(false)
50
+ } finally {
51
+ unsubscribe()
52
+ client.clear()
53
+ }
54
+ })
55
+
56
+ it('refreshes dependents without polling status again when OpenObserve settles', async () => {
57
+ const client = new QueryClient()
58
+ client.setQueryData(['prometheus-status'], 'settled')
59
+ client.setQueryData(['prometheus-cluster'], 'previous')
60
+
61
+ await invalidateIntegrationQueries(client, ['metrics'], { includeStatus: false })
62
+
63
+ expect(client.getQueryState(['prometheus-status'])?.isInvalidated).toBe(false)
64
+ expect(client.getQueryState(['prometheus-cluster'])?.isInvalidated).toBe(true)
65
+ client.clear()
66
+ })
67
+
68
+ it('replaces an in-flight first fetch when settings are saved', async () => {
69
+ const client = new QueryClient()
70
+ const queryKey = ['prometheus-cluster']
71
+ let resolvePrevious!: (data: string) => void
72
+ const previous = new Promise<string>(resolve => { resolvePrevious = resolve })
73
+ let oldSignal: AbortSignal | undefined
74
+ const queryFn = vi.fn()
75
+ .mockImplementationOnce(({ signal }) => {
76
+ oldSignal = signal
77
+ return previous
78
+ })
79
+ .mockResolvedValueOnce('updated')
80
+ const observer = new QueryObserver(client, { queryKey, queryFn })
81
+ const unsubscribe = observer.subscribe(() => {})
82
+ try {
83
+ expect(client.getQueryData(queryKey)).toBeUndefined()
84
+ expect(observer.getCurrentResult().isFetching).toBe(true)
85
+
86
+ await invalidateIntegrationQueries(client, ['metrics'])
87
+ resolvePrevious('previous')
88
+ await previous
89
+
90
+ expect(oldSignal?.aborted).toBe(true)
91
+ expect(queryFn).toHaveBeenCalledTimes(2)
92
+ expect(observer.getCurrentResult().data).toBe('updated')
93
+ } finally {
94
+ unsubscribe()
95
+ client.clear()
96
+ }
97
+ })
98
+ })
@@ -0,0 +1,36 @@
1
+ import type { QueryClient, QueryFilters } from '@tanstack/react-query'
2
+ import type { IntegrationKind } from './LocalConnectionSettings'
3
+
4
+ const metricsKeys = new Set([
5
+ 'workload-metrics', 'substrate-health', 'dashboard',
6
+ 'traffic-sources', 'traffic-flows', 'traffic-source-active', 'traffic-connection',
7
+ ])
8
+ const cnpgMetricsKeys = ['history', 'fleet-metrics', 'storage', 'disk']
9
+ const argoKeys = new Set([
10
+ 'argocd-status', 'gitops-tree', 'gitops-insights', 'argo-resource-diff',
11
+ 'argo-sync-diff', 'argo-revision-metadata',
12
+ ])
13
+
14
+ export async function invalidateIntegrationQueries(
15
+ client: QueryClient,
16
+ kinds: IntegrationKind[],
17
+ { includeStatus = true } = {},
18
+ ): Promise<void> {
19
+ const metrics = kinds.includes('metrics')
20
+ const cost = metrics || kinds.includes('cost')
21
+ const argo = kinds.includes('argocd')
22
+ const filters: QueryFilters = {
23
+ predicate: ({ queryKey: [root, section] }) => {
24
+ if (typeof root !== 'string') return false
25
+ if (root === 'diagnostics') return kinds.length > 0
26
+ if (cost && root.startsWith('opencost-')) return true
27
+ if (argo && argoKeys.has(root)) return true
28
+ if (!metrics) return false
29
+ if (root === 'prometheus-status') return includeStatus
30
+ return root.startsWith('prometheus-') || metricsKeys.has(root) ||
31
+ (root === 'cnpg' && typeof section === 'string' && cnpgMetricsKeys.includes(section))
32
+ },
33
+ }
34
+ await client.cancelQueries(filters)
35
+ await client.invalidateQueries(filters)
36
+ }