@skyhook-io/radar-app 1.19.0 → 1.20.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 (173) hide show
  1. package/README.md +1 -1
  2. package/package.json +5 -5
  3. package/src/App.tsx +31 -5
  4. package/src/api/application-evidence.ts +63 -0
  5. package/src/api/argoSync.test.ts +22 -0
  6. package/src/api/client.audit-gating.test.tsx +48 -0
  7. package/src/api/client.kueuePosition.test.ts +32 -0
  8. package/src/api/client.kueueQueueWorkloads.test.tsx +71 -0
  9. package/src/api/client.resource-identity.test.ts +3 -0
  10. package/src/api/client.resourceIssues.test.tsx +239 -0
  11. package/src/api/client.resourcePath.test.ts +3 -0
  12. package/src/api/client.ts +285 -55
  13. package/src/api/config.ts +21 -0
  14. package/src/api/diagnose.ts +4 -0
  15. package/src/api/radarFeatures.render.test.tsx +33 -1
  16. package/src/api/radarFeatures.test.ts +47 -0
  17. package/src/api/radarFeatures.ts +40 -1
  18. package/src/api/rbac.settled.test.tsx +42 -0
  19. package/src/api/rbac.test.ts +18 -0
  20. package/src/api/rbac.ts +37 -7
  21. package/src/api/traffic.ts +9 -4
  22. package/src/api/usage-data.fixtures.ts +3 -1
  23. package/src/api/usage-data.test.tsx +134 -0
  24. package/src/api/usage-data.ts +35 -7
  25. package/src/api/workloadPodsPolling.test.ts +26 -0
  26. package/src/components/CloudConnectFlow.test.tsx +86 -0
  27. package/src/components/CloudConnectFlow.tsx +65 -27
  28. package/src/components/CloudFunnelButton.test.tsx +140 -5
  29. package/src/components/CloudFunnelButton.tsx +50 -9
  30. package/src/components/ConnectionErrorView.test.tsx +34 -0
  31. package/src/components/ConnectionErrorView.tsx +35 -11
  32. package/src/components/ContextSwitcher.tsx +5 -2
  33. package/src/components/SwitchAwareConnectionError.test.tsx +43 -0
  34. package/src/components/SwitchAwareConnectionError.tsx +85 -0
  35. package/src/components/application-evidence/ApplicationEvidenceAction.flow.test.tsx +234 -0
  36. package/src/components/application-evidence/ApplicationEvidenceAction.test.tsx +144 -0
  37. package/src/components/application-evidence/ApplicationEvidenceAction.tsx +218 -0
  38. package/src/components/capacity/CapacityDemand.tsx +3 -2
  39. package/src/components/capacity/demandSummary.test.ts +38 -0
  40. package/src/components/capacity/shared.tsx +12 -1
  41. package/src/components/cost/ApplicationCostTab.tsx +4 -0
  42. package/src/components/cost/CostTrendChart.tsx +2 -0
  43. package/src/components/cost/WorkloadCostTab.tsx +4 -0
  44. package/src/components/cost/source.test.ts +5 -0
  45. package/src/components/cost/source.ts +11 -0
  46. package/src/components/diagnose/AIMarkdown.tsx +3 -0
  47. package/src/components/diagnose/AgentSetupNotice.test.tsx +17 -0
  48. package/src/components/diagnose/AgentSetupNotice.tsx +21 -3
  49. package/src/components/diagnose/ContinueInAgentButton.mounted.test.tsx +182 -0
  50. package/src/components/diagnose/ContinueInAgentButton.test.tsx +128 -0
  51. package/src/components/diagnose/ContinueInAgentButton.tsx +303 -0
  52. package/src/components/diagnose/DiagnoseContext.question.test.tsx +1 -1
  53. package/src/components/diagnose/DiagnoseContext.tsx +68 -2
  54. package/src/components/diagnose/DiagnoseSurface.tsx +58 -113
  55. package/src/components/diagnose/ExampleInvestigationLink.tsx +20 -0
  56. package/src/components/diagnose/Home.test.tsx +26 -0
  57. package/src/components/diagnose/Home.tsx +20 -1
  58. package/src/components/diagnose/InvestigationEvidenceSections.tsx +45 -22
  59. package/src/components/diagnose/InvestigationView.tsx +94 -26
  60. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +450 -0
  61. package/src/components/diagnose/LocalDiagnoseAction.tsx +354 -35
  62. package/src/components/diagnose/NextStepJump.test.tsx +92 -0
  63. package/src/components/diagnose/NextStepJump.tsx +75 -0
  64. package/src/components/diagnose/QuestionComposer.tsx +8 -0
  65. package/src/components/diagnose/exampleInvestigation.events.json +191 -0
  66. package/src/components/diagnose/exampleInvestigation.loadFailure.test.tsx +94 -0
  67. package/src/components/diagnose/exampleInvestigation.test.tsx +248 -0
  68. package/src/components/diagnose/exampleInvestigation.ts +121 -0
  69. package/src/components/diagnose/investigationCase.test.tsx +9 -1
  70. package/src/components/diagnose/investigationEvidence/adapters/applicationFindings.test.ts +739 -0
  71. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +50 -2
  72. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +9 -0
  73. package/src/components/diagnose/investigationEvidence/builder.ts +30 -0
  74. package/src/components/diagnose/investigationEvidence/observations.ts +121 -2
  75. package/src/components/diagnose/investigationEvidence/projection.test.ts +85 -3
  76. package/src/components/diagnose/investigationEvidence/types.ts +5 -0
  77. package/src/components/diagnose/investigationState.ts +28 -0
  78. package/src/components/diagnose/lastInvestigation.test.ts +95 -0
  79. package/src/components/diagnose/lastInvestigation.ts +58 -0
  80. package/src/components/diagnose/launch.test.ts +125 -1
  81. package/src/components/diagnose/launch.ts +57 -10
  82. package/src/components/diagnose/toolCallLabel.test.ts +10 -4
  83. package/src/components/execution/BatchExecutionView.tsx +24 -11
  84. package/src/components/execution/JobSetAdmission.test.tsx +42 -0
  85. package/src/components/execution/JobSetAdmission.tsx +18 -3
  86. package/src/components/execution/JobSetMemberComparison.tsx +2 -1
  87. package/src/components/execution/runState.test.ts +14 -0
  88. package/src/components/execution/runState.ts +8 -0
  89. package/src/components/gitops/GitOpsView.rollbackGate.test.tsx +202 -0
  90. package/src/components/gitops/GitOpsView.syncRequest.test.tsx +369 -0
  91. package/src/components/gitops/GitOpsView.tsx +86 -17
  92. package/src/components/gitops/RemoteDestinationCloudHint.tsx +2 -3
  93. package/src/components/gitops/destination-toast.test.ts +1 -1
  94. package/src/components/gitops/destination-toast.ts +2 -2
  95. package/src/components/home/ClusterHealthCard.tsx +1 -1
  96. package/src/components/home/HomeAgentBlock.test.tsx +31 -3
  97. package/src/components/home/HomeAgentBlock.tsx +13 -4
  98. package/src/components/home/HomeDiagramCard.tsx +47 -0
  99. package/src/components/home/HomeView.tsx +81 -41
  100. package/src/components/home/MCPSetupDialog.test.tsx +95 -5
  101. package/src/components/home/MCPSetupDialog.tsx +30 -5
  102. package/src/components/home/ProblemsPanel.investigate.test.tsx +171 -0
  103. package/src/components/home/ProblemsPanel.test.tsx +3 -1
  104. package/src/components/home/TopologyPreview.test.tsx +73 -0
  105. package/src/components/home/TopologyPreview.tsx +120 -233
  106. package/src/components/home/TrafficSummary.test.tsx +63 -0
  107. package/src/components/home/TrafficSummary.tsx +135 -138
  108. package/src/components/home/mcpToolCatalog.ts +23 -10
  109. package/src/components/issues/IssuesPane.test.ts +11 -0
  110. package/src/components/issues/IssuesPane.tsx +15 -5
  111. package/src/components/issues/uncheckedSources.test.ts +20 -1
  112. package/src/components/issues/uncheckedSources.ts +18 -0
  113. package/src/components/kueue/KueuePendingPosition.tsx +35 -0
  114. package/src/components/kueue/useRelatedObjects.test.tsx +219 -0
  115. package/src/components/kueue/useRelatedReads.test.ts +56 -0
  116. package/src/components/kueue/useRelatedReads.ts +205 -0
  117. package/src/components/logs/MultiPodLogsTab.test.tsx +93 -0
  118. package/src/components/logs/MultiPodLogsTab.tsx +120 -0
  119. package/src/components/logs/PodLogsUnavailable.test.tsx +18 -0
  120. package/src/components/logs/PodLogsUnavailable.tsx +21 -0
  121. package/src/components/logs/RayClusterLogsTab.reselect.test.tsx +67 -0
  122. package/src/components/logs/RayClusterLogsTab.test.tsx +167 -0
  123. package/src/components/logs/RayClusterLogsTab.tsx +109 -0
  124. package/src/components/logs/ScheduledWorkloadLogsViewer.tsx +3 -2
  125. package/src/components/logs/rayClusterPods.ts +32 -0
  126. package/src/components/outageSince.test.ts +21 -0
  127. package/src/components/outageSince.ts +10 -0
  128. package/src/components/resource/PrometheusCharts.overlays.test.ts +12 -0
  129. package/src/components/resource/PrometheusCharts.tsx +3 -40
  130. package/src/components/resources/crd/CRDSchemaTab.test.tsx +28 -0
  131. package/src/components/resources/crd/CRDSchemaTab.tsx +13 -0
  132. package/src/components/resources/crd/host.tsx +14 -0
  133. package/src/components/resources/renderers/CustomResourceDefinitionRenderer.test.tsx +27 -0
  134. package/src/components/resources/renderers/CustomResourceDefinitionRenderer.tsx +12 -0
  135. package/src/components/resources/renderers/JobAdmissionRenderers.test.tsx +4 -1
  136. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +4 -3
  137. package/src/components/resources/renderers/KueueHostRenderers.test.tsx +117 -0
  138. package/src/components/resources/renderers/KueueQueueRenderers.test.tsx +97 -0
  139. package/src/components/resources/renderers/KueueQueueRenderers.tsx +139 -0
  140. package/src/components/resources/renderers/KueueWorkloadRenderer.test.tsx +7 -1
  141. package/src/components/resources/renderers/KueueWorkloadRenderer.tsx +47 -7
  142. package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.test.tsx +67 -0
  143. package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.tsx +31 -0
  144. package/src/components/resources/renderers/RayClusterRenderer.test.tsx +81 -3
  145. package/src/components/resources/renderers/RayClusterRenderer.tsx +19 -4
  146. package/src/components/traffic/TrafficView.tsx +3 -3
  147. package/src/components/ui/command-items-crd.test.tsx +23 -0
  148. package/src/components/ui/command-items.ts +2 -1
  149. package/src/components/useContextSwitchFlow.test.tsx +61 -0
  150. package/src/components/useContextSwitchFlow.tsx +21 -4
  151. package/src/components/whats-new/WhatsNew.test.ts +10 -3
  152. package/src/components/whats-new/WhatsNew.tsx +5 -1
  153. package/src/components/whats-new/WhatsNewDialog.test.tsx +17 -3
  154. package/src/components/whats-new/releaseNotes.ts +77 -4
  155. package/src/components/workload/RelatedFindingsSection.test.tsx +126 -0
  156. package/src/components/workload/RelatedFindingsSection.tsx +80 -0
  157. package/src/components/workload/WorkloadView.test.ts +10 -1
  158. package/src/components/workload/WorkloadView.tsx +85 -98
  159. package/src/components/workload/issueResourceOpener.test.ts +20 -0
  160. package/src/components/workload/issueResourceOpener.ts +17 -0
  161. package/src/context/ConnectionContext.tsx +133 -60
  162. package/src/context/ConnectionProvider.retry.test.tsx +176 -0
  163. package/src/context/ContextSwitchContext.tsx +14 -1
  164. package/src/context/DiagnoseCustomization.tsx +3 -0
  165. package/src/context/clusterConnected.ts +10 -0
  166. package/src/contexts/CapabilitiesContext.tsx +6 -4
  167. package/src/hooks/useElementSize.ts +30 -0
  168. package/src/integrations/resourceHost.test.tsx +1 -0
  169. package/src/integrations/resourceHost.ts +5 -1
  170. package/src/integrations/resourceHosts.test.tsx +21 -4
  171. package/src/integrations/resourceHosts.tsx +12 -0
  172. package/src/main.tsx +5 -0
  173. package/src/utils/related-findings.ts +46 -0
package/src/api/config.ts CHANGED
@@ -133,3 +133,24 @@ export function setCredentialsMode(mode: RequestCredentials): void {
133
133
  export function getCredentialsMode(): RequestCredentials {
134
134
  return credentialsMode;
135
135
  }
136
+
137
+ let markAutomaticRequests = false;
138
+
139
+ /**
140
+ * Internal: Radar's own entry point turns the automatic-request mark on at
141
+ * startup, and the usage status then keeps it on only while usage data is
142
+ * recorded. Off, requests carry nothing extra, which also keeps an embedding
143
+ * host free of a header its proxy might refuse.
144
+ */
145
+ export function setAutomaticRequestMarking(on: boolean): void {
146
+ markAutomaticRequests = on;
147
+ }
148
+
149
+ /**
150
+ * Headers for a request the UI makes on its own (a background probe, a
151
+ * reconnect attempt) rather than for something the user did, so the opt-in
152
+ * usage report does not count it as an action.
153
+ */
154
+ export function automaticRequestHeaders(): Record<string, string> {
155
+ return markAutomaticRequests ? { 'X-Radar-Request-Origin': 'auto' } : {};
156
+ }
@@ -255,6 +255,10 @@ export interface RunSummary {
255
255
  status: "running" | "stopping" | "done" | "error" | "stopped" | "stale";
256
256
  sessionId?: string;
257
257
  preview?: string;
258
+ /** When the turn behind preview finished. Set only when preview is an
259
+ * assessment Findings shows; absent before any, or when the server
260
+ * doesn't record it. */
261
+ assessedAt?: string;
258
262
  createdAt: string;
259
263
  updatedAt: string;
260
264
  visibility?: "private" | "organization";
@@ -4,7 +4,7 @@ import { createRoot } from 'react-dom/client'
4
4
  import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
5
  import { afterEach, beforeEach, expect, it, vi } from 'vitest'
6
6
  import { getRadarUpgradeRequirement } from '@skyhook-io/k8s-ui'
7
- import { ApiError, isNotFoundError, useApplications, useCapacityPoolDetail, useDrainPlan, useNodeRemovalPlan, usePodEnvironment, useSubjectIssues, useWorkloadHistory } from './client'
7
+ import { ApiError, isNotFoundError, useApplications, useCapacityPoolDetail, useDrainPlan, useNodeRemovalPlan, usePodEnvironment, useRadarFeature, useSubjectIssues, useWorkloadHistory } from './client'
8
8
  import { getApiBase } from './config'
9
9
  import { usePolicyResource } from './policy'
10
10
  import { isRadarFeatureUnsupported } from './radarFeatures'
@@ -283,3 +283,35 @@ it('asks again once capabilities confirm workload history after a probe hit an o
283
283
  await settle()
284
284
  expect(requested.filter((url) => url.includes('/history'))).toHaveLength(2)
285
285
  })
286
+
287
+ function ArgoRollbackGate() {
288
+ const { upgrade, blockedReason } = useRadarFeature('argoRollback')
289
+ return <span>{blockedReason || (upgrade ? `${upgrade.feature} @ ${upgrade.currentVersion}` : 'enabled')}</span>
290
+ }
291
+
292
+ it('hands a control the upgrade requirement once capabilities omit its flag', async () => {
293
+ client.setQueryData(['capabilities'], { features: { workloadHistory: true } })
294
+ await render(<ArgoRollbackGate />)
295
+ expect(element.textContent).toBe('Argo CD rollbacks @ v1.7.2')
296
+ })
297
+
298
+ it('reports that support could not be checked when /api/capabilities fails', async () => {
299
+ const answer = vi.mocked(fetch).getMockImplementation()!
300
+ vi.mocked(fetch).mockImplementation((input, init) =>
301
+ String(input).endsWith('/capabilities')
302
+ ? Promise.resolve(Response.json({ error: 'capabilities down' }, { status: 500 }))
303
+ : answer(input, init),
304
+ )
305
+ await render(<ArgoRollbackGate />)
306
+ await settle()
307
+ expect(element.textContent).toBe("Couldn't check this cluster's Radar support. Refresh to try again.")
308
+ })
309
+
310
+ it('keeps a control checking until capabilities carry its flag', async () => {
311
+ await render(<ArgoRollbackGate />)
312
+ expect(element.textContent).toBe("Checking this cluster's Radar…")
313
+
314
+ await act(async () => { client.setQueryData(['capabilities'], { features: { argoRollbackSync: true } }) })
315
+ await settle()
316
+ expect(element.textContent).toBe('enabled')
317
+ })
@@ -6,6 +6,8 @@ import {
6
6
  RadarFeatureUnsupportedError,
7
7
  guardRadarFeature,
8
8
  isRadarFeatureUnsupported,
9
+ radarControlBlocked,
10
+ radarControlBlockedReason,
9
11
  radarFeatureSupport,
10
12
  radarSpecSupport,
11
13
  type RadarFeatureSpec,
@@ -65,6 +67,28 @@ describe('workload history, whose flag shipped with its endpoint', () => {
65
67
  })
66
68
  })
67
69
 
70
+ // A behavior change on endpoints every Radar serves: only the flag tells.
71
+ describe('Argo CD rollback and auto-sync, gated on argoRollbackSync', () => {
72
+ it.each(['argoRollback', 'argoAutoSyncEnable'] as const)('%s trusts the flag and reads its absence as too old', (feature) => {
73
+ expect(radarFeatureSupport(feature, { features: { argoRollbackSync: true } }, 'v1.16.3')).toBe('supported')
74
+ expect(radarFeatureSupport(feature, { features: { workloadHistory: true } }, 'v1.16.3')).toBe('unsupported')
75
+ expect(radarFeatureSupport(feature, {}, 'dev')).toBe('unsupported')
76
+ expect(radarFeatureSupport(feature, undefined, 'v1.16.3')).toBe('unknown')
77
+ })
78
+ })
79
+
80
+ describe('radarControlBlocked', () => {
81
+ // A control can't be probed like a request: its outcome on an older Radar
82
+ // is wrong, not a 404. So it fails closed when /api/capabilities failed,
83
+ // and stays usable only while the answer is still loading.
84
+ it('blocks a known-old Radar, and an unknown one whose capabilities failed', () => {
85
+ expect(radarControlBlocked('unsupported', false)).toBe(true)
86
+ expect(radarControlBlocked('unknown', true)).toBe(true)
87
+ expect(radarControlBlocked('unknown', false)).toBe(false)
88
+ expect(radarControlBlocked('supported', true)).toBe(false)
89
+ })
90
+ })
91
+
68
92
  describe('radarSpecSupport for a feature whose flag shipped with its endpoint', () => {
69
93
  const driftAlerts: RadarFeatureSpec = { label: 'Drift alerts', flag: 'resourceIssues', flagShippedWithEndpoint: true }
70
94
 
@@ -140,3 +164,26 @@ describe('shouldRetryRadarQuery', () => {
140
164
  }
141
165
  })
142
166
  })
167
+
168
+ describe('affirmative mutation support', () => {
169
+ it.each(['argoRollback', 'argoAutoSyncEnable'] as const)('%s distinguishes checking, failed and known answers', feature => {
170
+ expect(radarControlBlockedReason(feature, 'unknown', false)).toBe("Checking this cluster's Radar…")
171
+ expect(radarControlBlockedReason(feature, 'unknown', true)).toBe("Couldn't check this cluster's Radar support. Refresh to try again.")
172
+ expect(radarControlBlockedReason(feature, 'supported', false)).toBeUndefined()
173
+ expect(radarControlBlockedReason(feature, 'supported', true)).toBe("Couldn't check this cluster's Radar support. Refresh to try again.")
174
+ expect(radarControlBlockedReason(feature, 'unsupported', false)).toBeUndefined()
175
+ })
176
+ it('preserves permissive loading for other features', () => {
177
+ expect(radarControlBlockedReason('workloadHistory', 'unknown', false)).toBeUndefined()
178
+ expect(radarControlBlocked('unknown', false)).toBe(false)
179
+ })
180
+ })
181
+
182
+ describe('RayCluster runtime Pods, whose flag came after its route', () => {
183
+ it('trusts the flag, and otherwise the first release that served the route', () => {
184
+ expect(radarFeatureSupport('rayClusterPods', { features: { rayClusterPods: true } }, 'v1.14.0')).toBe('supported')
185
+ expect(radarFeatureSupport('rayClusterPods', { features: { resourceIssues: true } }, 'v1.15.0')).toBe('supported')
186
+ expect(radarFeatureSupport('rayClusterPods', { features: { resourceIssues: true } }, 'v1.14.1')).toBe('unsupported')
187
+ expect(radarFeatureSupport('rayClusterPods', { features: {} }, 'dev')).toBe('unknown')
188
+ })
189
+ })
@@ -11,7 +11,9 @@ import { compareVersions } from '../utils/version'
11
11
  // an entry here with that flag and `flagShippedWithEndpoint: true`, and guard
12
12
  // its hook with useRadarFeature. TestFeatureFlagsHaveFrontendGates keeps the
13
13
  // two lists in step. `minimumVersion` can wait for the release to be cut:
14
- // until then the note asks for the latest Radar.
14
+ // until then the note asks for the latest Radar. A behavior change on an
15
+ // existing endpoint is gated the same way, except that the control relying on
16
+ // it is disabled: an older Radar still answers the request, wrongly.
15
17
  export interface RadarFeatureSpec {
16
18
  /** Plural noun phrase; the upgrade note reads "<label> need Radar vX or newer." */
17
19
  label: string
@@ -24,16 +26,20 @@ export interface RadarFeatureSpec {
24
26
  * entries below, whose flags were added after their endpoints.
25
27
  */
26
28
  flagShippedWithEndpoint?: boolean
29
+ requireAffirmativeSupport?: boolean
27
30
  }
28
31
 
29
32
  export const RADAR_FEATURES = {
30
33
  resourceReadCoverage: { label: 'Resource read coverage', flag: 'resourceReadCoverage', flagShippedWithEndpoint: true },
31
34
  searchCoverage: { label: 'Search coverage and object filters', flag: 'searchCoverage', flagShippedWithEndpoint: true },
35
+ applicationEvidence: { label: 'Application evidence collection', flag: 'applicationEvidence', flagShippedWithEndpoint: true },
32
36
  resourceIssues: { label: 'Operational issues', minimumVersion: 'v1.8.0', flag: 'resourceIssues' },
33
37
  resourceIssueCoverage: { label: 'Resource-specific issue views', flag: 'resourceIssueCoverage', flagShippedWithEndpoint: true },
34
38
  podEnvironment: { label: 'Values from ConfigMaps and Secrets', minimumVersion: 'v1.9.0', flag: 'podEnvironment' },
35
39
  policyResource: { label: 'Policy results', minimumVersion: 'v1.10.0', flag: 'policyResource' },
36
40
  capacity: { label: 'Capacity views', minimumVersion: 'v1.9.0' },
41
+ // Radars from v1.15.0 serve the route without advertising the flag.
42
+ rayClusterPods: { label: 'RayCluster runtime Pods', minimumVersion: 'v1.15.0', flag: 'rayClusterPods' },
37
43
  upgradeReadiness: { label: 'Upgrade impact reports', minimumVersion: 'v1.9.0' },
38
44
  drainPlan: { label: 'Drain plans', minimumVersion: 'v1.14.0' },
39
45
  applications: { label: 'Applications', minimumVersion: 'v1.7.7' },
@@ -43,6 +49,22 @@ export const RADAR_FEATURES = {
43
49
  gitopsWriteEvidence: { label: 'GitOps revert warnings', flag: 'gitopsWriteEvidence', flagShippedWithEndpoint: true },
44
50
  serviceEndpointSlices: { label: 'Service EndpointSlice inventories', flag: 'serviceEndpointSlices', flagShippedWithEndpoint: true },
45
51
  trafficRecords: { label: 'Flow records for a graph selection', flag: 'trafficRecords', flagShippedWithEndpoint: true },
52
+ kueuePendingPosition: { label: 'Kueue queue positions', flag: 'kueuePendingPosition', flagShippedWithEndpoint: true },
53
+ kueueQueueWorkloads: { label: 'Workload lists on Kueue queues', flag: 'kueueQueueWorkloads', flagShippedWithEndpoint: true },
54
+ // One flag, two controls. An older Radar's rollback never runs, and its
55
+ // resume reports success while leaving automated.enabled: false in place.
56
+ argoRollback: { label: 'Argo CD rollbacks', flag: 'argoRollbackSync', flagShippedWithEndpoint: true, requireAffirmativeSupport: true },
57
+ argoAutoSyncEnable: { label: 'Auto-sync controls for Applications with automated.enabled: false', flag: 'argoRollbackSync', flagShippedWithEndpoint: true, requireAffirmativeSupport: true },
58
+ // Never blocks a control. An older Radar's sync drops the Application's
59
+ // sync options when the request omits them, and prunes when it omits prune,
60
+ // so useArgoSync sends both explicitly unless this is supported. Also tells
61
+ // the UI that Enable auto-sync on a never-suspended Application starts with
62
+ // prune off.
63
+ argoSyncInheritance: { label: "Syncs that keep the Application's sync options", flag: 'argoSyncInheritance', flagShippedWithEndpoint: true },
64
+ // Never blocks a control: tells the UI that Enable auto-sync on a
65
+ // never-suspended Application starts with selfHeal off; an older Radar
66
+ // turns it on.
67
+ argoEnableSelfHealOff: { label: 'Auto-sync that starts without self-heal', flag: 'argoEnableSelfHealOff', flagShippedWithEndpoint: true },
46
68
  helmSourceIdentity: { label: 'Helm source selection', flag: 'helmSourceIdentity', flagShippedWithEndpoint: true },
47
69
  agentSigninCheck: { label: 'Agent sign-in checks', flag: 'agentSigninCheck', flagShippedWithEndpoint: true },
48
70
  } as const satisfies Record<string, RadarFeatureSpec>
@@ -89,6 +111,23 @@ export function radarFeatureSupport(
89
111
  return radarSpecSupport(RADAR_FEATURES[feature], capabilities, currentVersion)
90
112
  }
91
113
 
114
+ /**
115
+ * Whether a control backed by `feature` renders disabled with the upgrade
116
+ * note. A request can be probed, but a control's outcome can't, so a control
117
+ * also stays disabled when /api/capabilities failed, as CapabilitiesContext
118
+ * fails closed on the same error. While it loads, the control stays enabled.
119
+ */
120
+ export function radarControlBlocked(support: RadarFeatureSupport, capabilitiesFailed: boolean): boolean {
121
+ return support === 'unsupported' || (support === 'unknown' && capabilitiesFailed)
122
+ }
123
+
124
+ export function radarControlBlockedReason(feature: RadarFeature, support: RadarFeatureSupport, capabilitiesFailed: boolean): string | undefined {
125
+ const spec: RadarFeatureSpec = RADAR_FEATURES[feature]
126
+ if (!spec.requireAffirmativeSupport) return undefined
127
+ if (capabilitiesFailed) return "Couldn't check this cluster's Radar support. Refresh to try again."
128
+ return support === 'unknown' ? "Checking this cluster's Radar…" : undefined
129
+ }
130
+
92
131
  export function radarUpgradeRequirement(feature: RadarFeature, versions: RadarVersions): RadarUpgradeRequirement {
93
132
  const spec: RadarFeatureSpec = RADAR_FEATURES[feature]
94
133
  return {
@@ -0,0 +1,42 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { afterEach, describe, expect, it, vi } from 'vitest'
6
+ import { useRBACSubject } from './rbac'
7
+
8
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
9
+
10
+ function Probe() {
11
+ useRBACSubject('ServiceAccount', 'shop', 'default')
12
+ return null
13
+ }
14
+
15
+ afterEach(() => vi.unstubAllGlobals())
16
+
17
+ // Opens the "drawer" twice on one query client and counts RBAC requests.
18
+ async function requestsOverTwoOpens(status: number, error: string) {
19
+ const fetchMock = vi.fn<(input: RequestInfo | URL) => Promise<Response>>(async () =>
20
+ new Response(JSON.stringify({ error }), { status, headers: { 'Content-Type': 'application/json' } }))
21
+ vi.stubGlobal('fetch', fetchMock)
22
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
23
+ for (let open = 0; open < 2; open++) {
24
+ const root = createRoot(document.createElement('div'))
25
+ await act(async () => {
26
+ root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>)
27
+ })
28
+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)) })
29
+ act(() => root.unmount())
30
+ }
31
+ return fetchMock.mock.calls.filter(([input]) => String(input).includes('/rbac/subject')).length
32
+ }
33
+
34
+ describe('useRBACSubject', () => {
35
+ it('asks once when Radar cannot read RBAC', async () => {
36
+ expect(await requestsOverTwoOpens(503, 'RBAC cache not available (informers not synced)')).toBe(1)
37
+ })
38
+
39
+ it('asks again on the next open after any other failure', async () => {
40
+ expect(await requestsOverTwoOpens(404, 'not found')).toBe(2)
41
+ })
42
+ })
@@ -0,0 +1,18 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { isRBACCacheUnavailable } from './rbac'
3
+
4
+ function fetchError(status: number, message: string) {
5
+ return Object.assign(new Error(message), { status })
6
+ }
7
+
8
+ describe('isRBACCacheUnavailable', () => {
9
+ it('recognizes the settled answer from a Radar that cannot read RBAC', () => {
10
+ expect(isRBACCacheUnavailable(fetchError(503, 'RBAC cache not available (informers not synced or RBAC reads disabled for the Radar SA)'))).toBe(true)
11
+ })
12
+
13
+ it('leaves other outages to the normal retry', () => {
14
+ expect(isRBACCacheUnavailable(fetchError(503, 'Not connected to cluster'))).toBe(false)
15
+ expect(isRBACCacheUnavailable(fetchError(500, 'RBAC cache exploded'))).toBe(false)
16
+ expect(isRBACCacheUnavailable(null)).toBe(false)
17
+ })
18
+ })
package/src/api/rbac.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { useQuery } from '@tanstack/react-query'
1
+ import { useQuery, useQueryClient } from '@tanstack/react-query'
2
2
  import type {
3
3
  RBACSubjectResponse,
4
4
  RBACRoleResponse,
@@ -6,6 +6,27 @@ import type {
6
6
  RBACNamespaceResponse,
7
7
  } from '@skyhook-io/k8s-ui'
8
8
  import { fetchJSON } from './client'
9
+ import { shouldRetryRadarQuery } from './radarFeatures'
10
+
11
+ // The server answers 503 "RBAC cache not available" when the identity Radar
12
+ // connects with can't read RBAC. That holds until the next connection, so a
13
+ // retry, or a refetch on every drawer open, only repeats the same answer.
14
+ // Reconnecting removes errored RBAC queries and a context switch removes all
15
+ // queries, so the next look after either asks again.
16
+ export function isRBACCacheUnavailable(error: unknown): boolean {
17
+ const e = error as { status?: unknown; message?: unknown } | null
18
+ return e?.status === 503 && typeof e.message === 'string' && e.message.includes('RBAC cache')
19
+ }
20
+
21
+ function retryRBACQuery(failureCount: number, error: unknown): boolean {
22
+ return !isRBACCacheUnavailable(error) && shouldRetryRadarQuery(failureCount, error)
23
+ }
24
+
25
+ // Pauses one RBAC query, and only while its stored answer is the settled
26
+ // "can't read RBAC" 503; any other error still refetches when the drawer opens.
27
+ function useRBACAnswerSettled(queryKey: readonly unknown[]): boolean {
28
+ return isRBACCacheUnavailable(useQueryClient().getQueryState(queryKey)?.error)
29
+ }
9
30
 
10
31
  // /api/rbac/subject/{kind}/{namespace}/{name} (ServiceAccount)
11
32
  // /api/rbac/subject/{kind}/{name} (User/Group — no namespace)
@@ -17,10 +38,13 @@ export function useRBACSubject(kind: 'ServiceAccount' | 'User' | 'Group', namesp
17
38
  kind === 'ServiceAccount'
18
39
  ? `/rbac/subject/${kind}/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`
19
40
  : `/rbac/subject/${kind}/${encodeURIComponent(name)}`
41
+ const queryKey = ['rbac', 'subject', kind, namespace, name]
42
+ const settled = useRBACAnswerSettled(queryKey)
20
43
  return useQuery<RBACSubjectResponse>({
21
- queryKey: ['rbac', 'subject', kind, namespace, name],
44
+ queryKey,
45
+ retry: retryRBACQuery,
22
46
  queryFn: () => fetchJSON<RBACSubjectResponse>(path),
23
- enabled: enabled && !!name && (kind !== 'ServiceAccount' || !!namespace),
47
+ enabled: enabled && !settled && !!name && (kind !== 'ServiceAccount' || !!namespace),
24
48
  staleTime: 15000,
25
49
  })
26
50
  }
@@ -28,20 +52,26 @@ export function useRBACSubject(kind: 'ServiceAccount' | 'User' | 'Group', namesp
28
52
  // /api/rbac/role/{kind}/{namespace}/{name} (use "_" for ClusterRole's empty namespace)
29
53
  export function useRBACRole(kind: 'Role' | 'ClusterRole', namespace: string, name: string, enabled = true) {
30
54
  const nsSegment = kind === 'ClusterRole' ? '_' : encodeURIComponent(namespace)
55
+ const queryKey = ['rbac', 'role', kind, namespace, name]
56
+ const settled = useRBACAnswerSettled(queryKey)
31
57
  return useQuery<RBACRoleResponse>({
32
- queryKey: ['rbac', 'role', kind, namespace, name],
58
+ queryKey,
59
+ retry: retryRBACQuery,
33
60
  queryFn: () => fetchJSON<RBACRoleResponse>(`/rbac/role/${kind}/${nsSegment}/${encodeURIComponent(name)}`),
34
- enabled: enabled && !!name && (kind !== 'Role' || !!namespace),
61
+ enabled: enabled && !settled && !!name && (kind !== 'Role' || !!namespace),
35
62
  staleTime: 15000,
36
63
  })
37
64
  }
38
65
 
39
66
  // /api/rbac/namespace/{namespace}
40
67
  export function useRBACNamespace(namespace: string, enabled = true) {
68
+ const queryKey = ['rbac', 'namespace', namespace]
69
+ const settled = useRBACAnswerSettled(queryKey)
41
70
  return useQuery<RBACNamespaceResponse>({
42
- queryKey: ['rbac', 'namespace', namespace],
71
+ queryKey,
72
+ retry: retryRBACQuery,
43
73
  queryFn: () => fetchJSON<RBACNamespaceResponse>(`/rbac/namespace/${encodeURIComponent(namespace)}`),
44
- enabled: enabled && !!namespace,
74
+ enabled: enabled && !settled && !!namespace,
45
75
  staleTime: 15000,
46
76
  })
47
77
  }
@@ -3,7 +3,7 @@ import { useQuery, useMutation, useQueryClient, type QueryClient } from '@tansta
3
3
  import type { TrafficSourcesResponse, TrafficFlowsResponse, TrafficRecordsResponse } from '../types'
4
4
  import { fetchJSON as fetchApiJSON, useRadarFeature } from './client'
5
5
  import { shouldRetryRadarQuery } from './radarFeatures'
6
- import { apiUrl, getAuthHeaders, getCredentialsMode } from './config'
6
+ import { apiUrl, automaticRequestHeaders, getAuthHeaders, getCredentialsMode } from './config'
7
7
  import { readErrorBody } from './httpErrors'
8
8
 
9
9
  async function fetchJSON<T>(path: string, signal?: AbortSignal): Promise<T> {
@@ -279,12 +279,17 @@ export function useTrafficConnectionStatus() {
279
279
  export function useTrafficConnect() {
280
280
  const queryClient = useQueryClient()
281
281
 
282
- return useMutation<TrafficConnectionInfo, Error>({
283
- mutationFn: async () => {
282
+ // `automatic`: the page connected by itself, not for a click.
283
+ return useMutation<TrafficConnectionInfo, Error, { automatic?: boolean } | void>({
284
+ mutationFn: async (vars) => {
284
285
  const response = await fetch(apiUrl('/traffic/connect'), {
285
286
  method: 'POST',
286
287
  credentials: getCredentialsMode(),
287
- headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
288
+ headers: {
289
+ 'Content-Type': 'application/json',
290
+ ...getAuthHeaders(),
291
+ ...(vars?.automatic ? automaticRequestHeaders() : {}),
292
+ },
288
293
  })
289
294
  if (!response.ok) {
290
295
  const error = await readErrorBody(response)
@@ -3,15 +3,17 @@ import type { UsageDataStatus, UsageReport } from './usage-data'
3
3
  // Test-only: a report and status shaped like the server's.
4
4
  export function exampleReport(patch: Partial<UsageReport> = {}): UsageReport {
5
5
  return {
6
- schema: 3,
6
+ schema: 4,
7
7
  version: '1.15.0', os: 'darwin', arch: 'arm64', installMethod: 'homebrew', mode: 'local',
8
8
  periodStart: '2026-09-23', periodEnd: '2026-09-24',
9
9
  setup: {
10
10
  authMode: 'none', timelineStorage: 'memory', mcpEnabled: true, prometheus: 'none',
11
11
  costSource: 'auto', browsers: ['chrome'],
12
+ aiConfigured: false, trafficSource: 'none',
12
13
  },
13
14
  engagement: { sessions: 2, activeMinutes: '20-49' },
14
15
  views: {}, actions: {}, mcpTools: {}, uiEvents: {}, errors: {},
16
+ actionKinds: {}, connectionFailures: {},
15
17
  clusters: {
16
18
  contexts: '5-9', used: 1,
17
19
  shapes: [{ kubernetesVersion: '1.33', platform: 'eks', nodes: '10-19', integrations: ['argo-cd'] }],
@@ -0,0 +1,134 @@
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 { automaticRequestHeaders, setAutomaticRequestMarking } from './config'
6
+ import { useUsageRecording, type UsageDataStatus } from './usage-data'
7
+ import { exampleStatus } from './usage-data.fixtures'
8
+
9
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
10
+
11
+ const TICK_MS = 5 * 60_000
12
+ let root: Root
13
+ let container: HTMLDivElement
14
+ let visibility: DocumentVisibilityState
15
+ const fetchMock = vi.fn<(...args: unknown[]) => Promise<Response>>(() => Promise.resolve(new Response(null, { status: 204 })))
16
+
17
+ function Recorder({ view, status }: { view: string; status: UsageDataStatus | undefined }) {
18
+ useUsageRecording(view, status)
19
+ return null
20
+ }
21
+
22
+ function render(view: string, status: UsageDataStatus | undefined) {
23
+ act(() => root.render(<Recorder view={view} status={status} />))
24
+ }
25
+
26
+ function sentEvents(): Array<Record<string, unknown>> {
27
+ return fetchMock.mock.calls.map((call) => JSON.parse(String((call[1] as RequestInit).body)))
28
+ }
29
+
30
+ function activeEvents() {
31
+ return sentEvents().filter((e) => e.type === 'active')
32
+ }
33
+
34
+ function tick() {
35
+ act(() => {
36
+ vi.advanceTimersByTime(TICK_MS)
37
+ })
38
+ }
39
+
40
+ const on = exampleStatus({ state: 'on', source: 'user' })
41
+
42
+ beforeEach(() => {
43
+ vi.useFakeTimers()
44
+ vi.stubGlobal('fetch', fetchMock)
45
+ fetchMock.mockClear()
46
+ visibility = 'visible'
47
+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility })
48
+ container = document.createElement('div')
49
+ document.body.appendChild(container)
50
+ root = createRoot(container)
51
+ })
52
+
53
+ afterEach(() => {
54
+ // Leave recording off for whatever runs next in this worker.
55
+ render('home', undefined)
56
+ act(() => root.unmount())
57
+ container.remove()
58
+ vi.useRealTimers()
59
+ vi.unstubAllGlobals()
60
+ })
61
+
62
+ describe('useUsageRecording active time', () => {
63
+ it('counts a tick only when someone used the visible page during it', () => {
64
+ render('topology', on)
65
+ tick()
66
+ expect(activeEvents()).toEqual([])
67
+
68
+ act(() => {
69
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'j' }))
70
+ })
71
+ tick()
72
+ expect(activeEvents()).toEqual([{ type: 'active', minutes: 5 }])
73
+
74
+ // Input belongs to the tick it happened in.
75
+ tick()
76
+ expect(activeEvents()).toHaveLength(1)
77
+ })
78
+
79
+ it('does not count a hidden page, even with input', () => {
80
+ render('topology', on)
81
+ visibility = 'hidden'
82
+ act(() => {
83
+ window.dispatchEvent(new PointerEvent('pointerdown'))
84
+ })
85
+ tick()
86
+ expect(activeEvents()).toEqual([])
87
+ })
88
+
89
+ it('ignores a page that scrolls by itself, such as logs being followed', () => {
90
+ render('resources:pods', on)
91
+ const list = document.createElement('div')
92
+ container.appendChild(list)
93
+ act(() => {
94
+ list.dispatchEvent(new Event('scroll'))
95
+ })
96
+ tick()
97
+ expect(activeEvents()).toEqual([])
98
+ })
99
+
100
+ it('sends nothing while usage data is off', () => {
101
+ render('topology', exampleStatus({ state: 'off', source: 'user' }))
102
+ act(() => {
103
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'j' }))
104
+ })
105
+ tick()
106
+ expect(fetchMock).not.toHaveBeenCalled()
107
+ })
108
+ })
109
+
110
+ describe('automatic request marking', () => {
111
+ afterEach(() => setAutomaticRequestMarking(false))
112
+
113
+ it('keeps an embedding host unmarked', () => {
114
+ render('home', undefined)
115
+ expect(automaticRequestHeaders()).toEqual({})
116
+ })
117
+
118
+ it('stays marked until the status says usage data is not recorded', () => {
119
+ setAutomaticRequestMarking(true)
120
+ render('home', undefined)
121
+ expect(automaticRequestHeaders()).toEqual({ 'X-Radar-Request-Origin': 'auto' })
122
+ render('home', on)
123
+ expect(automaticRequestHeaders()).toEqual({ 'X-Radar-Request-Origin': 'auto' })
124
+ render('home', exampleStatus({ state: 'off', source: 'user' }))
125
+ expect(automaticRequestHeaders()).toEqual({})
126
+ })
127
+
128
+ it('marks requests when usage data is turned on later', () => {
129
+ render('home', exampleStatus({ state: 'off', source: 'user' }))
130
+ expect(automaticRequestHeaders()).toEqual({})
131
+ render('home', on)
132
+ expect(automaticRequestHeaders()).toEqual({ 'X-Radar-Request-Origin': 'auto' })
133
+ })
134
+ })
@@ -1,7 +1,7 @@
1
1
  import { useCallback, useEffect } from 'react'
2
2
  import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
3
3
  import { fetchJSON } from './client'
4
- import { apiUrl, getApiBase, getAuthHeaders, getCredentialsMode } from './config'
4
+ import { apiUrl, getApiBase, getAuthHeaders, getCredentialsMode, setAutomaticRequestMarking } from './config'
5
5
 
6
6
  export type UsageDataState = 'undecided' | 'on' | 'off'
7
7
  export type UsageDataSource = 'default' | 'user' | 'env' | 'deployment'
@@ -26,9 +26,12 @@ export interface UsageReport {
26
26
  authMode: string
27
27
  timelineStorage: string
28
28
  mcpEnabled: boolean
29
+ // 'none' | 'discovered' | 'manual'
29
30
  prometheus: string
30
31
  costSource: string
31
32
  browsers: string[]
33
+ aiConfigured: boolean
34
+ trafficSource: string
32
35
  }
33
36
  engagement: { sessions: number; activeMinutes: string }
34
37
  views: Record<string, number>
@@ -36,6 +39,8 @@ export interface UsageReport {
36
39
  mcpTools: Record<string, number>
37
40
  uiEvents: Record<string, number>
38
41
  errors: Record<string, number>
42
+ actionKinds: Record<string, number>
43
+ connectionFailures: Record<string, number>
39
44
  clusters: { contexts: string; used: number; shapes: ClusterShape[] }
40
45
  }
41
46
 
@@ -140,14 +145,27 @@ export function recordUsageEvent(event: UsageEvent): void {
140
145
 
141
146
  const ACTIVE_TICK_MINUTES = 5
142
147
 
143
- // Counts views, one session per page load, and visible time in five-minute
144
- // ticks. Nothing is sent unless usage data is on.
148
+ // Real use: a window left open on a second screen sees none of these. Scroll
149
+ // isn't one: following logs scrolls by itself, and a person scrolling already
150
+ // shows up as wheel, touch, pointer or key input.
151
+ const INPUT_EVENTS = ['pointerdown', 'pointermove', 'keydown', 'wheel', 'touchstart'] as const
152
+
153
+ // Counts views, one session per page load, and time in use in five-minute
154
+ // ticks: a tick counts only if the page is visible and someone used it during
155
+ // that tick. Nothing is sent unless usage data is on.
145
156
  export function useUsageRecording(view: string, status: UsageDataStatus | undefined) {
146
157
  const on = isRecording(status)
158
+
147
159
  useEffect(() => {
148
160
  setUsageRecording(on)
149
161
  }, [on])
150
162
 
163
+ // No status yet leaves the mark as the entry point set it.
164
+ const decided = status !== undefined
165
+ useEffect(() => {
166
+ if (decided) setAutomaticRequestMarking(on)
167
+ }, [decided, on])
168
+
151
169
  useEffect(() => {
152
170
  if (on) recordUsageEvent({ type: 'view', name: view })
153
171
  }, [view, on])
@@ -155,11 +173,21 @@ export function useUsageRecording(view: string, status: UsageDataStatus | undefi
155
173
  useEffect(() => {
156
174
  if (!on) return
157
175
  recordUsageEvent({ type: 'session' })
176
+ let usedThisTick = false
177
+ const markUsed = () => {
178
+ usedThisTick = true
179
+ }
180
+ // Capture, because views may stop propagation.
181
+ const listenerOptions = { capture: true, passive: true }
182
+ for (const type of INPUT_EVENTS) window.addEventListener(type, markUsed, listenerOptions)
158
183
  const tick = window.setInterval(() => {
159
- if (document.visibilityState === 'visible') {
160
- recordUsageEvent({ type: 'active', minutes: ACTIVE_TICK_MINUTES })
161
- }
184
+ const used = usedThisTick && document.visibilityState === 'visible'
185
+ usedThisTick = false
186
+ if (used) recordUsageEvent({ type: 'active', minutes: ACTIVE_TICK_MINUTES })
162
187
  }, ACTIVE_TICK_MINUTES * 60_000)
163
- return () => window.clearInterval(tick)
188
+ return () => {
189
+ window.clearInterval(tick)
190
+ for (const type of INPUT_EVENTS) window.removeEventListener(type, markUsed, listenerOptions)
191
+ }
164
192
  }, [on])
165
193
  }