@skyhook-io/radar-app 1.19.0 → 1.20.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 (198) hide show
  1. package/README.md +1 -1
  2. package/package.json +5 -5
  3. package/src/App.tsx +37 -9
  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 +353 -64
  13. package/src/api/config.ts +21 -0
  14. package/src/api/diagnose.ts +4 -0
  15. package/src/api/helmInventory.test.tsx +108 -0
  16. package/src/api/radarFeatures.render.test.tsx +33 -1
  17. package/src/api/radarFeatures.test.ts +47 -0
  18. package/src/api/radarFeatures.ts +42 -1
  19. package/src/api/rbac.settled.test.tsx +42 -0
  20. package/src/api/rbac.test.ts +18 -0
  21. package/src/api/rbac.ts +37 -7
  22. package/src/api/traffic.ts +9 -4
  23. package/src/api/usage-data.fixtures.ts +3 -1
  24. package/src/api/usage-data.test.tsx +134 -0
  25. package/src/api/usage-data.ts +35 -7
  26. package/src/api/workloadPodsPolling.test.ts +26 -0
  27. package/src/components/CloudConnectFlow.test.tsx +86 -0
  28. package/src/components/CloudConnectFlow.tsx +65 -27
  29. package/src/components/CloudFunnelButton.test.tsx +140 -5
  30. package/src/components/CloudFunnelButton.tsx +50 -9
  31. package/src/components/ConnectionErrorView.test.tsx +34 -0
  32. package/src/components/ConnectionErrorView.tsx +35 -11
  33. package/src/components/ContextSwitcher.tsx +5 -2
  34. package/src/components/SwitchAwareConnectionError.test.tsx +43 -0
  35. package/src/components/SwitchAwareConnectionError.tsx +85 -0
  36. package/src/components/application-evidence/ApplicationEvidenceAction.flow.test.tsx +234 -0
  37. package/src/components/application-evidence/ApplicationEvidenceAction.test.tsx +144 -0
  38. package/src/components/application-evidence/ApplicationEvidenceAction.tsx +218 -0
  39. package/src/components/capacity/CapacityDemand.tsx +3 -2
  40. package/src/components/capacity/demandSummary.test.ts +38 -0
  41. package/src/components/capacity/shared.tsx +12 -1
  42. package/src/components/cost/ApplicationCostTab.tsx +4 -0
  43. package/src/components/cost/CostTrendChart.tsx +2 -0
  44. package/src/components/cost/WorkloadCostTab.tsx +4 -0
  45. package/src/components/cost/source.test.ts +5 -0
  46. package/src/components/cost/source.ts +11 -0
  47. package/src/components/curl/ServiceCurlAvailability.test.tsx +32 -0
  48. package/src/components/curl/ServiceCurlButton.tsx +2 -2
  49. package/src/components/diagnose/AIMarkdown.tsx +3 -0
  50. package/src/components/diagnose/AgentSetupNotice.test.tsx +17 -0
  51. package/src/components/diagnose/AgentSetupNotice.tsx +21 -3
  52. package/src/components/diagnose/ContinueInAgentButton.mounted.test.tsx +182 -0
  53. package/src/components/diagnose/ContinueInAgentButton.test.tsx +128 -0
  54. package/src/components/diagnose/ContinueInAgentButton.tsx +303 -0
  55. package/src/components/diagnose/DiagnoseContext.question.test.tsx +1 -1
  56. package/src/components/diagnose/DiagnoseContext.tsx +68 -2
  57. package/src/components/diagnose/DiagnoseSurface.tsx +58 -113
  58. package/src/components/diagnose/ExampleInvestigationLink.tsx +20 -0
  59. package/src/components/diagnose/Home.test.tsx +26 -0
  60. package/src/components/diagnose/Home.tsx +20 -1
  61. package/src/components/diagnose/InvestigationEvidenceSections.tsx +45 -22
  62. package/src/components/diagnose/InvestigationView.tsx +94 -26
  63. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +450 -0
  64. package/src/components/diagnose/LocalDiagnoseAction.tsx +354 -35
  65. package/src/components/diagnose/NextStepJump.test.tsx +92 -0
  66. package/src/components/diagnose/NextStepJump.tsx +75 -0
  67. package/src/components/diagnose/QuestionComposer.tsx +8 -0
  68. package/src/components/diagnose/exampleInvestigation.events.json +191 -0
  69. package/src/components/diagnose/exampleInvestigation.loadFailure.test.tsx +94 -0
  70. package/src/components/diagnose/exampleInvestigation.test.tsx +248 -0
  71. package/src/components/diagnose/exampleInvestigation.ts +121 -0
  72. package/src/components/diagnose/investigationCase.test.tsx +50 -1
  73. package/src/components/diagnose/investigationEvidence/adapters/applicationFindings.test.ts +739 -0
  74. package/src/components/diagnose/investigationEvidence/adapters/coverage.test.tsx +72 -0
  75. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +50 -2
  76. package/src/components/diagnose/investigationEvidence/adapters/helm.ts +51 -16
  77. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +9 -0
  78. package/src/components/diagnose/investigationEvidence/adapters/listings.ts +34 -4
  79. package/src/components/diagnose/investigationEvidence/adapters/resource.ts +3 -2
  80. package/src/components/diagnose/investigationEvidence/builder.ts +30 -0
  81. package/src/components/diagnose/investigationEvidence/observations.ts +121 -2
  82. package/src/components/diagnose/investigationEvidence/projection.test.ts +85 -3
  83. package/src/components/diagnose/investigationEvidence/types.ts +5 -0
  84. package/src/components/diagnose/investigationState.ts +28 -0
  85. package/src/components/diagnose/lastInvestigation.test.ts +95 -0
  86. package/src/components/diagnose/lastInvestigation.ts +58 -0
  87. package/src/components/diagnose/launch.test.ts +125 -1
  88. package/src/components/diagnose/launch.ts +57 -10
  89. package/src/components/diagnose/toolCallLabel.test.ts +10 -4
  90. package/src/components/execution/BatchExecutionView.tsx +24 -11
  91. package/src/components/execution/JobSetAdmission.test.tsx +42 -0
  92. package/src/components/execution/JobSetAdmission.tsx +18 -3
  93. package/src/components/execution/JobSetMemberComparison.tsx +2 -1
  94. package/src/components/execution/runState.test.ts +14 -0
  95. package/src/components/execution/runState.ts +8 -0
  96. package/src/components/gitops/GitOpsView.rollbackGate.test.tsx +202 -0
  97. package/src/components/gitops/GitOpsView.syncRequest.test.tsx +369 -0
  98. package/src/components/gitops/GitOpsView.tsx +86 -17
  99. package/src/components/gitops/RemoteDestinationCloudHint.tsx +2 -3
  100. package/src/components/gitops/destination-toast.test.ts +1 -1
  101. package/src/components/gitops/destination-toast.ts +2 -2
  102. package/src/components/helm/HelmDrawerFrame.tsx +101 -0
  103. package/src/components/helm/HelmDrawerRouting.test.tsx +86 -0
  104. package/src/components/helm/HelmReleaseDrawer.tsx +23 -86
  105. package/src/components/helm/HelmView.tsx +213 -71
  106. package/src/components/helm/ObservedHelmNotice.tsx +146 -0
  107. package/src/components/helm/ObservedHelmRelease.test.tsx +261 -0
  108. package/src/components/helm/ObservedHelmReleaseDrawer.test.tsx +80 -0
  109. package/src/components/helm/ObservedHelmReleaseDrawer.tsx +228 -0
  110. package/src/components/helm/OwnedResources.tsx +4 -2
  111. package/src/components/home/ClusterHealthCard.restricted.test.tsx +76 -0
  112. package/src/components/home/ClusterHealthCard.tsx +28 -5
  113. package/src/components/home/HelmSummary.tsx +23 -4
  114. package/src/components/home/HelmSummary.unread.test.ts +16 -0
  115. package/src/components/home/HomeAgentBlock.test.tsx +31 -3
  116. package/src/components/home/HomeAgentBlock.tsx +20 -4
  117. package/src/components/home/HomeDiagramCard.tsx +47 -0
  118. package/src/components/home/HomeView.tsx +81 -41
  119. package/src/components/home/MCPSetupDialog.test.tsx +126 -10
  120. package/src/components/home/MCPSetupDialog.tsx +33 -5
  121. package/src/components/home/ProblemsPanel.investigate.test.tsx +171 -0
  122. package/src/components/home/ProblemsPanel.test.tsx +3 -1
  123. package/src/components/home/TopologyPreview.test.tsx +73 -0
  124. package/src/components/home/TopologyPreview.tsx +120 -233
  125. package/src/components/home/TrafficSummary.test.tsx +63 -0
  126. package/src/components/home/TrafficSummary.tsx +135 -138
  127. package/src/components/home/mcpToolCatalog.ts +67 -14
  128. package/src/components/issues/IssuesPane.test.ts +11 -0
  129. package/src/components/issues/IssuesPane.tsx +15 -5
  130. package/src/components/issues/uncheckedSources.test.ts +22 -1
  131. package/src/components/issues/uncheckedSources.ts +21 -0
  132. package/src/components/kueue/KueuePendingPosition.tsx +35 -0
  133. package/src/components/kueue/useRelatedObjects.test.tsx +219 -0
  134. package/src/components/kueue/useRelatedReads.test.ts +56 -0
  135. package/src/components/kueue/useRelatedReads.ts +205 -0
  136. package/src/components/logs/MultiPodLogsTab.test.tsx +93 -0
  137. package/src/components/logs/MultiPodLogsTab.tsx +120 -0
  138. package/src/components/logs/PodLogsUnavailable.test.tsx +18 -0
  139. package/src/components/logs/PodLogsUnavailable.tsx +21 -0
  140. package/src/components/logs/RayClusterLogsTab.reselect.test.tsx +67 -0
  141. package/src/components/logs/RayClusterLogsTab.test.tsx +167 -0
  142. package/src/components/logs/RayClusterLogsTab.tsx +109 -0
  143. package/src/components/logs/ScheduledWorkloadLogsViewer.tsx +3 -2
  144. package/src/components/logs/rayClusterPods.ts +32 -0
  145. package/src/components/outageSince.test.ts +21 -0
  146. package/src/components/outageSince.ts +10 -0
  147. package/src/components/resource/PrometheusCharts.overlays.test.ts +12 -0
  148. package/src/components/resource/PrometheusCharts.tsx +3 -40
  149. package/src/components/resources/crd/CRDSchemaTab.test.tsx +28 -0
  150. package/src/components/resources/crd/CRDSchemaTab.tsx +13 -0
  151. package/src/components/resources/crd/host.tsx +14 -0
  152. package/src/components/resources/renderers/CustomResourceDefinitionRenderer.test.tsx +27 -0
  153. package/src/components/resources/renderers/CustomResourceDefinitionRenderer.tsx +12 -0
  154. package/src/components/resources/renderers/JobAdmissionRenderers.test.tsx +4 -1
  155. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +4 -3
  156. package/src/components/resources/renderers/KueueHostRenderers.test.tsx +117 -0
  157. package/src/components/resources/renderers/KueueQueueRenderers.test.tsx +97 -0
  158. package/src/components/resources/renderers/KueueQueueRenderers.tsx +139 -0
  159. package/src/components/resources/renderers/KueueWorkloadRenderer.test.tsx +7 -1
  160. package/src/components/resources/renderers/KueueWorkloadRenderer.tsx +47 -7
  161. package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.test.tsx +67 -0
  162. package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.tsx +31 -0
  163. package/src/components/resources/renderers/RayClusterRenderer.test.tsx +81 -3
  164. package/src/components/resources/renderers/RayClusterRenderer.tsx +19 -4
  165. package/src/components/resources/renderers/ServiceRenderer.test.tsx +15 -2
  166. package/src/components/resources/renderers/ServiceRenderer.tsx +1 -1
  167. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.test.tsx +160 -0
  168. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.tsx +128 -0
  169. package/src/components/traffic/TrafficView.tsx +3 -3
  170. package/src/components/ui/command-items-crd.test.tsx +23 -0
  171. package/src/components/ui/command-items.ts +2 -1
  172. package/src/components/useContextSwitchFlow.test.tsx +61 -0
  173. package/src/components/useContextSwitchFlow.tsx +21 -4
  174. package/src/components/whats-new/WhatsNew.test.ts +10 -3
  175. package/src/components/whats-new/WhatsNew.tsx +5 -1
  176. package/src/components/whats-new/WhatsNewDialog.test.tsx +17 -3
  177. package/src/components/whats-new/releaseNotes.ts +77 -4
  178. package/src/components/workload/RelatedFindingsSection.test.tsx +126 -0
  179. package/src/components/workload/RelatedFindingsSection.tsx +80 -0
  180. package/src/components/workload/WorkloadView.test.ts +10 -1
  181. package/src/components/workload/WorkloadView.tsx +85 -98
  182. package/src/components/workload/issueResourceOpener.test.ts +20 -0
  183. package/src/components/workload/issueResourceOpener.ts +17 -0
  184. package/src/context/ConnectionContext.tsx +133 -60
  185. package/src/context/ConnectionProvider.retry.test.tsx +176 -0
  186. package/src/context/ContextSwitchContext.tsx +14 -1
  187. package/src/context/DiagnoseCustomization.tsx +3 -0
  188. package/src/context/clusterConnected.ts +10 -0
  189. package/src/contexts/CapabilitiesContext.tsx +8 -4
  190. package/src/hooks/useElementSize.ts +30 -0
  191. package/src/hooks/useResolvedGitOpsOwner.test.ts +22 -0
  192. package/src/hooks/useResolvedGitOpsOwner.ts +6 -3
  193. package/src/integrations/resourceHost.test.tsx +1 -0
  194. package/src/integrations/resourceHost.ts +5 -1
  195. package/src/integrations/resourceHosts.test.tsx +21 -4
  196. package/src/integrations/resourceHosts.tsx +17 -0
  197. package/src/main.tsx +5 -0
  198. package/src/utils/related-findings.ts +46 -0
package/src/api/client.ts CHANGED
@@ -2,9 +2,15 @@ import { createListRefetchInterval, normalizeResourceList, type ResourceListBody
2
2
  import type { CascadeDetail } from '@skyhook-io/k8s-ui/components/ui/ForceDeleteConfirmDialog'
3
3
  import { canonicalResourceGroup } from '@skyhook-io/k8s-ui/utils/api-resources'
4
4
  import { pluralize } from '@skyhook-io/k8s-ui/utils/pluralize'
5
+ import type { ReadGap, ReadGapSet } from '@skyhook-io/k8s-ui/types/read-coverage'
6
+ import type { WorkloadHistoryCoverage } from '@skyhook-io/k8s-ui/utils/workload-history-notes'
5
7
  import { knownKindForPluralWithGroup, pluralToKind } from '@skyhook-io/k8s-ui/utils/navigation'
6
8
  import { useEffect, useRef, useCallback, useMemo } from 'react'
7
- import type { KueueAdmissionResponse } from '@skyhook-io/k8s-ui/types/scheduling'
9
+ import { argoSyncOptionsForRequest } from '@skyhook-io/k8s-ui'
10
+ import { useClusterConnected } from '../context/clusterConnected'
11
+ import type { KueueAdmissionResponse, KueuePositionResponse } from '@skyhook-io/k8s-ui/types/scheduling'
12
+ import type { KueueQueueMembership, KueueQueueWorkloadsResponse } from '@skyhook-io/k8s-ui/types/kueue-queues'
13
+ import { kueueQueueRetryable } from '@skyhook-io/k8s-ui/utils/kueue-queue-workloads'
8
14
  import { canonicalReadCode, readActionFor } from '@skyhook-io/k8s-ui/utils/read-actions'
9
15
  import type { SearchCoverage } from '@skyhook-io/k8s-ui/types/read-coverage'
10
16
  import type { GitOpsWriteEvidence } from '@skyhook-io/k8s-ui/utils/gitops-write-guard'
@@ -26,7 +32,7 @@ import type {
26
32
  YamlDocumentIdentity,
27
33
  YamlSchemaLoadResult,
28
34
  } from '@skyhook-io/k8s-ui'
29
- import { useQuery, useMutation, useQueryClient, skipToken, type QueryClient } from '@tanstack/react-query'
35
+ import { focusManager, useInfiniteQuery, useQuery, useMutation, useQueryClient, skipToken, type QueryClient } from '@tanstack/react-query'
30
36
  import { showApiError, showApiSuccess, showApiNotice } from '../components/ui/Toast'
31
37
  import { useIsAuthEnabled, useNamespacedCapabilities } from '../contexts/CapabilitiesContext'
32
38
  import type {
@@ -38,8 +44,10 @@ import type {
38
44
  TimelineEvent,
39
45
  TimeRange,
40
46
  ResourceWithRelationships,
47
+ HelmInventory,
41
48
  HelmRelease,
42
49
  HelmReleaseDetail,
50
+ ObservedHelmReleaseDetail,
43
51
  HelmValues,
44
52
  ManifestDiff,
45
53
  NotesDiff,
@@ -67,12 +75,15 @@ import type {
67
75
  PodEnvironmentRevealResponse,
68
76
  } from '../types'
69
77
  import type { GitOpsOperationResponse } from '../types/gitops'
70
- import { apiUrl, getApiBase, getAuthHeaders, getCredentialsMode, getBasename, routePath, stripBasename } from './config'
78
+ import { apiUrl, automaticRequestHeaders, getApiBase, getAuthHeaders, getCredentialsMode, getBasename, routePath, stripBasename } from './config'
71
79
  import { httpStatusMessage, markShownInline, readErrorBody, readErrorResponse } from './httpErrors'
72
80
  import {
73
81
  RadarFeatureUnsupportedError,
74
82
  guardRadarFeature,
83
+ radarControlBlocked,
84
+ radarControlBlockedReason,
75
85
  radarFeatureSupport,
86
+ radarUpgradeRequirement,
76
87
  shouldRetryRadarQuery,
77
88
  type RadarFeature,
78
89
  } from './radarFeatures'
@@ -233,6 +244,18 @@ export function isForbiddenError(error: unknown): boolean {
233
244
  return error instanceof ApiError && error.status === 403;
234
245
  }
235
246
 
247
+ // Answers that won't change on the next poll: a rejected request, a denial, a
248
+ // missing or recreated root. A 401 (an expired session) can recover.
249
+ export function isStableClientError(error: unknown): boolean {
250
+ return error instanceof ApiError && [400, 403, 404, 409].includes(error.status)
251
+ }
252
+
253
+ // An owner-UID query stops polling on an answer that will repeat; a recreated
254
+ // root recovers when its new UID changes the query key.
255
+ export function workloadPodsRefetchInterval(error: unknown, options?: { ownerUID?: string; refetchInterval?: number | false }): number | false {
256
+ return options?.ownerUID && isStableClientError(error) ? false : options?.refetchInterval ?? false
257
+ }
258
+
236
259
  export function isNotFoundError(error: unknown): boolean {
237
260
  return error instanceof ApiError && error.status === 404;
238
261
  }
@@ -492,17 +515,8 @@ export interface DashboardChange {
492
515
  timestamp: string;
493
516
  }
494
517
 
495
- export interface DashboardTopFlow {
496
- src: string;
497
- dst: string;
498
- requestsPerSec?: number;
499
- connections: number;
500
- }
501
-
502
518
  export interface DashboardTrafficSummary {
503
519
  source: string;
504
- flowCount: number;
505
- topFlows: DashboardTopFlow[];
506
520
  }
507
521
 
508
522
  export interface DashboardHelmRelease {
@@ -517,13 +531,20 @@ export interface DashboardHelmRelease {
517
531
  export interface DashboardHelmSummary {
518
532
  total: number;
519
533
  releases: DashboardHelmRelease[];
520
- restricted?: boolean; // True when user lacks permissions to list Helm releases (RBAC-denied)
534
+ // True when no Helm records could be read and the caller was refused. A
535
+ // refusal in only some namespaces leaves it false and fills unreadNamespaces.
536
+ restricted?: boolean;
521
537
  // error + errorCode populated when the Helm read failed for a non-RBAC
522
538
  // reason (client not initialized, unconfigured, network). Surfaced
523
539
  // via the dashboard widget so empty results aren't mistaken for
524
540
  // "this cluster has zero releases."
525
541
  error?: string;
526
542
  errorCode?: string;
543
+ // Namespaces whose Helm records weren't read: refused, or the permission
544
+ // check behind that went unanswered. Their releases are missing from total
545
+ // and releases. Absent when everything in scope was read, on a restricted or
546
+ // failed answer, and from an older Radar.
547
+ unreadNamespaces?: ReadGapSet<string>;
527
548
  }
528
549
 
529
550
  export interface DashboardCRDCount {
@@ -710,9 +731,12 @@ export function useDashboard(
710
731
  export function useAudit(namespaces: string[] = []) {
711
732
  const params =
712
733
  namespaces.length > 0 ? `?namespaces=${namespaces.join(",")}` : "";
734
+ // Mounted app-wide, so without this it keeps polling a cluster that is down.
735
+ const connected = useClusterConnected();
713
736
  return useQuery<AuditResponse>({
714
737
  queryKey: ["audit", namespaces],
715
738
  queryFn: () => fetchJSON(`/audit${params}`),
739
+ enabled: connected,
716
740
  staleTime: 30000,
717
741
  refetchInterval: AUDIT_REFRESH_INTERVAL_MS,
718
742
  placeholderData: (prev) => prev,
@@ -786,8 +810,10 @@ export interface UncheckedSource {
786
810
  // The kinds within the source that went unchecked; absent means the whole
787
811
  // source, or that Radar couldn't tell which kinds.
788
812
  kinds?: { group?: string; kind: string }[];
789
- // The namespaces whose read failed while the others were read; absent
790
- // means the gap isn't limited to particular namespaces.
813
+ // The namespaces this entry's gap is limited to: the source was checked in
814
+ // the others, and these weren't (the read failed or was refused there, or
815
+ // Radar didn't read there because the caller can't). Absent means the gap
816
+ // isn't limited to particular namespaces.
791
817
  namespaces?: string[];
792
818
  }
793
819
 
@@ -828,12 +854,17 @@ export function useResourceAudit(
828
854
  // the "Operational Issues" section in the resource detail. Cluster-scoped
829
855
  // resources pass "_" for namespace; namespaced ones also scope the scan via
830
856
  // ?namespaces= for a cheap, bounded Compose.
857
+ // rootObservation is an opaque root UID/resourceVersion token: changes schedule
858
+ // a refresh at most every 10s, without creating a query key per version. Omit it
859
+ // to retain the 60s visible-tab fallback and stale-view/focus refreshes.
860
+ // Disabled hooks and cluster-scoped subjects do not poll for namespaced Issues.
831
861
  export function useResourceIssues(
832
862
  kind: string,
833
863
  group: string | undefined,
834
864
  namespace: string,
835
865
  name: string,
836
866
  enabled = true,
867
+ rootObservation?: string,
837
868
  ) {
838
869
  const clusterScoped = !namespace;
839
870
  const pathNs = clusterScoped ? "_" : encodeURIComponent(namespace);
@@ -843,16 +874,52 @@ export function useResourceIssues(
843
874
  const qs = params.toString();
844
875
  // An older Radar without the endpoint settles as unsupported, so the
845
876
  // renderers fall back to their own status-derived problem banners.
846
- const { guard, gatedKey } = useRadarFeature("resourceIssues");
847
- return useQuery<Issue[]>({
848
- queryKey: ["issues", "resource", kind, group ?? "", namespace, name, ...gatedKey],
877
+ const { guard, gatedKey, support } = useRadarFeature("resourceIssues");
878
+ const queryClient = useQueryClient();
879
+ const queryKey = useMemo(() => ["issues", "resource", kind, group ?? "", namespace, name, ...gatedKey],
880
+ [kind, group, namespace, name, gatedKey]);
881
+ const query = useQuery<Issue[]>({
882
+ queryKey,
849
883
  queryFn: () => guard(() => fetchJSON<Issue[]>(`${path}${qs ? `?${qs}` : ""}`)),
850
884
  retry: shouldRetryRadarQuery,
851
- // No refetchInterval: a drawer doesn't need to poll; staleTime keeps it fresh
852
- // on reopen without re-running an uncapped Compose every 30s.
853
885
  staleTime: 30000,
886
+ // Time-based detections can change without a resource watch update.
887
+ refetchInterval: (q) => clusterScoped || q.state.error instanceof RadarFeatureUnsupportedError ? false : 60000,
888
+ refetchIntervalInBackground: false,
889
+ refetchOnWindowFocus: (q) => !(q.state.error instanceof RadarFeatureUnsupportedError),
854
890
  enabled: enabled && !!kind && !!name,
855
891
  });
892
+ const { error, refetch } = query;
893
+ useEffect(() => {
894
+ if (enabled && kind && name && support === "supported" && error instanceof RadarFeatureUnsupportedError) void refetch();
895
+ }, [enabled, kind, name, support, error, refetch]);
896
+ const identity = JSON.stringify(queryKey);
897
+ const previous = useRef<{ identity: string; rootObservation: string | undefined; refreshedAt: number } | null>(null);
898
+ useEffect(() => {
899
+ const prior = previous.current;
900
+ if (prior?.identity !== identity) {
901
+ previous.current = { identity, rootObservation, refreshedAt: Date.now() };
902
+ return;
903
+ }
904
+ if (prior.rootObservation === undefined) {
905
+ prior.rootObservation = rootObservation;
906
+ return;
907
+ }
908
+ if (clusterScoped || !enabled || !kind || !name || query.error instanceof RadarFeatureUnsupportedError ||
909
+ rootObservation === undefined || prior.rootObservation === rootObservation) return;
910
+
911
+ // Keep the rootObservation out of the query key, and bound Compose requests even
912
+ // when a busy workload's resource version changes continuously.
913
+ const delay = Math.max(0, 10000 - (Date.now() - Math.max(prior.refreshedAt, query.dataUpdatedAt)));
914
+ const timer = window.setTimeout(() => {
915
+ prior.rootObservation = rootObservation;
916
+ prior.refreshedAt = Date.now();
917
+ void queryClient.invalidateQueries({ queryKey, exact: true,
918
+ refetchType: focusManager.isFocused() ? 'active' : 'none' });
919
+ }, delay);
920
+ return () => window.clearTimeout(timer);
921
+ }, [identity, rootObservation, enabled, kind, name, clusterScoped, queryClient, query.error, query.dataUpdatedAt, queryKey]);
922
+ return query;
856
923
  }
857
924
 
858
925
  // The Issues page narrowed to one subject: the same per-resource lookup with
@@ -875,6 +942,8 @@ export interface SubjectIssuesResponse {
875
942
  coverage: "ok" | "syncing" | "notWatched" | "unknownKind";
876
943
  withheld?: { issues: number };
877
944
  visibility?: { state?: string; impact?: string };
945
+ /** Checks about this resource Radar couldn't make for the caller. */
946
+ unchecked_sources?: UncheckedSource[];
878
947
  }
879
948
 
880
949
  export function useSubjectIssues(
@@ -1086,6 +1155,8 @@ export type CostUnavailableReason =
1086
1155
  | "access_denied"
1087
1156
  | "not_found"
1088
1157
  | "source_unavailable"
1158
+ | "metrics_port_forward_disabled"
1159
+ | "kubecost_port_forward_disabled"
1089
1160
  | "authentication_error"
1090
1161
  | "configuration_mismatch"
1091
1162
  | "deployment_configuration_error"
@@ -1785,7 +1856,8 @@ export function useWhatsNewState(enabled: boolean) {
1785
1856
  export async function markWhatsNewSeen(version: string): Promise<void> {
1786
1857
  const response = await apiFetch(`${getApiBase()}/whats-new/seen`, {
1787
1858
  method: "POST",
1788
- headers: { "Content-Type": "application/json" },
1859
+ // Bookkeeping that follows the dialog, not a separate action.
1860
+ headers: { "Content-Type": "application/json", ...automaticRequestHeaders() },
1789
1861
  body: JSON.stringify({ version }),
1790
1862
  });
1791
1863
  if (!response.ok) throw new ApiError(`HTTP ${response.status}`, response.status);
@@ -1886,9 +1958,14 @@ export function useVersionCheck() {
1886
1958
  * (a host-supplied version before /capabilities answers) can lift later, and
1887
1959
  * the key change is what makes the query fetch for real; ungated keys are
1888
1960
  * unchanged.
1961
+ *
1962
+ * `upgrade` is set when a control the feature backs must render disabled with
1963
+ * RadarUpgradeNote's copy: the Radar is known to be too old, or failed to
1964
+ * answer /api/capabilities (see radarControlBlocked). Controls requiring
1965
+ * affirmative support instead get `blockedReason` while checking or unavailable.
1889
1966
  */
1890
1967
  export function useRadarFeature(feature: RadarFeature) {
1891
- const { data: capabilities } = useCapabilities()
1968
+ const { data: capabilities, isError: capabilitiesFailed } = useCapabilities()
1892
1969
  const { data: versionInfo } = useQuery<VersionInfo>(versionCheckQueryOptions(getApiBase()))
1893
1970
  const { radarVersion } = useRadarUpgradeHost()
1894
1971
  const currentVersion = versionInfo?.currentVersion || radarVersion
@@ -1900,8 +1977,17 @@ export function useRadarFeature(feature: RadarFeature) {
1900
1977
  [feature, support, currentVersion, latestVersion],
1901
1978
  )
1902
1979
  const gatedKey = useMemo(() => (support === 'unsupported' ? ['radar-feature-unsupported'] : []), [support])
1980
+ const blockedReason = radarControlBlockedReason(feature, support, capabilitiesFailed)
1903
1981
 
1904
- return { support, gatedKey, guard }
1982
+ return {
1983
+ support,
1984
+ blockedReason,
1985
+ upgrade: !blockedReason && radarControlBlocked(support, capabilitiesFailed)
1986
+ ? radarUpgradeRequirement(feature, { currentVersion, latestVersion })
1987
+ : null,
1988
+ gatedKey,
1989
+ guard,
1990
+ }
1905
1991
  }
1906
1992
 
1907
1993
  // ============================================================================
@@ -2079,11 +2165,14 @@ export function useRuntimeStats(enabled: boolean = true) {
2079
2165
 
2080
2166
  // Capabilities (RBAC-based feature flags)
2081
2167
  export function useCapabilities() {
2168
+ const connected = useClusterConnected();
2082
2169
  return useQuery<Capabilities>({
2083
2170
  queryKey: ["capabilities"],
2084
2171
  queryFn: () => fetchJSON("/capabilities"),
2085
2172
  staleTime: 60000, // 1 minute - cached on backend too
2086
- refetchInterval: 60000, // Re-check periodically so transient failures self-correct
2173
+ // Re-check periodically so transient failures self-correct, but not while
2174
+ // the cluster is down: reconnecting refreshes every query anyway.
2175
+ refetchInterval: connected ? 60000 : false,
2087
2176
  });
2088
2177
  }
2089
2178
 
@@ -2136,7 +2225,7 @@ export interface CloudInstallAttempted {
2136
2225
  mode: 'fresh' | 'adopt' | 'gitops'
2137
2226
  namespace: string
2138
2227
  release: string
2139
- stage: 'inspect' | 'prepare' | 'preflight'
2228
+ stage: CloudInstallStage
2140
2229
  // Discovery saw only the default namespace; a fresh plan is not proof that
2141
2230
  // no Radar exists elsewhere.
2142
2231
  partialScan?: boolean
@@ -2147,6 +2236,8 @@ export interface CloudInstallAttempted {
2147
2236
  method?: 'argocd' | 'flux' | ''
2148
2237
  }
2149
2238
 
2239
+ export type CloudInstallStage = 'inspect' | 'prepare' | 'preflight'
2240
+
2150
2241
  export interface CloudInstallBlocked {
2151
2242
  reason: 'gitops' | 'preflight' | 'unsupported'
2152
2243
  // The Kubernetes user the attempt acted as; absent when the API server
@@ -2176,6 +2267,8 @@ export type CloudInstallState =
2176
2267
  export interface CloudInstallStatus {
2177
2268
  flowId?: string
2178
2269
  state: CloudInstallState
2270
+ // Preparing only: the check the server is running now.
2271
+ prepareStep?: CloudInstallStage
2179
2272
  plan?: CloudInstallPlanSummary
2180
2273
  clusterName?: string
2181
2274
  connectUrl?: string
@@ -2241,7 +2334,10 @@ export function useCloudConnectInfo(
2241
2334
  });
2242
2335
  }
2243
2336
 
2244
- export function useCloudInstallStatus(enabled: boolean) {
2337
+ // preparing: the prepare request is in flight. It answers only once every
2338
+ // check has run, and the cached status from before it says idle, so without
2339
+ // this nothing would poll and the steps could not advance.
2340
+ export function useCloudInstallStatus(enabled: boolean, preparing = false) {
2245
2341
  const queryClient = useQueryClient()
2246
2342
  const query = useQuery<CloudInstallStatus>({
2247
2343
  queryKey: ['cloud-install-status'],
@@ -2249,7 +2345,10 @@ export function useCloudInstallStatus(enabled: boolean) {
2249
2345
  enabled,
2250
2346
  gcTime: 0,
2251
2347
  staleTime: 0,
2252
- refetchInterval: (q) => (cloudInstallActive(q.state.data?.state) ? 1500 : false),
2348
+ refetchInterval: (q) => {
2349
+ if (preparing || q.state.data?.state === 'preparing') return 1000
2350
+ return cloudInstallActive(q.state.data?.state) ? 1500 : false
2351
+ },
2253
2352
  })
2254
2353
  return {
2255
2354
  ...query,
@@ -2846,30 +2945,42 @@ export function refetchOnResourceEvents(
2846
2945
  return namedObjects.has(resourceEventKey(kind, String(namespace ?? ""), String(name ?? "")));
2847
2946
  }
2848
2947
 
2849
- // `cacheScope` keeps a caller's copy apart from the shared one, for hosts
2850
- // that point one QueryClient at several clusters (see useGitOpsWriteGuard).
2851
- export function useResource<T>(
2948
+ // The query behind useResource, for callers that read several resources at
2949
+ // once (useQueries) and must keep its key, polling and retry rules.
2950
+ export function resourceQueryOptions<T>(
2852
2951
  kind: string,
2853
2952
  namespace: string,
2854
2953
  name: string,
2855
2954
  group?: string,
2856
2955
  options?: { enabled?: boolean; refetchInterval?: number | false; cacheScope?: string },
2857
2956
  ) {
2858
- const query = useQuery<ResourceWithRelationships<T>>({
2957
+ return {
2859
2958
  queryKey: ["resource", kind, namespace, name, group, ...(options?.cacheScope ? [options.cacheScope] : [])],
2860
2959
  queryFn: () => fetchResourceWithRelationships<T>(kind, namespace, name, group),
2861
2960
  enabled: (options?.enabled ?? true) && Boolean(kind && name), // namespace can be empty for cluster-scoped resources
2862
- refetchInterval: (query) => goneRecheckInterval(query, options?.refetchInterval),
2961
+ refetchInterval: (query: { state: { error: unknown } }) => goneRecheckInterval(query, options?.refetchInterval),
2863
2962
  // Kind still completing its initial sync: stay in loading and poll until
2864
2963
  // it becomes readable instead of erroring out (deep links during startup).
2865
- retry: (failureCount, error) => {
2964
+ retry: (failureCount: number, error: unknown) => {
2866
2965
  if (isStillLoadingError(error)) return true;
2867
2966
  if (isKindSyncFailed(error)) return false;
2868
2967
  return failureCount < 1; // one retry, 4xx included, unlike the QueryClient default
2869
2968
  },
2870
- retryDelay: (failureCount, error) =>
2969
+ retryDelay: (failureCount: number, error: unknown) =>
2871
2970
  isStillLoadingError(error) ? 2000 : Math.min(1000 * 2 ** failureCount, 30000),
2872
- });
2971
+ };
2972
+ }
2973
+
2974
+ // `cacheScope` keeps a caller's copy apart from the shared one, for hosts
2975
+ // that point one QueryClient at several clusters (see useGitOpsWriteGuard).
2976
+ export function useResource<T>(
2977
+ kind: string,
2978
+ namespace: string,
2979
+ name: string,
2980
+ group?: string,
2981
+ options?: { enabled?: boolean; refetchInterval?: number | false; cacheScope?: string },
2982
+ ) {
2983
+ const query = useQuery<ResourceWithRelationships<T>>(resourceQueryOptions<T>(kind, namespace, name, group, options));
2873
2984
 
2874
2985
  // Extract resource and relationships from the response
2875
2986
  return {
@@ -2969,14 +3080,15 @@ export function useResources<T>(
2969
3080
  kind: string,
2970
3081
  namespace?: string,
2971
3082
  group?: string,
2972
- options?: { enabled?: boolean; refetchInterval?: number | false; cacheScope?: string },
3083
+ options?: { enabled?: boolean; refetchInterval?: number | false; cacheScope?: string; refetchOnMount?: boolean | 'always'; staleTime?: number },
2973
3084
  ) {
2974
3085
  const loadingInterval = useMemo(() => createListRefetchInterval(options?.refetchInterval), [options?.refetchInterval])
2975
3086
  const query = useQuery<ResourceListResult<T>>({
2976
3087
  queryKey: ["resources", kind, group, namespace, ...(options?.cacheScope ? [options.cacheScope] : [])],
2977
3088
  queryFn: ({ signal }) => fetchResourceList<T>(kind, { namespaces: namespace ? [namespace] : [], group, signal }),
2978
3089
  enabled: (options?.enabled ?? true) && Boolean(kind),
2979
- staleTime: 30000, // 30 seconds - matches refetchInterval in ResourcesView
3090
+ staleTime: options?.staleTime ?? 30000, // 30 seconds - matches refetchInterval in ResourcesView
3091
+ ...(options?.refetchOnMount !== undefined ? { refetchOnMount: options.refetchOnMount } : {}),
2980
3092
  refetchInterval: loadingInterval,
2981
3093
  // Kind still completing its initial sync (progressive shell, or a
2982
3094
  // deferred kind shortly after connect): keep polling instead of
@@ -3250,8 +3362,12 @@ export interface WorkloadHistoryPage {
3250
3362
  events: TimelineEvent[];
3251
3363
  truncated: boolean;
3252
3364
  nextBeforeSeq?: number;
3253
- /** The workload has more related resources than the history follows. */
3365
+ /** Related history may be missing because scope bounds or expired ownership records limit traversal. */
3254
3366
  incomplete?: boolean;
3367
+ /** Radar may not hold every change since the workload existed; absent when it does, and from older Radars. */
3368
+ historyCoverage?: WorkloadHistoryCoverage;
3369
+ /** Related kinds this history can't include for the caller (a queued job's Kueue Workload); the same on every page. */
3370
+ gaps?: ReadGap[];
3255
3371
  }
3256
3372
 
3257
3373
  function workloadHistoryPath(kind: string, namespace: string, name: string, group?: string, beforeSeq?: number): string {
@@ -4052,6 +4168,7 @@ export function useAutoPromConnect(): void {
4052
4168
  // meta-driven toast handler stays silent — the user didn't click anything.
4053
4169
  apiFetch(`${getApiBase()}/prometheus/connect?optional=true`, {
4054
4170
  method: "POST",
4171
+ headers: automaticRequestHeaders(),
4055
4172
  })
4056
4173
  .then(async (resp) => {
4057
4174
  if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
@@ -6015,13 +6132,59 @@ function helmNamespaceParams(namespaces: string[] = []) {
6015
6132
  return namespaces.length > 0 ? `?namespaces=${namespaces.join(",")}` : "";
6016
6133
  }
6017
6134
 
6018
- // List all Helm releases
6019
- export function useHelmReleases(namespaces: string[] = []) {
6135
+ // Objects still loading clear on their own, so the list shouldn't wait for a
6136
+ // manual refresh to fill in. Some gaps outlast any quick retry, such as
6137
+ // permission checks spread over many namespaces, so polling slows rather than
6138
+ // repeating a full object read every few seconds.
6139
+ const HELM_INVENTORY_FAST_POLLS = 24;
6140
+
6141
+ export function helmInventoryRefetchInterval(inventory: Pick<HelmInventory, "objectCoverage"> | undefined, updates: number): number | false {
6142
+ const settling = inventory?.objectCoverage?.gaps.some((gap) => gap.action === "retry" || gap.action === "wait");
6143
+ if (!settling) return false;
6144
+ return updates < HELM_INVENTORY_FAST_POLLS ? 5000 : 60000;
6145
+ }
6146
+
6147
+ // The Helm list as far as the caller's access reaches. An older Radar has no
6148
+ // inventory route: its list is the whole answer, and a denial stays a 403.
6149
+ export function useHelmInventory(namespaces: string[] = []) {
6020
6150
  const params = helmNamespaceParams(namespaces);
6021
- return useQuery<HelmRelease[]>({
6022
- queryKey: ["helm-releases", namespaces],
6023
- queryFn: () => fetchJSON(`/helm/releases${params}`),
6151
+ const { isPending: capabilitiesPending } = useCapabilities();
6152
+ const { support } = useRadarFeature("helmInventory");
6153
+ const hasInventory = support === "supported";
6154
+ return useQuery<HelmInventory>({
6155
+ queryKey: ["helm-releases", namespaces, hasInventory],
6156
+ queryFn: async () =>
6157
+ hasInventory
6158
+ ? fetchJSON<HelmInventory>(`/helm/inventory${params}`)
6159
+ : { releases: await fetchJSON<HelmRelease[]>(`/helm/releases${params}`), observed: [] },
6160
+ enabled: !capabilitiesPending,
6024
6161
  staleTime: 30000, // 30 seconds
6162
+ refetchInterval: (query) => helmInventoryRefetchInterval(query.state.data, query.state.dataUpdateCount),
6163
+ });
6164
+ }
6165
+
6166
+ // Kubernetes refused the caller's own read of Helm's storage. Other 403s on the
6167
+ // same route mean something else, and a Radar without inventory sends no code.
6168
+ export function isHelmReleaseReadDenied(error: unknown): boolean {
6169
+ return isForbiddenError(error) && (error as ApiError).data?.error_code === "release_read_denied";
6170
+ }
6171
+
6172
+ // Each observed read walks every object the caller can see, so an open drawer
6173
+ // follows the list's schedule while objects settle and otherwise refreshes
6174
+ // once a minute. A retryable error retries sooner.
6175
+ export function observedHelmReleaseRefetchInterval(detail: ObservedHelmReleaseDetail | undefined, updates: number, error: unknown): number | false {
6176
+ if (error) return isStableClientError(error) ? false : 15000
6177
+ return helmInventoryRefetchInterval(detail, updates) || 60000
6178
+ }
6179
+
6180
+ // One release built from the stamps on its objects, for a caller who can't read
6181
+ // Helm's storage.
6182
+ export function useObservedHelmRelease(namespace: string, name: string) {
6183
+ return useQuery<ObservedHelmReleaseDetail>({
6184
+ queryKey: ["helm-observed-release", namespace, name],
6185
+ queryFn: () => fetchJSON(`/helm/inventory/${namespace}/${name}`),
6186
+ staleTime: 5000,
6187
+ refetchInterval: (query) => observedHelmReleaseRefetchInterval(query.state.data, query.state.dataUpdateCount, query.state.error),
6025
6188
  });
6026
6189
  }
6027
6190
 
@@ -6036,7 +6199,9 @@ export function useHelmRelease(
6036
6199
  queryFn: () => fetchJSON(`/helm/releases/${namespace}/${name}`),
6037
6200
  enabled: Boolean(namespace && name) && (options?.enabled ?? true),
6038
6201
  staleTime: 5000,
6039
- refetchInterval: 10000, // Poll for live resource status updates (post-upgrade/rollback)
6202
+ // Poll for live resource status updates (post-upgrade/rollback); a refusal
6203
+ // would only repeat.
6204
+ refetchInterval: (query) => (isForbiddenError(query.state.error) ? false : 10000),
6040
6205
  });
6041
6206
  }
6042
6207
 
@@ -6910,12 +7075,15 @@ export function useArtifactHubChart(
6910
7075
  // GitOps Mutation Factory
6911
7076
  // ============================================================================
6912
7077
 
6913
- interface GitOpsMutationConfig<TVariables> {
7078
+ interface GitOpsMutationConfig<TVariables, TContext = undefined> {
6914
7079
  getPath: (variables: TVariables) => string;
6915
- getBody?: (variables: TVariables) => unknown;
7080
+ // Called by the hook on every render (so it may call hooks); its value is
7081
+ // passed to getBody.
7082
+ useRequestContext?: () => TContext;
7083
+ getBody?: (variables: TVariables, context: TContext) => unknown;
6916
7084
  errorMessage: string;
6917
7085
  successMessage?: string;
6918
- getSuccessMessage?: (data: GitOpsOperationResponse) => string;
7086
+ getSuccessMessage?: (data: GitOpsOperationResponse, variables: TVariables) => string;
6919
7087
  getInvalidateKeys: (variables: TVariables) => (string | undefined)[][];
6920
7088
  }
6921
7089
 
@@ -6923,11 +7091,12 @@ interface GitOpsMutationConfig<TVariables> {
6923
7091
  * Factory function for creating GitOps mutation hooks with consistent patterns.
6924
7092
  * Handles fetch, error handling, meta messages, and query invalidation.
6925
7093
  */
6926
- function createGitOpsMutation<TVariables>(
6927
- config: GitOpsMutationConfig<TVariables>,
7094
+ function createGitOpsMutation<TVariables, TContext = undefined>(
7095
+ config: GitOpsMutationConfig<TVariables, TContext>,
6928
7096
  ) {
6929
7097
  return function useGitOpsMutation() {
6930
7098
  const queryClient = useQueryClient();
7099
+ const requestContext = config.useRequestContext?.() as TContext;
6931
7100
  return useMutation<GitOpsOperationResponse, Error, TVariables>({
6932
7101
  mutationFn: async (
6933
7102
  variables: TVariables,
@@ -6940,7 +7109,7 @@ function createGitOpsMutation<TVariables>(
6940
7109
  ? { "Content-Type": "application/json" }
6941
7110
  : undefined,
6942
7111
  body: config.getBody
6943
- ? JSON.stringify(config.getBody(variables))
7112
+ ? JSON.stringify(config.getBody(variables, requestContext))
6944
7113
  : undefined,
6945
7114
  },
6946
7115
  );
@@ -6956,7 +7125,7 @@ function createGitOpsMutation<TVariables>(
6956
7125
  },
6957
7126
  onSuccess: (data, variables) => {
6958
7127
  if (config.getSuccessMessage)
6959
- showApiSuccess(config.getSuccessMessage(data));
7128
+ showApiSuccess(config.getSuccessMessage(data, variables));
6960
7129
  config
6961
7130
  .getInvalidateKeys(variables)
6962
7131
  .forEach((key) => queryClient.invalidateQueries({ queryKey: key }));
@@ -6987,8 +7156,12 @@ export type ArgoSyncVars = ArgoAppVars & {
6987
7156
  applyOnly?: boolean;
6988
7157
  // Free-form Argo SyncOption strings, e.g. "Replace=true",
6989
7158
  // "ServerSideApply=true", "PruneLast=true". Caller is responsible for
6990
- // spelling.
7159
+ // spelling. Omitted: the Application's own spec.syncPolicy.syncOptions.
6991
7160
  syncOptions?: string[];
7161
+ // The Application's spec.syncPolicy.syncOptions as the caller last read
7162
+ // them. Not a request field: sent as syncOptions only to a Radar that would
7163
+ // otherwise drop them (see argoSyncRequestBody).
7164
+ applicationSyncOptions?: string[];
6992
7165
  };
6993
7166
 
6994
7167
  export interface ArgoResourceValidationResult {
@@ -7009,11 +7182,13 @@ export function buildArgoResourceSyncVars(
7009
7182
  name: string,
7010
7183
  resource: GitOpsInsightRef,
7011
7184
  opts: ArgoSyncOpts,
7185
+ applicationSyncOptions?: string[],
7012
7186
  ): ArgoSyncVars {
7013
7187
  return {
7014
7188
  namespace,
7015
7189
  name,
7016
7190
  ...opts,
7191
+ applicationSyncOptions,
7017
7192
  resources: [
7018
7193
  {
7019
7194
  group: resource.group,
@@ -7096,24 +7271,45 @@ export const useFluxSyncWithSource = createGitOpsMutation<FluxResourceVars>({
7096
7271
  // ArgoCD API hooks
7097
7272
  // ============================================================================
7098
7273
 
7099
- export const useArgoSync = createGitOpsMutation<ArgoSyncVars>({
7100
- getPath: (v) => `/argo/applications/${v.namespace}/${v.name}/sync`,
7101
- getBody: (v) => ({
7274
+ // argoSyncRequestBody is the body POSTed to .../sync. A Radar that predates
7275
+ // argoSyncInheritance prunes when prune is omitted and syncs with no options
7276
+ // when syncOptions is omitted, so prune is always sent and, for such a Radar,
7277
+ // the Application's options are sent in place of an omission.
7278
+ export function argoSyncRequestBody(
7279
+ v: ArgoSyncVars,
7280
+ serverInheritsOptions: boolean,
7281
+ ) {
7282
+ return {
7102
7283
  resources: v.resources,
7103
7284
  revision: v.revision,
7104
- prune: v.prune,
7285
+ prune: v.prune ?? false,
7105
7286
  dryRun: v.dryRun,
7106
7287
  force: v.force,
7107
7288
  applyOnly: v.applyOnly,
7108
- syncOptions: v.syncOptions,
7109
- }),
7289
+ syncOptions: argoSyncOptionsForRequest(
7290
+ v.syncOptions,
7291
+ v.applicationSyncOptions,
7292
+ serverInheritsOptions,
7293
+ ),
7294
+ };
7295
+ }
7296
+
7297
+ function useArgoSyncInheritance(): boolean {
7298
+ return useRadarFeature("argoSyncInheritance").support === "supported";
7299
+ }
7300
+
7301
+ export const useArgoSync = createGitOpsMutation<ArgoSyncVars, boolean>({
7302
+ getPath: (v) => `/argo/applications/${v.namespace}/${v.name}/sync`,
7303
+ useRequestContext: useArgoSyncInheritance,
7304
+ getBody: argoSyncRequestBody,
7110
7305
  errorMessage: "Failed to trigger sync",
7111
- successMessage: "Sync initiated",
7306
+ getSuccessMessage: (_data, v) => (v.dryRun ? "Dry run started" : "Sync initiated"),
7112
7307
  getInvalidateKeys: argoInvalidateKeys,
7113
7308
  });
7114
7309
 
7115
7310
  export function useArgoResourceValidation() {
7116
7311
  const queryClient = useQueryClient();
7312
+ const serverInheritsOptions = useArgoSyncInheritance();
7117
7313
  return useMutation<ArgoResourceValidationResult, Error, ArgoSyncVars>({
7118
7314
  mutationFn: async (variables) => {
7119
7315
  const response = await apiFetch(
@@ -7124,7 +7320,11 @@ export function useArgoResourceValidation() {
7124
7320
  body: JSON.stringify({
7125
7321
  resources: variables.resources,
7126
7322
  force: variables.force,
7127
- syncOptions: variables.syncOptions,
7323
+ syncOptions: argoSyncOptionsForRequest(
7324
+ variables.syncOptions,
7325
+ variables.applicationSyncOptions,
7326
+ serverInheritsOptions,
7327
+ ),
7128
7328
  }),
7129
7329
  },
7130
7330
  );
@@ -7146,7 +7346,7 @@ export const useArgoRollback = createGitOpsMutation<ArgoRollbackVars>({
7146
7346
  getPath: (v) => `/argo/applications/${v.namespace}/${v.name}/rollback`,
7147
7347
  getBody: (v) => ({ id: v.id, prune: v.prune, dryRun: v.dryRun }),
7148
7348
  errorMessage: "Failed to roll back application",
7149
- successMessage: "Rollback initiated",
7349
+ getSuccessMessage: (_data, v) => (v.dryRun ? "Rollback preview started" : "Rollback initiated"),
7150
7350
  getInvalidateKeys: argoInvalidateKeys,
7151
7351
  });
7152
7352
 
@@ -7256,6 +7456,19 @@ export async function fetchSessionCounts(): Promise<SessionCounts> {
7256
7456
  const CONTEXT_SWITCH_TIMEOUT = 45000; // 45 seconds
7257
7457
 
7258
7458
  // Switch to a different context
7459
+ // A refused context switch. errorType is set when the server checked the new
7460
+ // cluster before leaving the current one and it didn't answer; older Radar
7461
+ // servers never send it.
7462
+ export class SwitchContextError extends Error {
7463
+ constructor(
7464
+ message: string,
7465
+ readonly errorType?: string,
7466
+ ) {
7467
+ super(message);
7468
+ this.name = "SwitchContextError";
7469
+ }
7470
+ }
7471
+
7259
7472
  export function useSwitchContext() {
7260
7473
  const queryClient = useQueryClient();
7261
7474
 
@@ -7279,7 +7492,10 @@ export function useSwitchContext() {
7279
7492
 
7280
7493
  if (!response.ok) {
7281
7494
  const error = await readErrorBody(response);
7282
- throw new Error(error.error || `HTTP ${response.status}`);
7495
+ throw new SwitchContextError(
7496
+ error.error || `HTTP ${response.status}`,
7497
+ typeof error.errorType === "string" ? error.errorType : undefined,
7498
+ );
7283
7499
  }
7284
7500
  return response.json();
7285
7501
  } catch (error) {
@@ -7671,8 +7887,8 @@ export function useWorkloadPods(
7671
7887
  fetchJSON(`/workloads/${kind}/${namespace}/${name}/pods${queryString}`),
7672
7888
  enabled: Boolean(kind && namespace && name),
7673
7889
  staleTime: 10000, // 10 seconds - pods can change
7674
- refetchInterval: options?.refetchInterval ?? false,
7675
- retry: options?.ownerUID ? (count, error) => !(error instanceof ApiError && error.status === 409) && count < 2 : undefined,
7890
+ refetchInterval: (query) => workloadPodsRefetchInterval(query.state.error, options),
7891
+ retry: options?.ownerUID ? (count, error) => !isStableClientError(error) && count < 2 : undefined,
7676
7892
  });
7677
7893
  }
7678
7894
 
@@ -7732,6 +7948,32 @@ export function useKueueAdmission(namespace: string, name: string, uid: string |
7732
7948
  })
7733
7949
  }
7734
7950
 
7951
+ // Kueue's reported position for one pending Workload. Polls only while the
7952
+ // answer can change by itself: a refusal, an absent API or an unsupported
7953
+ // version gives the same answer until someone changes access or the cluster.
7954
+ const kueuePositionPolledStatuses = new Set(['listed', 'not_listed', 'limit_reached', 'queue_unknown'])
7955
+
7956
+ export function kueuePositionRefetchInterval({ data, error }: { data?: KueuePositionResponse; error?: unknown }): number | false {
7957
+ if (error && !shouldRetryRadarQuery(0, error)) return false
7958
+ if (!data?.eligible || !data.position) return 30000
7959
+ const { status, code } = data.position
7960
+ return kueuePositionPolledStatuses.has(status) || (status === 'unavailable' && readActionFor(code) === 'retry') ? 30000 : false
7961
+ }
7962
+
7963
+ /** UID and queueName invalidate the cache; the endpoint reads by namespace/name.
7964
+ * Callers must check the returned UID and eligibility before displaying a position. */
7965
+ export function useKueuePendingPosition(namespace: string, name: string, uid: string | undefined, queueName: string | undefined, enabled: boolean) {
7966
+ const { guard, gatedKey } = useRadarFeature('kueuePendingPosition')
7967
+ return useQuery<KueuePositionResponse>({
7968
+ queryKey: ['kueue-position', namespace, name, uid, queueName ?? '', ...gatedKey],
7969
+ queryFn: () => guard(() => fetchJSON<KueuePositionResponse>(`/kueue/position/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`)),
7970
+ enabled: enabled && Boolean(namespace && name && uid),
7971
+ staleTime: 15000,
7972
+ refetchInterval: (query) => kueuePositionRefetchInterval(query.state),
7973
+ retry: shouldRetryRadarQuery,
7974
+ })
7975
+ }
7976
+
7735
7977
  // Fetch logs for a workload (non-streaming)
7736
7978
  export function useWorkloadLogs(
7737
7979
  kind: string,
@@ -8076,6 +8318,53 @@ export interface KueueProvisioningResponse {
8076
8318
  }>
8077
8319
  }
8078
8320
 
8321
+ // The Workloads that belong to a Kueue queue, page by page. Pages chain by
8322
+ // cursor; a refetch re-reads them from the first, so a list that changed is
8323
+ // traversed again rather than patched. Nothing is read until the queue's UID
8324
+ // is known, nor for a LocalQueue without its namespace.
8325
+ export function useKueueQueueWorkloads(queue: { kind: 'ClusterQueue' | 'LocalQueue'; namespace?: string; name: string; uid?: string }, filters: { membership?: KueueQueueMembership; state?: string }) {
8326
+ const { membership, state } = filters
8327
+ const { guard, gatedKey, support, upgrade } = useRadarFeature('kueueQueueWorkloads')
8328
+ const path = queue.kind === 'ClusterQueue'
8329
+ ? `/kueue/clusterqueues/${encodeURIComponent(queue.name)}/workloads`
8330
+ : `/kueue/localqueues/${encodeURIComponent(queue.namespace ?? '')}/${encodeURIComponent(queue.name)}/workloads`
8331
+ const query = useInfiniteQuery<KueueQueueWorkloadsResponse>({
8332
+ queryKey: ['kueue-queue-workloads', queue.kind, queue.namespace ?? '', queue.name, queue.uid ?? '', membership ?? '', state ?? '', ...gatedKey],
8333
+ queryFn: ({ pageParam, signal }) => {
8334
+ const params = new URLSearchParams()
8335
+ if (membership) params.set('membership', membership)
8336
+ if (state) params.set('state', state)
8337
+ if (typeof pageParam === 'string') params.set('cursor', pageParam)
8338
+ const qs = params.toString()
8339
+ return guard(() => fetchJSON<KueueQueueWorkloadsResponse>(`${path}${qs ? `?${qs}` : ''}`, signal))
8340
+ },
8341
+ initialPageParam: undefined as string | undefined,
8342
+ getNextPageParam: last => last.workloads?.next,
8343
+ // A changed filter keeps the previous list on screen until the new one
8344
+ // arrives; the renderer drops pages of another queue (by UID).
8345
+ placeholderData: previous => previous,
8346
+ enabled: Boolean(queue.name && queue.uid && (queue.kind === 'ClusterQueue' || queue.namespace)) && support !== 'unsupported',
8347
+ staleTime: 5000,
8348
+ // A paged list isn't replayed on mount (that would reread the queue once
8349
+ // per page); the renderer restarts it from the first page instead.
8350
+ refetchOnMount: query => (query.state.data?.pages.length ?? 0) <= 1,
8351
+ refetchOnWindowFocus: query => (query.state.data?.pages.length ?? 0) <= 1,
8352
+ refetchOnReconnect: query => (query.state.data?.pages.length ?? 0) <= 1,
8353
+ // Poll the first page only: refetching an infinite query rereads every
8354
+ // loaded page, so a list paged further waits for an explicit refresh.
8355
+ // A part a retry can complete (still loading, a check that failed) is
8356
+ // polled sooner.
8357
+ refetchInterval: query => {
8358
+ if (query.state.error instanceof ApiError && query.state.error.status < 500) return false
8359
+ const pages = query.state.data?.pages ?? []
8360
+ if (pages.length > 1) return false
8361
+ return kueueQueueRetryable(pages[0]) ? 3000 : 15000
8362
+ },
8363
+ retry: shouldRetryRadarQuery,
8364
+ })
8365
+ return { ...query, upgrade, support }
8366
+ }
8367
+
8079
8368
  export function useKueueProvisioning(namespace: string, name: string, uid: string | undefined, enabled: boolean) {
8080
8369
  return useQuery<KueueProvisioningResponse>({
8081
8370
  queryKey: ['kueue-provisioning', namespace, name, uid],