@skyhook-io/radar-app 1.22.1 → 1.23.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 (234) hide show
  1. package/package.json +8 -8
  2. package/src/App.tsx +131 -38
  3. package/src/RadarApp.basename.test.tsx +177 -0
  4. package/src/RadarApp.settings.test.tsx +33 -0
  5. package/src/RadarApp.tsx +5 -0
  6. package/src/api/agentSandbox.ts +259 -0
  7. package/src/api/client.autoPromConnect.test.tsx +43 -0
  8. package/src/api/client.metricsRelayCheck.test.tsx +134 -0
  9. package/src/api/client.ts +128 -25
  10. package/src/api/cloudInstallDiscover.test.tsx +76 -0
  11. package/src/api/diagnose.ts +4 -0
  12. package/src/api/kagent.test.ts +82 -0
  13. package/src/api/kagent.ts +230 -0
  14. package/src/api/prometheusCharts.ts +5 -0
  15. package/src/api/radarFeatures.test.ts +9 -0
  16. package/src/api/radarFeatures.ts +13 -0
  17. package/src/api/substrateWorkspace.test.ts +72 -0
  18. package/src/api/substrateWorkspace.ts +1394 -0
  19. package/src/api/vulnerabilities.ts +207 -9
  20. package/src/api/workloadSource.test.tsx +1172 -0
  21. package/src/api/workloadSource.ts +408 -0
  22. package/src/components/APIUnreachableBanner.test.tsx +19 -0
  23. package/src/components/APIUnreachableBanner.tsx +20 -0
  24. package/src/components/CloudConnectFlow.tsx +46 -7
  25. package/src/components/CloudFunnelButton.test.tsx +193 -7
  26. package/src/components/CloudFunnelButton.tsx +127 -32
  27. package/src/components/ConnectionErrorView.test.tsx +63 -2
  28. package/src/components/ConnectionErrorView.tsx +88 -68
  29. package/src/components/SelfManagedStart.tsx +12 -2
  30. package/src/components/agentsandbox/AgentSandboxKindLists.tsx +41 -0
  31. package/src/components/agentsandbox/AgentSandboxLists.test.tsx +410 -0
  32. package/src/components/agentsandbox/AgentSandboxOverview.test.tsx +333 -0
  33. package/src/components/agentsandbox/AgentSandboxOverview.tsx +555 -0
  34. package/src/components/agentsandbox/AgentSandboxSidebar.test.tsx +97 -0
  35. package/src/components/agentsandbox/AgentSandboxSummary.test.tsx +439 -0
  36. package/src/components/agentsandbox/AgentSandboxSummary.tsx +956 -0
  37. package/src/components/agentsandbox/AgentSandboxTables.tsx +966 -0
  38. package/src/components/agentsandbox/AgentSandboxView.tsx +34 -0
  39. package/src/components/agentsandbox/agentsandbox.fixtures.ts +135 -0
  40. package/src/components/agentsandbox/data.ts +135 -0
  41. package/src/components/agentsandbox/host.test.ts +27 -0
  42. package/src/components/agentsandbox/host.tsx +85 -0
  43. package/src/components/agentsandbox/labels.test.ts +42 -0
  44. package/src/components/agentsandbox/labels.ts +146 -0
  45. package/src/components/agentsandbox/listFilters.ts +85 -0
  46. package/src/components/agentsandbox/lists.ts +52 -0
  47. package/src/components/agentsandbox/routes.ts +23 -0
  48. package/src/components/agentsandbox/shared.tsx +321 -0
  49. package/src/components/agentsandbox/useAgentSandboxSidebarWorkspace.ts +69 -0
  50. package/src/components/agentsandbox/workspace.fixtures.ts +125 -0
  51. package/src/components/agentsandbox/workspace.tsx +258 -0
  52. package/src/components/agentsandbox/workspaceRoute.ts +18 -0
  53. package/src/components/applications/ApplicationsView.openResource.test.tsx +248 -3
  54. package/src/components/applications/ApplicationsView.tsx +156 -3
  55. package/src/components/audit/VulnerabilitiesColumns.test.tsx +487 -0
  56. package/src/components/audit/VulnerabilitiesRisk.test.tsx +318 -0
  57. package/src/components/audit/VulnerabilitiesView.test.tsx +458 -13
  58. package/src/components/audit/VulnerabilitiesView.tsx +639 -199
  59. package/src/components/cloudHints/AgentSetupCloudRow.tsx +28 -0
  60. package/src/components/cloudHints/CloudHintLink.tsx +29 -0
  61. package/src/components/cloudHints/SharedInstallAiLine.tsx +36 -0
  62. package/src/components/cloudHints/cloudHints.test.ts +126 -0
  63. package/src/components/cloudHints/cloudHints.ts +131 -0
  64. package/src/components/cloudHints/cloudHintsGate.test.tsx +70 -0
  65. package/src/components/cloudHints/cloudLinks.test.ts +52 -0
  66. package/src/components/cloudHints/cloudLinks.ts +31 -0
  67. package/src/components/cloudHints/hintStorage.ts +28 -0
  68. package/src/components/cnpg/CNPGView.tsx +4 -7
  69. package/src/components/diagnose/ActivityTurn.tsx +6 -4
  70. package/src/components/diagnose/AgentSetupNotice.tsx +5 -0
  71. package/src/components/diagnose/AssessmentCard.tsx +1 -2
  72. package/src/components/diagnose/ContinueInAgentButton.test.tsx +7 -0
  73. package/src/components/diagnose/DiagnoseContext.tsx +7 -0
  74. package/src/components/diagnose/DiagnoseSurface.escape.test.tsx +215 -0
  75. package/src/components/diagnose/DiagnoseSurface.tsx +57 -1
  76. package/src/components/diagnose/Home.test.tsx +6 -0
  77. package/src/components/diagnose/Home.tsx +10 -3
  78. package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +1 -1
  79. package/src/components/diagnose/InvestigationEvidencePane.tsx +19 -2
  80. package/src/components/diagnose/InvestigationFindingsFooter.test.tsx +413 -0
  81. package/src/components/diagnose/InvestigationView.tsx +120 -23
  82. package/src/components/diagnose/investigationEvidence/identity.test.ts +1 -1
  83. package/src/components/diagnose/investigationEvidence/projection.test.ts +1 -1
  84. package/src/components/diagnose/investigationState.ts +9 -0
  85. package/src/components/diagnose/parts.test.tsx +11 -3
  86. package/src/components/diagnose/toolCallLabel.ts +3 -0
  87. package/src/components/gitops/RemoteDestinationCloudHint.tsx +6 -14
  88. package/src/components/home/ActivitySummary.tsx +3 -8
  89. package/src/components/home/ClusterHealthCard.tsx +91 -17
  90. package/src/components/home/ClusterHealthCard.utilization.test.tsx +187 -0
  91. package/src/components/home/HomeAgentBlock.tsx +2 -0
  92. package/src/components/home/HomeView.tsx +9 -29
  93. package/src/components/home/MCPSetupDialog.test.tsx +9 -0
  94. package/src/components/home/MCPSetupDialog.tsx +6 -2
  95. package/src/components/home/McpCloudLine.test.tsx +162 -0
  96. package/src/components/home/McpCloudLine.tsx +95 -0
  97. package/src/components/home/ProblemsPanel.investigate.test.tsx +2 -2
  98. package/src/components/home/TopologyPreview.test.tsx +31 -30
  99. package/src/components/home/TopologyPreview.tsx +19 -28
  100. package/src/components/home/mcpToolCatalog.test.ts +10 -0
  101. package/src/components/home/mcpToolCatalog.ts +7 -7
  102. package/src/components/issues/ClusterSchedulingBlockerRow.tsx +35 -0
  103. package/src/components/issues/IssuesPane.render.test.tsx +36 -1
  104. package/src/components/issues/IssuesPane.tsx +181 -23
  105. package/src/components/issues/SinceLastVisitRow.render.test.tsx +302 -0
  106. package/src/components/issues/SinceLastVisitRow.tsx +71 -0
  107. package/src/components/issues/sinceLastVisit.test.ts +266 -0
  108. package/src/components/issues/sinceLastVisit.ts +439 -0
  109. package/src/components/kagent/KagentAgentRenderer.test.ts +32 -0
  110. package/src/components/kagent/KagentAgentRenderer.tsx +87 -0
  111. package/src/components/kagent/KagentAgentSessions.test.tsx +166 -0
  112. package/src/components/kagent/KagentAgentSessions.tsx +124 -0
  113. package/src/components/kagent/KagentDetailPage.tsx +106 -0
  114. package/src/components/kagent/KagentLists.tsx +412 -0
  115. package/src/components/kagent/KagentOverview.tsx +234 -0
  116. package/src/components/kagent/KagentPages.tsx +690 -0
  117. package/src/components/kagent/KagentRuntimeTabs.test.tsx +219 -0
  118. package/src/components/kagent/KagentRuntimeTabs.tsx +283 -0
  119. package/src/components/kagent/KagentSidebar.test.tsx +112 -0
  120. package/src/components/kagent/KagentView.tsx +109 -0
  121. package/src/components/kagent/KagentWorkspace.test.tsx +876 -0
  122. package/src/components/kagent/host.tsx +144 -0
  123. package/src/components/kagent/routes.ts +31 -0
  124. package/src/components/kagent/shared.tsx +336 -0
  125. package/src/components/kagent/useKagentRuntime.test.tsx +77 -0
  126. package/src/components/kagent/useKagentSidebarWorkspace.ts +67 -0
  127. package/src/components/kagent/workspace.fixtures.ts +108 -0
  128. package/src/components/kagent/workspaceRoute.ts +18 -0
  129. package/src/components/resource/MetricsNotConnected.test.tsx +28 -0
  130. package/src/components/resource/MetricsNotConnected.tsx +10 -7
  131. package/src/components/resource/PrometheusCharts.tsx +10 -1
  132. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +9 -0
  133. package/src/components/resource/PrometheusChartsGrid.tsx +3 -3
  134. package/src/components/resource/SubstrateHealthCharts.test.tsx +13 -1
  135. package/src/components/resource/SubstrateHealthCharts.tsx +9 -15
  136. package/src/components/resources/ResourceDetailDrawer.tsx +1 -0
  137. package/src/components/resources/ResourcesView.tsx +2 -6
  138. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +5 -4
  139. package/src/components/resources/renderers/PodRenderer.tsx +8 -2
  140. package/src/components/resources/renderers/RolloutRenderer.tsx +4 -1
  141. package/src/components/resources/renderers/WorkloadRenderer.tsx +4 -1
  142. package/src/components/settings/LocalIntegrationStatus.test.tsx +1 -0
  143. package/src/components/settings/LocalIntegrationStatus.tsx +3 -2
  144. package/src/components/settings/SettingsDialog.tsx +84 -16
  145. package/src/components/settings/SubstrateSettings.lifecycle.test.tsx +210 -0
  146. package/src/components/settings/SubstrateSettings.test.tsx +131 -0
  147. package/src/components/settings/SubstrateSettings.tsx +544 -0
  148. package/src/components/settings/settings-state.test.ts +21 -3
  149. package/src/components/settings/settings-state.ts +13 -3
  150. package/src/components/share/ShareLinkButton.test.tsx +360 -0
  151. package/src/components/share/ShareLinkButton.tsx +391 -0
  152. package/src/components/share/openShareInCloud.test.ts +29 -0
  153. package/src/components/share/openShareInCloud.ts +10 -0
  154. package/src/components/share/shareLink.test.ts +129 -0
  155. package/src/components/share/shareLink.ts +175 -0
  156. package/src/components/substrate/SubstrateActorDrawer.tsx +87 -0
  157. package/src/components/substrate/SubstrateActorOverview.tsx +489 -0
  158. package/src/components/substrate/SubstrateActorPage.tsx +384 -0
  159. package/src/components/substrate/SubstrateActors.test.tsx +1094 -0
  160. package/src/components/substrate/SubstrateActors.tsx +612 -0
  161. package/src/components/substrate/SubstrateAttentionList.tsx +441 -0
  162. package/src/components/substrate/SubstrateConnect.tsx +88 -0
  163. package/src/components/substrate/SubstrateOverview.test.tsx +396 -0
  164. package/src/components/substrate/SubstrateOverview.tsx +575 -0
  165. package/src/components/substrate/SubstratePages.test.tsx +478 -0
  166. package/src/components/substrate/SubstratePool.test.tsx +462 -0
  167. package/src/components/substrate/SubstratePoolPage.tsx +95 -0
  168. package/src/components/substrate/SubstratePoolSummary.tsx +485 -0
  169. package/src/components/substrate/SubstrateSidebar.test.tsx +101 -0
  170. package/src/components/substrate/SubstrateStateBar.tsx +63 -0
  171. package/src/components/substrate/SubstrateTemplates.tsx +376 -0
  172. package/src/components/substrate/SubstrateView.tsx +173 -0
  173. package/src/components/substrate/SubstrateWorkerPodContext.tsx +73 -0
  174. package/src/components/substrate/SubstrateWorkers.tsx +389 -0
  175. package/src/components/substrate/attention.ts +81 -0
  176. package/src/components/substrate/contextPin.tsx +69 -0
  177. package/src/components/substrate/host.tsx +83 -0
  178. package/src/components/substrate/kubectlTarget.test.tsx +77 -0
  179. package/src/components/substrate/readings.test.ts +484 -0
  180. package/src/components/substrate/readings.ts +997 -0
  181. package/src/components/substrate/routes.ts +103 -0
  182. package/src/components/substrate/shared.tsx +426 -0
  183. package/src/components/substrate/substrate.fixtures.ts +325 -0
  184. package/src/components/substrate/useSubstrateSidebarWorkspace.ts +87 -0
  185. package/src/components/substrate/workspaceRoute.ts +23 -0
  186. package/src/components/traffic/TrafficConnectionsTable.test.tsx +9 -0
  187. package/src/components/traffic/TrafficConnectionsTable.tsx +4 -2
  188. package/src/components/traffic/TrafficFilterSidebar.tsx +19 -14
  189. package/src/components/traffic/TrafficFlowList.test.tsx +63 -0
  190. package/src/components/traffic/TrafficFlowList.tsx +9 -5
  191. package/src/components/traffic/TrafficGraph.test.tsx +26 -0
  192. package/src/components/traffic/TrafficGraph.tsx +17 -14
  193. package/src/components/traffic/TrafficGraphTooLarge.tsx +2 -0
  194. package/src/components/traffic/TrafficGraphUnavailable.tsx +3 -1
  195. package/src/components/traffic/TrafficView.tsx +26 -56
  196. package/src/components/traffic/trafficFilters.test.ts +61 -1
  197. package/src/components/traffic/trafficFilters.ts +68 -8
  198. package/src/components/velero/VeleroOverview.tsx +2 -2
  199. package/src/components/velero/VeleroView.tsx +3 -6
  200. package/src/components/vulnerabilities/columns.tsx +132 -0
  201. package/src/components/vulnerabilities/filters.tsx +317 -0
  202. package/src/components/vulnerabilities/owner.test.ts +54 -0
  203. package/src/components/vulnerabilities/owner.tsx +163 -0
  204. package/src/components/vulnerabilities/parts.test.ts +126 -12
  205. package/src/components/vulnerabilities/parts.tsx +612 -52
  206. package/src/components/vulnerabilities/traffic.test.tsx +65 -0
  207. package/src/components/vulnerabilities/traffic.tsx +40 -0
  208. package/src/components/workload/WorkloadView.substrateVersion.test.tsx +88 -0
  209. package/src/components/workload/WorkloadView.tsx +119 -14
  210. package/src/components/workload/WorkloadView.workloadSource.test.tsx +121 -0
  211. package/src/components/workspace/layout.tsx +13 -7
  212. package/src/components/workspace/sidebar.test.ts +48 -0
  213. package/src/components/workspace/sidebar.ts +73 -3
  214. package/src/components/workspace/table.ts +2 -1
  215. package/src/context/ConnectionContext.tsx +24 -5
  216. package/src/context/ConnectionProvider.connectionId.test.tsx +14 -0
  217. package/src/context/ConnectionProvider.handover.test.tsx +94 -0
  218. package/src/context/DiagnoseCustomization.tsx +20 -2
  219. package/src/contexts/RegistryAccessMode.test.tsx +51 -0
  220. package/src/contexts/RegistryAccessMode.tsx +25 -0
  221. package/src/hooks/useEventSource.test.tsx +275 -4
  222. package/src/hooks/useEventSource.ts +278 -51
  223. package/src/index.ts +1 -0
  224. package/src/integrations/resourceHost.ts +12 -6
  225. package/src/integrations/resourceHosts.test.tsx +27 -1
  226. package/src/integrations/resourceHosts.tsx +15 -7
  227. package/src/integrations/sidebarWorkspaces.test.tsx +63 -0
  228. package/src/integrations/sidebarWorkspaces.ts +41 -0
  229. package/src/integrations/workspaceRoute.ts +1 -1
  230. package/src/integrations/workspaceRoutes.ts +7 -1
  231. package/src/integrations/workspaceScreens.tsx +6 -0
  232. package/src/utils/navigation.test.ts +1 -6
  233. package/src/utils/navigation.ts +9 -44
  234. package/src/utils/network-policy-navigation.test.ts +21 -36
@@ -0,0 +1,408 @@
1
+ import { useEffect, useRef } from 'react'
2
+ import { useQueries, useQuery, useQueryClient, type QueryClient, type UseQueryResult } from '@tanstack/react-query'
3
+ import {
4
+ getRadarUpgradeRequirement,
5
+ type RadarUpgradeRequirement,
6
+ type WorkloadSourceResponse,
7
+ type WorkloadSourceState,
8
+ } from '@skyhook-io/k8s-ui'
9
+ import { kindToPluralWithGroup } from '@skyhook-io/k8s-ui/utils/navigation'
10
+ import type { K8sEvent } from '../types'
11
+ import { fetchJSON, useRadarFeature } from './client'
12
+ import { getApiBase } from './config'
13
+ import {
14
+ isRadarFeatureUnsupported,
15
+ RadarFeatureUnsupportedError,
16
+ shouldRetryRadarQuery,
17
+ type RadarFeatureSupport,
18
+ } from './radarFeatures'
19
+
20
+ const APPS_SOURCE_KINDS = new Set(['deployments', 'statefulsets', 'daemonsets', 'replicasets'])
21
+ const BATCH_SOURCE_KINDS = new Set(['jobs', 'cronjobs'])
22
+ const ARGO_SOURCE_KINDS = new Set(['rollouts', 'workflows'])
23
+
24
+ // GitOps managers and Flux source objects whose updates can change a workload's
25
+ // reported deployment source from another namespace (e.g. argocd / flux-system).
26
+ const GITOPS_SOURCE_MANAGER_KINDS: Readonly<Record<string, string>> = {
27
+ applications: 'argoproj.io',
28
+ kustomizations: 'kustomize.toolkit.fluxcd.io',
29
+ helmreleases: 'helm.toolkit.fluxcd.io',
30
+ gitrepositories: 'source.toolkit.fluxcd.io',
31
+ ocirepositories: 'source.toolkit.fluxcd.io',
32
+ buckets: 'source.toolkit.fluxcd.io',
33
+ helmrepositories: 'source.toolkit.fluxcd.io',
34
+ helmcharts: 'source.toolkit.fluxcd.io',
35
+ externalartifacts: 'source.toolkit.fluxcd.io',
36
+ artifactgenerators: 'source.extensions.fluxcd.io',
37
+ }
38
+
39
+ export const WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS = 5_000
40
+ export const WORKLOAD_SOURCE_REFETCH_INTERVAL_MS = 120_000
41
+
42
+ // Mirrors backend workloadSourceTargets in internal/server/workload_source.go.
43
+ export function supportsWorkloadSource(kind: string, group?: string): boolean {
44
+ const k = kind.toLowerCase()
45
+ const g = (group ?? '').toLowerCase()
46
+ if (APPS_SOURCE_KINDS.has(k)) return !g || g === 'apps'
47
+ if (BATCH_SOURCE_KINDS.has(k)) return !g || g === 'batch'
48
+ if (ARGO_SOURCE_KINDS.has(k)) return !g || g === 'argoproj.io'
49
+ return false
50
+ }
51
+
52
+ export type WorkloadSourceInvalidationScope =
53
+ | { scope: 'all' }
54
+ | { scope: 'namespace'; namespace: string }
55
+ | { scope: 'workload'; kind: string; namespace: string; name: string }
56
+
57
+ // Determines which cached ['workload-source', ...] queries an SSE resource
58
+ // change can make stale: a Pod in the workload's namespace, the workload itself,
59
+ // or a GitOps manager / Flux source object (which may live in another namespace).
60
+ export function workloadSourceInvalidationScope(
61
+ event: Pick<K8sEvent, 'kind' | 'group' | 'namespace' | 'name'>,
62
+ ): WorkloadSourceInvalidationScope | null {
63
+ const group = (event.group ?? '').toLowerCase()
64
+ const pluralKind = kindToPluralWithGroup(event.kind, group).toLowerCase()
65
+
66
+ if (GITOPS_SOURCE_MANAGER_KINDS[pluralKind] === group) {
67
+ return { scope: 'all' }
68
+ }
69
+ if (pluralKind === 'pods' && !group) {
70
+ return event.namespace ? { scope: 'namespace', namespace: event.namespace } : null
71
+ }
72
+ if (supportsWorkloadSource(pluralKind, group) && event.namespace && event.name) {
73
+ return { scope: 'workload', kind: pluralKind, namespace: event.namespace, name: event.name }
74
+ }
75
+ return null
76
+ }
77
+
78
+ interface WorkloadSourceTarget {
79
+ apiBase: string
80
+ kind: string
81
+ namespace: string
82
+ name: string
83
+ }
84
+
85
+ function parseWorkloadSourceQueryKey(queryKey: readonly unknown[]): WorkloadSourceTarget | null {
86
+ if (
87
+ queryKey.length < 5 ||
88
+ queryKey[0] !== 'workload-source' ||
89
+ typeof queryKey[1] !== 'string' ||
90
+ typeof queryKey[2] !== 'string' ||
91
+ typeof queryKey[3] !== 'string' ||
92
+ typeof queryKey[4] !== 'string'
93
+ ) {
94
+ return null
95
+ }
96
+ return {
97
+ apiBase: queryKey[1],
98
+ kind: queryKey[2],
99
+ namespace: queryKey[3],
100
+ name: queryKey[4],
101
+ }
102
+ }
103
+
104
+ export interface WorkloadSourceInvalidator {
105
+ handleEvent: (queryClient: QueryClient, event: K8sEvent) => void
106
+ reset: () => void
107
+ }
108
+
109
+ // Invalidates matching ['workload-source', ...] queries in response to SSE
110
+ // resource changes, throttled to at most once per window (default 5s) per
111
+ // workload (leading edge + trailing edge for bursts within the window).
112
+ export function createWorkloadSourceInvalidator(
113
+ throttleMs = WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS,
114
+ ): WorkloadSourceInvalidator {
115
+ const buckets = new Map<
116
+ string,
117
+ { lastInvalidatedAt: number; timer: ReturnType<typeof setTimeout> | null }
118
+ >()
119
+
120
+ const invalidateTarget = (queryClient: QueryClient, target: WorkloadSourceTarget) => {
121
+ void queryClient.invalidateQueries(
122
+ {
123
+ queryKey: ['workload-source', target.apiBase, target.kind, target.namespace, target.name],
124
+ },
125
+ { cancelRefetch: false },
126
+ )
127
+ }
128
+
129
+ return {
130
+ handleEvent(queryClient, event) {
131
+ const scope = workloadSourceInvalidationScope(event)
132
+ if (!scope) return
133
+
134
+ const matched = new Map<string, WorkloadSourceTarget>()
135
+ for (const query of queryClient.getQueryCache().findAll({ queryKey: ['workload-source'] })) {
136
+ const target = parseWorkloadSourceQueryKey(query.queryKey)
137
+ if (!target) continue
138
+ if (scope.scope === 'namespace' && target.namespace !== scope.namespace) continue
139
+ if (
140
+ scope.scope === 'workload' &&
141
+ (target.kind !== scope.kind ||
142
+ target.namespace !== scope.namespace ||
143
+ target.name !== scope.name)
144
+ ) {
145
+ continue
146
+ }
147
+ const key = `${target.apiBase}\0${target.kind}\0${target.namespace}\0${target.name}`
148
+ if (!matched.has(key)) matched.set(key, target)
149
+ }
150
+ if (matched.size === 0) return
151
+
152
+ const now = Date.now()
153
+ for (const [key, entry] of buckets) {
154
+ if (entry.timer === null && now - entry.lastInvalidatedAt >= throttleMs) {
155
+ buckets.delete(key)
156
+ }
157
+ }
158
+
159
+ for (const [key, target] of matched) {
160
+ const entry = buckets.get(key)
161
+ const elapsed = entry ? now - entry.lastInvalidatedAt : Infinity
162
+ if (elapsed >= throttleMs) {
163
+ if (entry?.timer !== null && entry?.timer !== undefined) clearTimeout(entry.timer)
164
+ buckets.set(key, { lastInvalidatedAt: now, timer: null })
165
+ invalidateTarget(queryClient, target)
166
+ } else if (entry && entry.timer === null) {
167
+ const delay = throttleMs - elapsed
168
+ entry.timer = setTimeout(() => {
169
+ entry.timer = null
170
+ entry.lastInvalidatedAt = Date.now()
171
+ invalidateTarget(queryClient, target)
172
+ }, delay)
173
+ }
174
+ }
175
+ },
176
+
177
+ reset() {
178
+ for (const entry of buckets.values()) {
179
+ if (entry.timer !== null) clearTimeout(entry.timer)
180
+ }
181
+ buckets.clear()
182
+ },
183
+ }
184
+ }
185
+
186
+ function shouldDropCachedSourceOnError(error: unknown): boolean {
187
+ const status = (error as { status?: number } | null)?.status
188
+ return status === 401 || status === 403 || status === 404
189
+ }
190
+
191
+ export type WorkloadSourceQueryResult = UseQueryResult<WorkloadSourceResponse, Error> & {
192
+ support: RadarFeatureSupport
193
+ upgrade: RadarUpgradeRequirement | null
194
+ cachedData?: WorkloadSourceResponse
195
+ }
196
+
197
+ // Evicts cached data on the existing query entry without deleting the entry
198
+ // (removeQueries on a mounted query triggers a fresh refetch) and without
199
+ // calling setQueryData(undefined) (which is a no-op in TanStack Query v5).
200
+ function evictCachedWorkloadSource(queryClient: QueryClient, queryKey: readonly unknown[]) {
201
+ queryClient.getQueryCache().find({ queryKey, exact: true })?.setState({
202
+ data: undefined,
203
+ dataUpdatedAt: 0,
204
+ })
205
+ }
206
+
207
+ export function useWorkloadSource(
208
+ kind: string,
209
+ namespace: string,
210
+ name: string,
211
+ enabled = true,
212
+ uid?: string,
213
+ ): WorkloadSourceQueryResult {
214
+ const normalizedKind = kind.toLowerCase()
215
+ const normalizedUid = typeof uid === 'string' ? uid : ''
216
+ const apiBase = getApiBase()
217
+ const workloadBase = `${apiBase}|${normalizedKind}|${namespace}|${name}`
218
+ const lastSuccessRef = useRef<{ base: string; uid: string; data: WorkloadSourceResponse } | null>(null)
219
+ // The resource's UID arrives after the first render (list row first, full
220
+ // object later). An unknown UID on either side is the same workload; only two
221
+ // known, different UIDs mean it was replaced and the old answer must go.
222
+ const last = lastSuccessRef.current
223
+ const sameWorkloadCached =
224
+ last &&
225
+ last.base === workloadBase &&
226
+ (last.uid === normalizedUid || last.uid === '' || normalizedUid === '')
227
+ ? last.data
228
+ : undefined
229
+
230
+ const queryClient = useQueryClient()
231
+ const { guard, gatedKey, support, upgrade } = useRadarFeature('workloadSource')
232
+ const query = useQuery<WorkloadSourceResponse, Error>({
233
+ queryKey: ['workload-source', apiBase, normalizedKind, namespace, name, normalizedUid, ...gatedKey],
234
+ queryFn: async ({ signal, queryKey }) => {
235
+ try {
236
+ return await guard(() =>
237
+ fetchJSON<WorkloadSourceResponse>(
238
+ `/workloads/${encodeURIComponent(normalizedKind)}/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}/source`,
239
+ signal,
240
+ ),
241
+ )
242
+ } catch (err) {
243
+ if (shouldDropCachedSourceOnError(err)) {
244
+ lastSuccessRef.current = null
245
+ evictCachedWorkloadSource(queryClient, queryKey)
246
+ }
247
+ throw err
248
+ }
249
+ },
250
+ placeholderData: () => sameWorkloadCached,
251
+ staleTime: 60_000,
252
+ // Fallback for large clusters where namespace-scoped SSE streams filter out
253
+ // cross-namespace GitOps manager or Flux source events.
254
+ refetchInterval: (q) =>
255
+ support === 'unsupported' || isRadarFeatureUnsupported(q.state.error, 'workloadSource')
256
+ ? false
257
+ : WORKLOAD_SOURCE_REFETCH_INTERVAL_MS,
258
+ refetchIntervalInBackground: false,
259
+ retry: shouldRetryRadarQuery,
260
+ enabled: enabled && Boolean(normalizedKind && namespace && name),
261
+ })
262
+
263
+ const dropCached = shouldDropCachedSourceOnError(query.error)
264
+
265
+ useEffect(() => {
266
+ if (dropCached) {
267
+ lastSuccessRef.current = null
268
+ } else if (query.data && !query.isPlaceholderData) {
269
+ lastSuccessRef.current = { base: workloadBase, uid: normalizedUid, data: query.data }
270
+ } else if (lastSuccessRef.current && !sameWorkloadCached) {
271
+ lastSuccessRef.current = null
272
+ }
273
+ }, [dropCached, query.data, query.isPlaceholderData, workloadBase, normalizedUid, sameWorkloadCached])
274
+
275
+ const { error, refetch } = query
276
+ useEffect(() => {
277
+ if (support === 'supported' && error instanceof RadarFeatureUnsupportedError) {
278
+ void refetch()
279
+ }
280
+ }, [support, error, refetch])
281
+
282
+ return {
283
+ ...query,
284
+ support,
285
+ upgrade,
286
+ cachedData: dropCached ? undefined : (query.data ?? sameWorkloadCached),
287
+ }
288
+ }
289
+
290
+ export function toWorkloadSourceState(query: WorkloadSourceQueryResult): WorkloadSourceState {
291
+ if (query.support === 'unsupported' || isRadarFeatureUnsupported(query.error, 'workloadSource')) {
292
+ return {
293
+ status: 'unsupported',
294
+ upgrade: getRadarUpgradeRequirement(query.error) ?? query.upgrade ?? undefined,
295
+ }
296
+ }
297
+ const data = shouldDropCachedSourceOnError(query.error) ? undefined : (query.data ?? query.cachedData)
298
+ if (data) {
299
+ if (query.error) {
300
+ return {
301
+ status: 'ready',
302
+ data,
303
+ refreshError: query.error.message || 'Unknown error',
304
+ onRetry: () => {
305
+ void query.refetch()
306
+ },
307
+ }
308
+ }
309
+ return { status: 'ready', data }
310
+ }
311
+ if (query.error) {
312
+ return {
313
+ status: 'error',
314
+ message: query.error.message || 'Unknown error',
315
+ onRetry: () => {
316
+ void query.refetch()
317
+ },
318
+ }
319
+ }
320
+ return { status: 'loading' }
321
+ }
322
+
323
+ export interface WorkloadSourceTargetRef {
324
+ kind: string
325
+ group?: string
326
+ namespace: string
327
+ name: string
328
+ }
329
+
330
+ export type WorkloadSourcesRead =
331
+ | { status: 'loading' }
332
+ | { status: 'unreadable'; denied: boolean; message?: string }
333
+ | { status: 'ready'; source: WorkloadSourceResponse; stale?: boolean }
334
+
335
+ // The most workloads one page reads source for at once. Past this limit across
336
+ // environments, cross-environment comparison is skipped while the viewed
337
+ // environment's own workloads are still read when they fit within the limit.
338
+ export const WORKLOAD_SOURCES_MAX = 24
339
+
340
+ /** Source reads for several workloads, sharing the per-workload cache and
341
+ * invalidation of useWorkloadSource. Returns null when the feature is
342
+ * unsupported, disabled, or there are more than WORKLOAD_SOURCES_MAX targets. */
343
+ export function useWorkloadSources(targets: WorkloadSourceTargetRef[], enabled = true): Map<string, WorkloadSourcesRead> | null {
344
+ const apiBase = getApiBase()
345
+ const queryClient = useQueryClient()
346
+ const { guard, gatedKey, support } = useRadarFeature('workloadSource')
347
+ const usable = enabled && support === 'supported' && targets.length > 0 && targets.length <= WORKLOAD_SOURCES_MAX
348
+ const resolved = targets.map((t) => ({ ...t, plural: kindToPluralWithGroup(t.kind, t.group ?? '').toLowerCase() }))
349
+ const results = useQueries({
350
+ queries: resolved.map((t) => ({
351
+ // Not 'workload-source': the per-Pod SSE invalidation that keeps one
352
+ // workload's Source section current would refetch every workload of every
353
+ // environment on each Pod change. These follow the poll instead.
354
+ queryKey: ['app-workload-source', apiBase, t.plural, t.namespace, t.name, ...gatedKey],
355
+ queryFn: async ({ signal, queryKey }: { signal: AbortSignal; queryKey: readonly unknown[] }) => {
356
+ try {
357
+ return await guard(() =>
358
+ fetchJSON<WorkloadSourceResponse>(
359
+ `/workloads/${encodeURIComponent(t.plural)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.name)}/source`,
360
+ signal,
361
+ ),
362
+ )
363
+ } catch (err) {
364
+ if (shouldDropCachedSourceOnError(err)) {
365
+ evictCachedWorkloadSource(queryClient, queryKey)
366
+ }
367
+ throw err
368
+ }
369
+ },
370
+ staleTime: 60_000,
371
+ refetchInterval: (q: { state: { error: Error | null } }) =>
372
+ isRadarFeatureUnsupported(q.state.error, 'workloadSource') ? false : WORKLOAD_SOURCE_REFETCH_INTERVAL_MS,
373
+ refetchIntervalInBackground: false,
374
+ retry: shouldRetryRadarQuery,
375
+ enabled: usable && supportsWorkloadSource(t.plural, t.group),
376
+ })),
377
+ })
378
+ const resultsRef = useRef(results)
379
+ resultsRef.current = results
380
+ const hasUnsupportedError = results.some((r) => r.error instanceof RadarFeatureUnsupportedError)
381
+ useEffect(() => {
382
+ if (support !== 'supported' || !hasUnsupportedError) return
383
+ for (const r of resultsRef.current) {
384
+ if (r.error instanceof RadarFeatureUnsupportedError) {
385
+ void r.refetch()
386
+ }
387
+ }
388
+ }, [support, hasUnsupportedError])
389
+ if (!usable) return null
390
+ if (results.some((r) => isRadarFeatureUnsupported(r.error, 'workloadSource'))) return null
391
+ const out = new Map<string, WorkloadSourcesRead>()
392
+ resolved.forEach((t, i) => {
393
+ const r = results[i]
394
+ const key = workloadSourceTargetKey(t)
395
+ const status = (r.error as { status?: number } | null)?.status
396
+ const denied = status === 403
397
+ const dropCached = shouldDropCachedSourceOnError(r.error)
398
+ // Auth loss, refusal, or missing workload outranks the cached answer.
399
+ if (r.data && !dropCached) out.set(key, { status: 'ready', source: r.data, ...(r.error ? { stale: true } : {}) })
400
+ else if (r.error) out.set(key, { status: 'unreadable', denied, message: r.error.message })
401
+ else out.set(key, { status: 'loading' })
402
+ })
403
+ return out
404
+ }
405
+
406
+ export function workloadSourceTargetKey(t: WorkloadSourceTargetRef): string {
407
+ return `${(t.group ?? '').toLowerCase()}/${t.kind.toLowerCase()}/${t.namespace}/${t.name}`
408
+ }
@@ -0,0 +1,19 @@
1
+ import { renderToStaticMarkup } from 'react-dom/server'
2
+ import { describe, expect, it } from 'vitest'
3
+ import { APIUnreachableBanner } from './APIUnreachableBanner'
4
+ import { outageSinceLabel } from './outageSince'
5
+
6
+ describe('APIUnreachableBanner', () => {
7
+ it('says since when the API server stopped answering and that changes are paused', () => {
8
+ const since = new Date().toISOString()
9
+ const html = renderToStaticMarkup(<APIUnreachableBanner since={since} />)
10
+ expect(html).toContain(`Can&#x27;t reach the cluster&#x27;s API server since ${outageSinceLabel(since)}`)
11
+ expect(html).toContain('last state Radar received')
12
+ expect(html).toContain('Changes are paused')
13
+ })
14
+
15
+ it('drops the time when the server sent one it cannot read', () => {
16
+ const html = renderToStaticMarkup(<APIUnreachableBanner since="not-a-time" />)
17
+ expect(html).toContain('Can&#x27;t reach the cluster&#x27;s API server</div>')
18
+ })
19
+ })
@@ -0,0 +1,20 @@
1
+ import { CloudOff } from 'lucide-react'
2
+ import { AlertBanner } from '@skyhook-io/k8s-ui'
3
+ import { outageSinceLabel } from './outageSince'
4
+
5
+ // Radar stays connected when its API server stops answering: the cache keeps
6
+ // serving what it last received, so views still read normally. Without this,
7
+ // a VPN drop or a sleeping laptop leaves a frozen cluster looking live.
8
+ export function APIUnreachableBanner({ since }: { since: string }) {
9
+ const sinceLabel = outageSinceLabel(since)
10
+ return (
11
+ <div className="px-4 pt-3">
12
+ <AlertBanner
13
+ variant="warning"
14
+ icon={CloudOff}
15
+ title={sinceLabel ? `Can't reach the cluster's API server since ${sinceLabel}` : "Can't reach the cluster's API server"}
16
+ message="You're seeing the last state Radar received. Changes are paused until the cluster answers again. Radar keeps checking, and this clears on its own."
17
+ />
18
+ </div>
19
+ )
20
+ }
@@ -11,6 +11,7 @@ import {
11
11
  cancelCloudInstall,
12
12
  type CloudInstallBlocked,
13
13
  type CloudInstallRecoveryGuidance,
14
+ type CloudInstallConnected,
14
15
  type CloudInstallStage,
15
16
  type CloudInstallStatus,
16
17
  dismissCloudInstall,
@@ -22,16 +23,24 @@ import { showApiError } from './ui/Toast'
22
23
  // flow itself is server-owned (it survives modal close and page reloads);
23
24
  // this component only renders the observed status and issues transitions.
24
25
  export function CloudConnectFlow({
25
- status,
26
+ status: observed,
26
27
  blocked,
27
28
  exit,
28
29
  where,
29
30
  onStatus,
30
31
  onExit,
32
+ tagUrl = (url) => url,
33
+ connectedAction,
31
34
  }: {
32
35
  status: CloudInstallStatus
33
36
  blocked: CloudInstallBlocked | null
34
37
  exit: BlockedExit
38
+ // Marks the Hub approval link with which hint opened the dialog, so the
39
+ // page the person opens can say where they came from.
40
+ tagUrl?: (url: string) => string
41
+ // What the person came to do once the cluster is in Radar Cloud (open the
42
+ // resource they were sharing), offered as the connected card's main action.
43
+ connectedAction?: (connected: CloudInstallConnected) => { label: string; href: string } | null
35
44
  // Which cluster this is, for the note a blocked person hands to an admin.
36
45
  where?: AdminNoteContext
37
46
  // Push a mutation's status response into the shared query state.
@@ -43,11 +52,19 @@ export function CloudConnectFlow({
43
52
  return <BlockedView blocked={blocked} exit={exit} where={where} onExit={onExit} />
44
53
  }
45
54
 
55
+ const status: CloudInstallStatus = {
56
+ ...observed,
57
+ ...(observed.connectUrl && { connectUrl: tagUrl(observed.connectUrl) }),
58
+ ...(observed.connected?.clusterUrl && {
59
+ connected: { ...observed.connected, clusterUrl: tagUrl(observed.connected.clusterUrl) },
60
+ }),
61
+ }
62
+
46
63
  switch (status.state) {
47
64
  case 'preparing':
48
65
  return <PreparingCard step={status.prepareStep} context={where?.context} />
49
66
  case 'ready':
50
- return <PlanCard status={status} onStatus={onStatus} onExit={onExit} />
67
+ return <PlanCard status={status} onStatus={onStatus} onExit={onExit} tagUrl={tagUrl} />
51
68
  case 'starting':
52
69
  case 'awaiting_approval':
53
70
  return <ApprovalCard status={status} onStatus={onStatus} />
@@ -57,7 +74,14 @@ export function CloudConnectFlow({
57
74
  case 'waiting_tunnel':
58
75
  return <ProgressCard status={status} onStatus={onStatus} />
59
76
  case 'connected':
60
- return <ConnectedCard status={status} onStatus={onStatus} onExit={onExit} />
77
+ return (
78
+ <ConnectedCard
79
+ status={status}
80
+ onStatus={onStatus}
81
+ onExit={onExit}
82
+ action={status.connected && connectedAction ? connectedAction(status.connected) : null}
83
+ />
84
+ )
61
85
  case 'failed':
62
86
  return <FailedCard status={status} where={where} onStatus={onStatus} onExit={onExit} />
63
87
  default:
@@ -427,10 +451,12 @@ function PlanCard({
427
451
  status,
428
452
  onStatus,
429
453
  onExit,
454
+ tagUrl,
430
455
  }: {
431
456
  status: CloudInstallStatus
432
457
  onStatus: (st: CloudInstallStatus) => void
433
458
  onExit: () => void
459
+ tagUrl: (url: string) => string
434
460
  }) {
435
461
  const plan = status.plan
436
462
  const [clusterName, setClusterName] = useState(plan?.defaultClusterName ?? '')
@@ -458,10 +484,11 @@ function PlanCard({
458
484
  // flight, and opening its connectUrl anyway would present an approvable
459
485
  // request for a flow the user already stopped.
460
486
  if (st.connectUrl && st.state === 'awaiting_approval') {
487
+ const connectUrl = tagUrl(st.connectUrl)
461
488
  if (approvalTab.current && !approvalTab.current.closed) {
462
- approvalTab.current.location.href = st.connectUrl
489
+ approvalTab.current.location.href = connectUrl
463
490
  } else {
464
- window.open(st.connectUrl, '_blank', 'noopener')
491
+ window.open(connectUrl, '_blank', 'noopener')
465
492
  }
466
493
  } else {
467
494
  approvalTab.current?.close()
@@ -797,10 +824,12 @@ function ConnectedCard({
797
824
  status,
798
825
  onStatus,
799
826
  onExit,
827
+ action,
800
828
  }: {
801
829
  status: CloudInstallStatus
802
830
  onStatus: (st: CloudInstallStatus) => void
803
831
  onExit: () => void
832
+ action?: { label: string; href: string } | null
804
833
  }) {
805
834
  const dismiss = useDismiss(status, onStatus, onExit)
806
835
  const connected = status.connected
@@ -821,13 +850,23 @@ function ConnectedCard({
821
850
  </p>
822
851
  <div className="flex items-center gap-4 mb-4">
823
852
  <a
824
- href={connected.clusterUrl}
853
+ href={action?.href ?? connected.clusterUrl}
825
854
  target="_blank"
826
855
  rel="noopener noreferrer"
827
856
  className="px-5 py-2 rounded-[10px] bg-emerald-500 hover:bg-emerald-400 text-emerald-950 text-[13px] font-bold transition-all inline-flex items-center gap-1.5"
828
857
  >
829
- Open in Radar Cloud <ArrowUpRight className="w-3.5 h-3.5" />
858
+ {action?.label ?? 'Open in Radar Cloud'} <ArrowUpRight className="w-3.5 h-3.5" />
830
859
  </a>
860
+ {action && (
861
+ <a
862
+ href={connected.clusterUrl}
863
+ target="_blank"
864
+ rel="noopener noreferrer"
865
+ className="text-[12.5px] text-theme-text-secondary hover:text-theme-text-primary hover:underline underline-offset-2"
866
+ >
867
+ Open the cluster
868
+ </a>
869
+ )}
831
870
  <button onClick={dismiss} className="text-[12.5px] text-theme-text-tertiary hover:text-theme-text-primary transition-colors">
832
871
  Done
833
872
  </button>