@skyhook-io/radar-app 1.21.2 → 1.21.3

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 (89) hide show
  1. package/README.md +11 -0
  2. package/package.json +2 -2
  3. package/src/App.tsx +50 -28
  4. package/src/api/actions.test.ts +11 -0
  5. package/src/api/actions.ts +5 -0
  6. package/src/api/apiResources.navigation.test.tsx +58 -0
  7. package/src/api/apiResources.ts +22 -16
  8. package/src/api/client.diagnostics.test.ts +52 -0
  9. package/src/api/client.triggerCronJob.test.tsx +49 -0
  10. package/src/api/client.ts +140 -120
  11. package/src/api/connectionBinding.test.tsx +82 -0
  12. package/src/api/connectionBinding.ts +52 -0
  13. package/src/api/contextSwitch.test.ts +11 -0
  14. package/src/api/contextSwitch.ts +58 -0
  15. package/src/api/radarFeatures.ts +5 -0
  16. package/src/components/ConnectionErrorView.tsx +13 -0
  17. package/src/components/ContextSwitchActions.tsx +43 -0
  18. package/src/components/ContextSwitcher.tsx +13 -6
  19. package/src/components/SwitchAwareConnectionError.tsx +2 -2
  20. package/src/components/cost/ApplicationCostTab.test.ts +16 -0
  21. package/src/components/cost/ApplicationCostTab.tsx +41 -9
  22. package/src/components/cost/CostTrendChart.tsx +25 -2
  23. package/src/components/cost/CostTrendWithheld.render.test.tsx +105 -0
  24. package/src/components/cost/CostView.tsx +10 -2
  25. package/src/components/cost/CostViewTabs.test.tsx +18 -0
  26. package/src/components/cost/CostViewTabs.tsx +14 -22
  27. package/src/components/cost/WorkloadCostTab.test.ts +15 -0
  28. package/src/components/cost/WorkloadCostTab.tsx +42 -8
  29. package/src/components/cost/source.test.ts +16 -1
  30. package/src/components/cost/source.ts +34 -0
  31. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +35 -0
  32. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +16 -1
  33. package/src/components/dock/NodeTerminalTab.test.tsx +4 -2
  34. package/src/components/dock/NodeTerminalTab.tsx +8 -8
  35. package/src/components/dock/TerminalTab.test.tsx +12 -1
  36. package/src/components/dock/TerminalTab.tsx +6 -3
  37. package/src/components/home/CostCard.test.tsx +49 -0
  38. package/src/components/home/CostCard.tsx +98 -63
  39. package/src/components/home/mcpToolCatalog.ts +1 -0
  40. package/src/components/resource/DatadogRightsizingPanel.test.tsx +118 -0
  41. package/src/components/resource/DatadogRightsizingPanel.tsx +68 -0
  42. package/src/components/resource/DatadogWorkloadCharts.tsx +149 -0
  43. package/src/components/resource/HPACharts.render.test.tsx +42 -0
  44. package/src/components/resource/HPACharts.tsx +34 -1
  45. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +126 -3
  46. package/src/components/resource/PrometheusChartsGrid.tsx +58 -25
  47. package/src/components/resource/RestartChart.render.test.tsx +72 -0
  48. package/src/components/resource/RestartChart.tsx +31 -3
  49. package/src/components/resource/RightsizingPanel.access.test.tsx +24 -0
  50. package/src/components/resource/RightsizingStrip.render.test.tsx +44 -0
  51. package/src/components/resource/RightsizingStrip.test.ts +1 -188
  52. package/src/components/resource/RightsizingStrip.tsx +27 -300
  53. package/src/components/resource/WorkloadMetricsSection.render.test.tsx +22 -0
  54. package/src/components/resource/WorkloadMetricsSection.tsx +14 -4
  55. package/src/components/resource/nameMatchedScope.ts +39 -0
  56. package/src/components/resources/pod-file-upload.ts +3 -0
  57. package/src/components/resources/renderers/CAPIClusterRenderer.tsx +5 -2
  58. package/src/components/resources/renderers/LonghornVolumeRenderer.test.tsx +104 -0
  59. package/src/components/resources/renderers/LonghornVolumeRenderer.tsx +31 -0
  60. package/src/components/rightsizing/RightsizingScanLink.tsx +22 -0
  61. package/src/components/rightsizing/RightsizingScanView.tsx +65 -528
  62. package/src/components/rightsizing/model.test.ts +20 -9
  63. package/src/components/rightsizing/model.ts +17 -176
  64. package/src/components/rightsizing/notices.test.tsx +30 -29
  65. package/src/components/ui/DiagnosticsOverlay.test.ts +3 -2
  66. package/src/components/ui/DiagnosticsOverlay.tsx +23 -13
  67. package/src/components/ui/command-items.ts +3 -4
  68. package/src/components/useContextSwitchFlow.test.tsx +9 -0
  69. package/src/components/useContextSwitchFlow.tsx +43 -5
  70. package/src/components/workload/WorkloadRightsizingSource.test.tsx +83 -0
  71. package/src/components/workload/WorkloadView.test.ts +22 -1
  72. package/src/components/workload/WorkloadView.tsx +57 -16
  73. package/src/context/ConnectionContext.test.ts +1 -0
  74. package/src/context/ConnectionContext.tsx +58 -15
  75. package/src/context/ConnectionProvider.connectionId.test.tsx +92 -0
  76. package/src/context/ConnectionProvider.retry.test.tsx +174 -1
  77. package/src/context/ContextSwitchContext.tsx +15 -1
  78. package/src/context/NavCustomization.tsx +6 -3
  79. package/src/hooks/useEventSource.test.tsx +85 -0
  80. package/src/hooks/useEventSource.ts +43 -16
  81. package/src/hooks/useResetViewsOnContextChange.test.tsx +34 -0
  82. package/src/hooks/useResetViewsOnContextChange.ts +27 -0
  83. package/src/index.ts +3 -0
  84. package/src/integrations/resourceHosts.test.tsx +1 -1
  85. package/src/integrations/resourceHosts.tsx +2 -0
  86. package/src/utils/navigation.ts +1 -15
  87. package/src/utils/page-links.ts +6 -0
  88. package/src/components/rightsizing/presentation.test.ts +0 -150
  89. package/src/components/rightsizing/presentation.ts +0 -109
package/src/api/client.ts CHANGED
@@ -1,8 +1,11 @@
1
+ import type { RightsizingRow, WorkloadRightsizingEvidence } from '@skyhook-io/k8s-ui/types/rightsizing'
2
+ import { followSwitch, switchFinished, switchInProgress, type ContextSwitchOperation } from './contextSwitch'
1
3
  import { createListRefetchInterval, normalizeResourceList, type ResourceListBody, type ResourceListResult } from './resourceLists'
2
4
  import type { CascadeDetail } from '@skyhook-io/k8s-ui/components/ui/ForceDeleteConfirmDialog'
3
5
  import { canonicalResourceGroup } from '@skyhook-io/k8s-ui/utils/api-resources'
4
6
  import { pluralize } from '@skyhook-io/k8s-ui/utils/pluralize'
5
7
  import type { ReadGap, ReadGapSet } from '@skyhook-io/k8s-ui/types/read-coverage'
8
+ import type { ClusterScope } from '@skyhook-io/k8s-ui/types/cluster-scope'
6
9
  import type { WorkloadHistoryCoverage } from '@skyhook-io/k8s-ui/utils/workload-history-notes'
7
10
  import { knownKindForPluralWithGroup, pluralToKind } from '@skyhook-io/k8s-ui/utils/navigation'
8
11
  import { useEffect, useRef, useCallback, useMemo } from 'react'
@@ -26,6 +29,7 @@ import type {
26
29
  CapacityOverviewResponse,
27
30
  CapacityPoolDetailResponse,
28
31
  CapacityPoolListResponse,
32
+ NamespaceCollection,
29
33
  SetWorkloadImagesResult,
30
34
  WorkloadImageInventory,
31
35
  WorkloadImageUpdate,
@@ -77,6 +81,7 @@ import type {
77
81
  } from '../types'
78
82
  import type { GitOpsOperationResponse } from '../types/gitops'
79
83
  import { apiUrl, automaticRequestHeaders, getApiBase, getAuthHeaders, getCredentialsMode, getBasename, routePath, stripBasename } from './config'
84
+ import { CONNECTION_HEADER, connectionHeaderValue } from './connectionBinding'
80
85
  import { httpStatusMessage, markShownInline, readErrorBody, readErrorResponse } from './httpErrors'
81
86
  import {
82
87
  RadarFeatureUnsupportedError,
@@ -161,6 +166,10 @@ export function apiFetch(
161
166
  for (const [k, v] of Object.entries(getAuthHeaders())) {
162
167
  if (!headers.has(k)) headers.set(k, v);
163
168
  }
169
+ // Name the connection this tab is on, so the server can refuse a write
170
+ // meant for a cluster it no longer serves (see connectionBinding.ts).
171
+ const connection = connectionHeaderValue();
172
+ if (connection && !headers.has(CONNECTION_HEADER)) headers.set(CONNECTION_HEADER, connection);
164
173
  return fetch(input, {
165
174
  credentials: getCredentialsMode(),
166
175
  ...init,
@@ -713,7 +722,7 @@ export interface DashboardResponse {
713
722
  maxVersion: string;
714
723
  } | null;
715
724
  deferredLoading?: boolean; // True while deferred informers (secrets, events, etc.) are still syncing
716
- partialData?: string[]; // Critical kinds promoted at first paint that haven't yet finished syncing (live-filtered)
725
+ partialData?: string[]; // Resources still loading after the initial wait
717
726
  accessRestricted?: boolean; // True when user has no namespace access (RBAC)
718
727
  }
719
728
 
@@ -1235,7 +1244,12 @@ export type CostUnavailableReason =
1235
1244
  | "metrics_settings_error"
1236
1245
  | "cost_settings_error"
1237
1246
  | "history_unsupported"
1238
- | "insufficient_history";
1247
+ | "insufficient_history"
1248
+ // The metrics store holds several clusters and these costs couldn't be
1249
+ // kept to this one; clusterScope says why.
1250
+ | "cluster_scope"
1251
+ // The metrics store answered partially, so totals could miss series.
1252
+ | "partial_data";
1239
1253
 
1240
1254
  export type CostDataSource = "prometheus" | "kubecost";
1241
1255
 
@@ -1253,6 +1267,11 @@ export interface OpenCostSummary {
1253
1267
  clusterEfficiency?: number;
1254
1268
  namespaceScope?: string[];
1255
1269
  namespaces?: OpenCostNamespaceCost[];
1270
+ /** How a metrics-store answer was kept to this cluster; older Radar omits it. */
1271
+ clusterScope?: ClusterScope;
1272
+ /** Efficiency and idle couldn't be measured (not zero); usageClusterScope says why. */
1273
+ efficiencyUnavailable?: boolean;
1274
+ usageClusterScope?: ClusterScope;
1256
1275
  }
1257
1276
 
1258
1277
  const costDiscoveryFirstSeenAt = new Map<string, number>();
@@ -1331,6 +1350,11 @@ export interface OpenCostWorkloadResponse {
1331
1350
  currency?: string;
1332
1351
  namespace: string;
1333
1352
  workloads: OpenCostWorkloadCost[];
1353
+ /** How a metrics-store answer was kept to this cluster; older Radar omits it. */
1354
+ clusterScope?: ClusterScope;
1355
+ /** Efficiency and idle couldn't be measured (not zero); usageClusterScope says why. */
1356
+ efficiencyUnavailable?: boolean;
1357
+ usageClusterScope?: ClusterScope;
1334
1358
  }
1335
1359
 
1336
1360
  export function useOpenCostWorkloads(
@@ -1364,6 +1388,11 @@ export interface OpenCostWorkloadDetailResponse {
1364
1388
  kind: string;
1365
1389
  name: string;
1366
1390
  current?: OpenCostWorkloadCost;
1391
+ /** How a metrics-store answer was kept to this cluster; older Radar omits it. */
1392
+ clusterScope?: ClusterScope;
1393
+ /** Efficiency and idle couldn't be measured (not zero); usageClusterScope says why. */
1394
+ efficiencyUnavailable?: boolean;
1395
+ usageClusterScope?: ClusterScope;
1367
1396
  }
1368
1397
 
1369
1398
  export function useOpenCostWorkload(
@@ -1411,6 +1440,8 @@ export interface OpenCostTrendResponse {
1411
1440
  windowEnd?: number;
1412
1441
  dataThrough?: string;
1413
1442
  series?: OpenCostTrendSeries[];
1443
+ /** How a metrics-store answer was kept to this cluster; older Radar omits it. */
1444
+ clusterScope?: ClusterScope;
1414
1445
  }
1415
1446
 
1416
1447
  export function useOpenCostTrend(range_: CostTimeRange = "24h") {
@@ -1438,6 +1469,8 @@ export interface OpenCostWorkloadTrendResponse {
1438
1469
  range: string;
1439
1470
  windowTotalCost?: number;
1440
1471
  dataPoints?: OpenCostTrendDataPoint[];
1472
+ /** How a metrics-store answer was kept to this cluster; older Radar omits it. */
1473
+ clusterScope?: ClusterScope;
1441
1474
  }
1442
1475
 
1443
1476
  export function useOpenCostWorkloadTrend(
@@ -1512,6 +1545,8 @@ export interface OpenCostApplicationCostResponse {
1512
1545
  totals: OpenCostApplicationCostTotals;
1513
1546
  coverage: OpenCostApplicationCostCoverage;
1514
1547
  workloads?: OpenCostApplicationWorkloadCost[];
1548
+ /** How a metrics-store answer was kept to this cluster; older Radar omits it. */
1549
+ clusterScope?: ClusterScope;
1515
1550
  }
1516
1551
 
1517
1552
  export interface OpenCostApplicationCostTrendSeries extends OpenCostApplicationWorkloadRef {
@@ -1530,6 +1565,8 @@ export interface OpenCostApplicationCostTrendResponse {
1530
1565
  dataPoints?: OpenCostTrendDataPoint[];
1531
1566
  series?: OpenCostApplicationCostTrendSeries[];
1532
1567
  coverage: OpenCostApplicationCostCoverage;
1568
+ /** How a metrics-store answer was kept to this cluster; older Radar omits it. */
1569
+ clusterScope?: ClusterScope;
1533
1570
  }
1534
1571
 
1535
1572
  function stableOpenCostWorkloadRefs(
@@ -1619,6 +1656,8 @@ export interface OpenCostNodeResponse {
1619
1656
  dataThrough?: string;
1620
1657
  currency?: string;
1621
1658
  nodes?: OpenCostNodeCost[];
1659
+ /** How a metrics-store answer was kept to this cluster; older Radar omits it. */
1660
+ clusterScope?: ClusterScope;
1622
1661
  }
1623
1662
 
1624
1663
  export function useOpenCostNodes() {
@@ -4005,6 +4044,11 @@ export interface PrometheusResourceMetrics {
4005
4044
  // controller ownership. podsTotal is the full set when the cap cut the list.
4006
4045
  pods?: number;
4007
4046
  podsTotal?: number;
4047
+ // How the query was kept to this cluster in a shared metrics store; when it
4048
+ // withholds, result has no series. Older Radar omits it.
4049
+ clusterScope?: ClusterScope;
4050
+ // The store answered only partly: drawn, but samples may be missing.
4051
+ partial?: boolean;
4008
4052
  }
4009
4053
 
4010
4054
  export type PrometheusMetricCategory =
@@ -4024,72 +4068,10 @@ export interface PrometheusPVCUsage {
4024
4068
  hasData: boolean;
4025
4069
  }
4026
4070
 
4027
- export type RightsizingFit =
4028
- | "balanced"
4029
- | "oversized"
4030
- | "under_requested"
4031
- | "missing_request"
4032
- | "insufficient_history"
4033
- | "pod_level_request";
4034
- export type RightsizingConfidence = "low" | "medium" | "high";
4035
- export type RightsizingOwnerCoverage = "ksm_history" | "current_pods";
4036
-
4037
- export interface RightsizingRow {
4038
- container: string;
4039
- resource: "cpu" | "memory";
4040
- fit: RightsizingFit;
4041
- confidence: RightsizingConfidence;
4042
- currentRequest?: string;
4043
- currentRequestValue?: number;
4044
- currentLimit?: string;
4045
- currentLimitValue?: number;
4046
- /** The pod's fixed pod-level request (spec.resources), set when fit is pod_level_request. */
4047
- podLevelRequest?: string;
4048
- podLevelRequestValue?: number;
4049
- observed?: {
4050
- name: "P95" | "P99" | "Max";
4051
- value: number;
4052
- formatted: string;
4053
- };
4054
- peak?: {
4055
- name: "P99";
4056
- value: number;
4057
- formatted: string;
4058
- };
4059
- calculatedRequest?: string;
4060
- calculatedRequestValue?: number;
4061
- recommendedRequest?: string;
4062
- recommendedRequestValue?: number;
4063
- reductionLimited?: boolean;
4064
- bursty?: boolean;
4065
- recommendationReason?: string;
4066
- sampleCount: number;
4067
- expectedSamples: number;
4068
- coverage: number;
4069
- hpaManaged: boolean;
4070
- hpaEvidenceAvailable: boolean;
4071
- throttleAvailable?: boolean;
4072
- throttleRatio?: number;
4073
- currentPodOOM?: boolean;
4074
- windowOomEvidence?: boolean;
4075
- oomEvidenceAvailable: boolean;
4076
- /** The cluster cache would not list the workload's pods, so currentPodOOM is unknown rather than false. */
4077
- liveInventoryUnavailable?: boolean;
4078
- limitConflict?: boolean;
4079
- queryError?: string;
4080
- }
4081
-
4082
- export interface PrometheusRightsizing {
4083
- kind: string;
4084
- namespace: string;
4085
- name: string;
4086
- window: string;
4087
- source: "radar";
4088
- ownerCoverage: RightsizingOwnerCoverage;
4089
- scaledToZero: boolean;
4090
- sampleAvailable: boolean;
4091
- rows: RightsizingRow[];
4092
- reason?: string;
4071
+ export type { RightsizingRow, RightsizingFit, RightsizingConfidence, RightsizingOwnerCoverage } from '@skyhook-io/k8s-ui/types/rightsizing'
4072
+ export interface PrometheusRightsizing extends WorkloadRightsizingEvidence {
4073
+ source: "radar"
4074
+ clusterScope?: ClusterScope;
4093
4075
  }
4094
4076
 
4095
4077
  export type RightsizingScanState = "complete" | "partial" | "unavailable";
@@ -4100,6 +4082,7 @@ export interface RightsizingScanWorkload {
4100
4082
  name: string;
4101
4083
  replicas: number;
4102
4084
  scaledToZero: boolean;
4085
+ managedBy?: WorkloadRightsizingEvidence["managedBy"];
4103
4086
  rows: RightsizingRow[];
4104
4087
  }
4105
4088
 
@@ -4127,9 +4110,12 @@ export interface RightsizingScanResponse {
4127
4110
  window: string;
4128
4111
  source: "radar";
4129
4112
  coverage: RightsizingScanCoverage;
4130
- workloads: RightsizingScanWorkload[];
4113
+ /** Older spokes return null when a scan loses its Prometheus connection. */
4114
+ workloads: RightsizingScanWorkload[] | null;
4131
4115
  warnings?: { code: string; message: string }[];
4132
4116
  reason?: string;
4117
+ /** Absent from older Radar. A withheld scope means no workload was measured. */
4118
+ clusterScope?: ClusterScope;
4133
4119
  }
4134
4120
 
4135
4121
  // Poll quickly while a discovery run is in flight so the flip to connected
@@ -4411,9 +4397,10 @@ export function usePrometheusRightsizing(
4411
4397
  enabled = true,
4412
4398
  ) {
4413
4399
  return useQuery<PrometheusRightsizing>({
4414
- queryKey: ["prometheus-rightsizing", kind, namespace, name],
4415
- queryFn: () =>
4416
- fetchJSON(`/prometheus/rightsizing/${kind}/${namespace}/${name}`),
4400
+ queryKey: ["prometheus-rightsizing", getApiBase(), kind, namespace, name],
4401
+ queryFn: ({ signal }) =>
4402
+ fetchJSON(`/prometheus/rightsizing/${kind}/${namespace}/${name}`, signal),
4403
+ retry: (count, error) => !isForbiddenError(error) && count < 1,
4417
4404
  enabled: enabled && Boolean(kind && namespace && name),
4418
4405
  staleTime: 5 * 60 * 1000,
4419
4406
  refetchInterval: 10 * 60 * 1000,
@@ -4511,6 +4498,8 @@ export interface PrometheusHPAMetrics {
4511
4498
  range: string;
4512
4499
  current: PrometheusQueryResult;
4513
4500
  desired: PrometheusQueryResult;
4501
+ clusterScope?: ClusterScope;
4502
+ partial?: boolean;
4514
4503
  }
4515
4504
 
4516
4505
  export function usePrometheusHPAMetrics(
@@ -5375,15 +5364,23 @@ export function useTriggerCronJob() {
5375
5364
  mutationFn: async ({
5376
5365
  namespace,
5377
5366
  name,
5367
+ jobName,
5378
5368
  }: {
5379
5369
  namespace: string;
5380
5370
  name: string;
5371
+ // Only for a Radar advertising cronJobTriggerJobName; an older one
5372
+ // ignores the body and names the Job itself.
5373
+ jobName?: string;
5381
5374
  }) => {
5382
5375
  const response = await apiFetch(
5383
5376
  `${getApiBase()}/cronjobs/${namespace}/${name}/trigger`,
5384
- {
5385
- method: "POST",
5386
- },
5377
+ jobName
5378
+ ? {
5379
+ method: "POST",
5380
+ headers: { "Content-Type": "application/json" },
5381
+ body: JSON.stringify({ jobName }),
5382
+ }
5383
+ : { method: "POST" },
5387
5384
  );
5388
5385
  if (!response.ok) {
5389
5386
  const error = await readErrorBody(response);
@@ -6754,12 +6751,9 @@ function streamHelmProgress(
6754
6751
  onProgress: (event: InstallProgressEvent) => void,
6755
6752
  failureLabel: string,
6756
6753
  ): Promise<InstallProgressEvent> {
6757
- const headers = new Headers(options.headers);
6758
- for (const [k, v] of Object.entries(getAuthHeaders())) {
6759
- if (!headers.has(k)) headers.set(k, v);
6760
- }
6761
6754
  return new Promise((resolve, reject) => {
6762
- fetch(url, { credentials: getCredentialsMode(), ...options, headers })
6755
+ // apiFetch adds the auth headers and the tab's connection.
6756
+ apiFetch(url, options)
6763
6757
  .then(async (response) => {
6764
6758
  if (!response.ok) {
6765
6759
  const error = await readErrorBody(response);
@@ -7680,9 +7674,6 @@ export async function fetchSessionCounts(): Promise<SessionCounts> {
7680
7674
  return fetchJSON("/sessions");
7681
7675
  }
7682
7676
 
7683
- // Context switch timeout in milliseconds (should be longer than backend timeout)
7684
- const CONTEXT_SWITCH_TIMEOUT = 45000; // 45 seconds
7685
-
7686
7677
  // Switch to a different context
7687
7678
  // A refused context switch. errorType is set when the server checked the new
7688
7679
  // cluster before leaving the current one and it didn't answer; older Radar
@@ -7700,50 +7691,52 @@ export class SwitchContextError extends Error {
7700
7691
  export function useSwitchContext() {
7701
7692
  const queryClient = useQueryClient();
7702
7693
 
7703
- return useMutation<ClusterInfo, Error, { name: string }>({
7694
+ return useMutation<ContextSwitchOperation | null, Error, { name: string }>({
7704
7695
  mutationFn: async ({ name }) => {
7705
- const controller = new AbortController();
7706
- const timeoutId = setTimeout(
7707
- () => controller.abort(),
7708
- CONTEXT_SWITCH_TIMEOUT,
7709
- );
7710
-
7696
+ const base = getApiBase();
7697
+ const path = apiUrl(`/contexts/${encodeURIComponent(name)}?track=1`, base);
7698
+ const previous = queryClient.getQueryData<{ contextSwitch?: ContextSwitchOperation }>(["connection-status"]);
7711
7699
  try {
7712
- const response = await apiFetch(
7713
- `${getApiBase()}/contexts/${encodeURIComponent(name)}`,
7714
- {
7715
- method: "POST",
7716
- signal: controller.signal,
7717
- },
7718
- );
7719
- clearTimeout(timeoutId);
7720
-
7700
+ // This deadline bounds the acknowledgement, not the accepted operation.
7701
+ const response = await apiFetch(path, { method: "POST", signal: AbortSignal.timeout(45_000) });
7721
7702
  if (!response.ok) {
7722
7703
  const error = await readErrorBody(response);
7723
- throw new SwitchContextError(
7724
- error.error || `HTTP ${response.status}`,
7725
- typeof error.errorType === "string" ? error.errorType : undefined,
7726
- );
7704
+ throw new SwitchContextError(error.error || `HTTP ${response.status}`, typeof error.errorType === "string" ? error.errorType : undefined);
7727
7705
  }
7728
- return response.json();
7706
+ // Cloud-managed and older servers finish the switch before returning 200.
7707
+ return response.status === 202 ? await response.json() as ContextSwitchOperation : null;
7729
7708
  } catch (error) {
7730
- clearTimeout(timeoutId);
7731
- if (error instanceof Error && error.name === "AbortError") {
7732
- throw new Error(
7733
- "Context switch timed out. The cluster may be unreachable.",
7734
- {
7735
- cause: error,
7736
- },
7737
- );
7709
+ if (error instanceof SwitchContextError) throw error;
7710
+ // Either the headers or the body can be lost after the server starts.
7711
+ const status = await apiFetch(apiUrl("/connection?contexts=0", base), { signal: AbortSignal.timeout(10_000) }).catch(() => undefined);
7712
+ if (status?.ok) {
7713
+ const { contextSwitch } = await status.json() as { contextSwitch?: ContextSwitchOperation };
7714
+ if (contextSwitch?.target === name && (switchInProgress(contextSwitch) || (previous && contextSwitch.id !== previous.contextSwitch?.id))) {
7715
+ return contextSwitch;
7716
+ }
7717
+ }
7718
+ if (error instanceof Error && error.name === "TimeoutError") {
7719
+ throw new Error("Radar did not acknowledge the switch. Check the connection status before trying again.", { cause: error });
7738
7720
  }
7739
7721
  throw error;
7740
7722
  }
7741
7723
  },
7742
- onSuccess: () => {
7743
- // Clear all query cache to ensure fresh data from new context
7744
- // Using removeQueries + invalidateQueries ensures no stale data is served
7745
- queryClient.removeQueries();
7746
- queryClient.invalidateQueries();
7724
+ onSuccess: async (operation) => {
7725
+ if (operation) {
7726
+ // A late acknowledgement of a switch this tab already showed the outcome
7727
+ // of carries an older snapshot; seeding it would reopen the overlay.
7728
+ if (switchFinished(operation.id)) return;
7729
+ followSwitch(operation.id);
7730
+ await queryClient.cancelQueries({ queryKey: ["connection-status"] });
7731
+ if (switchInProgress(operation)) {
7732
+ queryClient.setQueryData(["connection-status"], (existing: { contextSwitch?: ContextSwitchOperation } | undefined) =>
7733
+ existing ? { ...existing, contextSwitch: operation } : existing);
7734
+ }
7735
+ void queryClient.invalidateQueries({ queryKey: ["connection-status"] });
7736
+ } else {
7737
+ queryClient.removeQueries();
7738
+ void queryClient.invalidateQueries();
7739
+ }
7747
7740
  },
7748
7741
  onError: () => {
7749
7742
  // Invalidate contexts so the dropdown checkmark reflects the backend's
@@ -7797,6 +7790,8 @@ export interface NamespaceScope {
7797
7790
  * its short fallback list. Absent from older servers.
7798
7791
  */
7799
7792
  listFailed?: boolean;
7793
+ /** Where Radar collects the kinds it keeps in only some namespaces; absent when none, or from an older Radar. */
7794
+ collection?: NamespaceCollection;
7800
7795
  }
7801
7796
 
7802
7797
  /**
@@ -8474,6 +8469,7 @@ export interface DiagnosticsSnapshot {
8474
8469
  clusterName?: string;
8475
8470
  error?: string;
8476
8471
  errorType?: string;
8472
+ progressMessage?: string;
8477
8473
  };
8478
8474
  kubeconfig?: {
8479
8475
  mode: "" | "in-cluster" | "single" | "multi-env" | "multi-dir" | "multi-source";
@@ -8483,11 +8479,12 @@ export interface DiagnosticsSnapshot {
8483
8479
  enrichedFromShell: boolean;
8484
8480
  kubeconfigEnvIgnored: boolean;
8485
8481
  kubeconfigEnvIgnoredReason: string;
8486
- currentContextUsesExec: boolean;
8482
+ currentContextUsesExec?: boolean;
8487
8483
  execPluginsPresent?: string[];
8488
8484
  execPluginsMissing?: string[];
8489
8485
  };
8490
8486
  cluster?: {
8487
+ observedAt?: string;
8491
8488
  platform: string;
8492
8489
  kubernetesVersion: string;
8493
8490
  nodeCount: number;
@@ -8525,7 +8522,7 @@ export interface DiagnosticsSnapshot {
8525
8522
  };
8526
8523
  informers?: {
8527
8524
  typedCount: number;
8528
- dynamicCount: number;
8525
+ dynamicCount?: number;
8529
8526
  watchedCRDs: string[];
8530
8527
  syncStatus?: DiagCacheSyncStatus;
8531
8528
  };
@@ -8597,7 +8594,30 @@ export interface DiagnosticsSnapshot {
8597
8594
  export function useDiagnostics(enabled: boolean) {
8598
8595
  return useQuery<DiagnosticsSnapshot>({
8599
8596
  queryKey: ["diagnostics"],
8600
- queryFn: enabled ? () => fetchJSON("/diagnostics") : skipToken,
8597
+ queryFn: enabled
8598
+ ? async ({ signal }) => {
8599
+ const request = new AbortController();
8600
+ const cancel = () => request.abort();
8601
+ signal.addEventListener("abort", cancel, { once: true });
8602
+ if (signal.aborted) cancel();
8603
+ const timeout = setTimeout(cancel, 15000);
8604
+ try {
8605
+ return await fetchJSON<DiagnosticsSnapshot>("/diagnostics", request.signal);
8606
+ } catch (error) {
8607
+ if (request.signal.aborted && !signal.aborted) {
8608
+ throw new Error("Radar did not return diagnostics within 15 seconds.", { cause: error });
8609
+ }
8610
+ if (signal.aborted) throw error;
8611
+ const message = error instanceof Error ? error.message : String(error);
8612
+ throw new Error(`Could not load diagnostics. ${message}`, { cause: error });
8613
+ } finally {
8614
+ clearTimeout(timeout);
8615
+ signal.removeEventListener("abort", cancel);
8616
+ }
8617
+ }
8618
+ : skipToken,
8619
+ retry: false,
8620
+ networkMode: "always",
8601
8621
  staleTime: 0,
8602
8622
  gcTime: 0,
8603
8623
  });
@@ -0,0 +1,82 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { afterEach, expect, it, vi } from 'vitest'
6
+ import { apiFetch, rollbackWithProgress, useRestartWorkload } from './client'
7
+ import { getApiBase } from './config'
8
+ import { connectionHeaderValue, observeConnectionStatus, resetConnectionBindingForTest, withConnectionParam } from './connectionBinding'
9
+
10
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
11
+ afterEach(() => {
12
+ resetConnectionBindingForTest()
13
+ vi.unstubAllGlobals()
14
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
15
+ })
16
+
17
+ function recordHeaders(status = 200, body = '{}') {
18
+ const seen: (string | null)[] = []
19
+ vi.stubGlobal('fetch', vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
20
+ seen.push(new Headers(init?.headers).get('X-Radar-Connection'))
21
+ return new Response(body, { status, headers: { 'Content-Type': 'application/json' } })
22
+ }))
23
+ return seen
24
+ }
25
+
26
+ it('follows the latest connection a status names, and keeps it while a switch has none', () => {
27
+ const base = getApiBase()
28
+ expect(connectionHeaderValue(base)).toBeUndefined()
29
+ observeConnectionStatus({ connectionId: 'n-1' }, base)
30
+ observeConnectionStatus({ connectionId: '' }, base) // mid-switch: nothing serving
31
+ expect(connectionHeaderValue(base)).toBe('n-1')
32
+ observeConnectionStatus({ connectionId: 'n-2' }, base)
33
+ expect(connectionHeaderValue(base)).toBe('n-2')
34
+ // Another API base (Radar Hub) keeps its own.
35
+ expect(connectionHeaderValue('/other/api')).toBeUndefined()
36
+ })
37
+
38
+ it('names the connection on requests only once the server published one', async () => {
39
+ const seen = recordHeaders()
40
+ await apiFetch(`${getApiBase()}/connection`)
41
+ observeConnectionStatus({ connectionId: 'n-1' })
42
+ await apiFetch(`${getApiBase()}/workloads/deployments/default/web/restart`, { method: 'POST' })
43
+ expect(seen).toEqual([null, 'n-1'])
44
+ })
45
+
46
+ it("shows the server's refusal when a restart names a connection it no longer serves", async () => {
47
+ observeConnectionStatus({ connectionId: 'n-1' })
48
+ const message = 'Nothing was changed: the cluster changed since this view loaded. Check the current cluster and try again.'
49
+ const seen = recordHeaders(409, JSON.stringify({ error: message, code: 'context_changed', error_code: 'context_changed' }))
50
+ const client = new QueryClient()
51
+ let restart: ReturnType<typeof useRestartWorkload> | undefined
52
+ function Probe() {
53
+ restart = useRestartWorkload()
54
+ return null
55
+ }
56
+ const root = createRoot(document.createElement('div'))
57
+ await act(async () => {
58
+ root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>)
59
+ })
60
+ let error: unknown
61
+ await act(async () => {
62
+ await restart!.mutateAsync({ kind: 'deployments', namespace: 'default', name: 'web' }).catch((e) => { error = e })
63
+ })
64
+ expect(seen).toEqual(['n-1'])
65
+ expect((error as Error).message).toBe(message)
66
+ act(() => root.unmount())
67
+ })
68
+
69
+ it('names the connection on a WebSocket URL, which cannot carry headers', () => {
70
+ expect(withConnectionParam('ws://h/api/pods/ns/p/exec?container=app')).toBe('ws://h/api/pods/ns/p/exec?container=app')
71
+ observeConnectionStatus({ connectionId: 'n 1' })
72
+ expect(withConnectionParam('ws://h/api/pods/ns/p/exec?container=app')).toBe('ws://h/api/pods/ns/p/exec?container=app&connection=n%201')
73
+ expect(withConnectionParam('ws://h/api/x')).toBe('ws://h/api/x?connection=n%201')
74
+ })
75
+
76
+ it('names the connection on streamed Helm actions', async () => {
77
+ observeConnectionStatus({ connectionId: 'n-1' })
78
+ const seen = recordHeaders(200, 'event: complete\ndata: {"type":"complete"}\n\n')
79
+ await rollbackWithProgress('default', 'web', 2, () => {}).catch(() => {})
80
+ expect(seen).toEqual(['n-1'])
81
+ })
82
+
@@ -0,0 +1,52 @@
1
+ import { useState } from 'react'
2
+ import { getApiBase } from './config'
3
+
4
+ // Which cluster connection this tab is on, per API base.
5
+ //
6
+ // A Radar serving from a kubeconfig gives each connection an ID when it starts
7
+ // serving a cluster (unique across switches and restarts) and publishes it
8
+ // with the connection status. The tab keeps the latest ID it heard and sends
9
+ // it with every request; the server refuses a write naming a connection that
10
+ // is no longer serving. When the cluster changes, the tab's views reset on the
11
+ // context change itself (context_changed, or a status poll showing another
12
+ // context), so the ID only has to follow the latest status.
13
+
14
+ export const CONNECTION_HEADER = 'X-Radar-Connection'
15
+
16
+ const ids = new Map<string, string>()
17
+
18
+ /** Record the connection named by a status the tab received (poll, SSE frame, retry result). */
19
+ export function observeConnectionStatus(status: { connectionId?: string }, base = getApiBase()): void {
20
+ if (status.connectionId) ids.set(base, status.connectionId)
21
+ }
22
+
23
+ /** The connection ID to send, or undefined when the server publishes none. */
24
+ export function connectionHeaderValue(base = getApiBase()): string | undefined {
25
+ return ids.get(base)
26
+ }
27
+
28
+ /** A WebSocket URL naming a connection (a browser can't set headers on one); by default this tab's latest. */
29
+ export function withConnectionParam(url: string, id = connectionHeaderValue()): string {
30
+ if (!id) return url
31
+ return `${url}${url.includes('?') ? '&' : '?'}connection=${encodeURIComponent(id)}`
32
+ }
33
+
34
+ /** Headers naming a connection, for a request that must not follow the tab's latest one. */
35
+ export function connectionHeaders(id: string | undefined): Record<string, string> {
36
+ return id ? { [CONNECTION_HEADER]: id } : {}
37
+ }
38
+
39
+ /**
40
+ * The connection a component opened on, kept for its lifetime. A dock tab
41
+ * outlives a switch, so its reconnects and actions name the cluster it was
42
+ * opened on and are refused once that connection retires.
43
+ */
44
+ export function useOpenedConnection(): string | undefined {
45
+ const [id] = useState(() => connectionHeaderValue())
46
+ return id
47
+ }
48
+
49
+ /** Test hook: forget everything. */
50
+ export function resetConnectionBindingForTest(): void {
51
+ ids.clear()
52
+ }
@@ -0,0 +1,11 @@
1
+ import { expect, it } from 'vitest'
2
+ import { finishSwitch, switchFinished } from './contextSwitch'
3
+
4
+ it('remembers every switch whose outcome the tab presented, not just the last', () => {
5
+ finishSwitch('switch-a')
6
+ finishSwitch('switch-b')
7
+ expect(switchFinished('switch-a')).toBe(true)
8
+ expect(switchFinished('switch-b')).toBe(true)
9
+ expect(switchFinished('switch-c')).toBe(false)
10
+ expect(switchFinished('')).toBe(false)
11
+ })