@skyhook-io/radar-app 1.20.1 → 1.21.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 (215) hide show
  1. package/package.json +10 -9
  2. package/src/App.tsx +65 -16
  3. package/src/api/client.audit-gating.test.tsx +105 -5
  4. package/src/api/client.auditBadgesSync.test.tsx +118 -0
  5. package/src/api/client.capabilitiesPoll.test.ts +61 -0
  6. package/src/api/client.namespaceSwitch.hook.test.tsx +170 -1
  7. package/src/api/client.pauseDeployment.test.tsx +77 -0
  8. package/src/api/client.restartError.test.ts +14 -0
  9. package/src/api/client.revisionRefresh.test.tsx +44 -0
  10. package/src/api/client.rollbackError.test.ts +14 -0
  11. package/src/api/client.ts +347 -16
  12. package/src/api/namespaceScopeRetry.test.ts +14 -0
  13. package/src/api/networkAttachments.test.tsx +120 -0
  14. package/src/api/networkAttachments.ts +30 -0
  15. package/src/api/radarFeatures.test.ts +5 -0
  16. package/src/api/radarFeatures.ts +10 -0
  17. package/src/api/secretsStore.test.ts +33 -0
  18. package/src/api/secretsStore.ts +37 -0
  19. package/src/api/substrateHealth.ts +134 -0
  20. package/src/api/velero.test.ts +60 -0
  21. package/src/api/velero.ts +201 -0
  22. package/src/api/vulnerabilities.ts +255 -0
  23. package/src/components/ConnectionErrorView.test.tsx +11 -0
  24. package/src/components/ConnectionErrorView.tsx +19 -0
  25. package/src/components/ContextSwitcher.tsx +9 -2
  26. package/src/components/NamespaceSwitcher.tsx +3 -1
  27. package/src/components/applications/ApplicationsView.openResource.test.tsx +118 -0
  28. package/src/components/applications/ApplicationsView.tsx +8 -11
  29. package/src/components/audit/AuditView.tsx +4 -0
  30. package/src/components/audit/ChecksViewTabs.test.tsx +33 -5
  31. package/src/components/audit/ChecksViewTabs.tsx +11 -1
  32. package/src/components/audit/UpgradeReadinessView.test.ts +35 -1
  33. package/src/components/audit/UpgradeReadinessView.tsx +60 -2
  34. package/src/components/audit/VulnerabilitiesView.tsx +907 -0
  35. package/src/components/cnpg/CNPGClusterTabs.tsx +3 -1
  36. package/src/components/cnpg/CNPGDrawerTrail.tsx +5 -26
  37. package/src/components/cnpg/CNPGInvestigationAction.test.tsx +27 -6
  38. package/src/components/cnpg/CNPGView.tsx +43 -117
  39. package/src/components/cnpg/CNPGWorkspace.compatibility.test.tsx +30 -0
  40. package/src/components/cnpg/host.tsx +2 -2
  41. package/src/components/cnpg/routes.ts +3 -1
  42. package/src/components/cnpg/shared.tsx +5 -53
  43. package/src/components/cnpg/useCNPGNavigate.ts +1 -21
  44. package/src/components/cnpg/useCNPGSidebarWorkspace.ts +16 -13
  45. package/src/components/community.tsx +42 -0
  46. package/src/components/cost/CostView.tsx +27 -9
  47. package/src/components/diagnose/InvestigationView.tsx +12 -3
  48. package/src/components/diagnose/diagnoseEvidenceTypes.ts +2 -0
  49. package/src/components/diagnose/investigationEvidence/adapters/helm.test.tsx +52 -0
  50. package/src/components/diagnose/investigationEvidence/adapters/helm.ts +10 -0
  51. package/src/components/diagnose/investigationEvidence/bodies/platform.tsx +82 -51
  52. package/src/components/diagnose/investigationEvidence/types.ts +5 -0
  53. package/src/components/diagnose/investigationMetrics.test.ts +20 -0
  54. package/src/components/diagnose/investigationMetrics.ts +2 -1
  55. package/src/components/dock/BottomDock.tsx +1 -0
  56. package/src/components/dock/LogsTab.tsx +3 -0
  57. package/src/components/dock/TerminalPreferences.query.test.tsx +57 -0
  58. package/src/components/dock/TerminalPreferences.test.tsx +68 -0
  59. package/src/components/dock/TerminalPreferences.tsx +73 -0
  60. package/src/components/gitops/GitOpsView.tsx +2 -10
  61. package/src/components/helm/HelmDrawerFrame.tsx +1 -1
  62. package/src/components/helm/HelmReleaseDrawer.tsx +24 -12
  63. package/src/components/helm/HelmView.tsx +25 -19
  64. package/src/components/helm/NotCheckedBadge.test.tsx +62 -0
  65. package/src/components/helm/NotCheckedBadge.tsx +39 -0
  66. package/src/components/helm/OwnedResources.test.tsx +86 -0
  67. package/src/components/helm/OwnedResources.tsx +69 -11
  68. package/src/components/home/ClusterHealthCard.heading.test.tsx +72 -0
  69. package/src/components/home/ClusterHealthCard.test.ts +44 -1
  70. package/src/components/home/ClusterHealthCard.tsx +25 -11
  71. package/src/components/home/HelmSummary.tsx +15 -15
  72. package/src/components/home/HomeAgentBlock.tsx +3 -0
  73. package/src/components/home/HomeView.tsx +7 -0
  74. package/src/components/home/MCPSetupDialog.test.tsx +19 -12
  75. package/src/components/home/MCPSetupDialog.tsx +4 -2
  76. package/src/components/home/mcpToolCatalog.ts +17 -4
  77. package/src/components/home/useVulnerabilitiesRow.test.ts +26 -0
  78. package/src/components/home/useVulnerabilitiesRow.ts +50 -0
  79. package/src/components/logs/LogsViewer.tsx +3 -1
  80. package/src/components/logs/MultiPodLogsTab.test.tsx +24 -4
  81. package/src/components/logs/MultiPodLogsTab.tsx +9 -5
  82. package/src/components/nav/PrimaryNavRail.test.tsx +17 -0
  83. package/src/components/nav/PrimaryNavRail.tsx +174 -29
  84. package/src/components/resource/PrometheusChartsGrid.tsx +5 -1
  85. package/src/components/resource/RightsizingStrip.test.ts +57 -0
  86. package/src/components/resource/RightsizingStrip.tsx +53 -4
  87. package/src/components/resource/SubstrateHealthCharts.test.tsx +143 -0
  88. package/src/components/resource/SubstrateHealthCharts.tsx +254 -0
  89. package/src/components/resource/SubstrateVerdictLine.test.tsx +131 -0
  90. package/src/components/resource/SubstrateVerdictLine.tsx +180 -0
  91. package/src/components/resources/ImageFilesystemModal.test.tsx +74 -6
  92. package/src/components/resources/ImageFilesystemModal.tsx +98 -6
  93. package/src/components/resources/PodFileUploadPanel.tsx +150 -0
  94. package/src/components/resources/PodFilesystemModal.tsx +246 -3
  95. package/src/components/resources/ResourcesView.tsx +12 -6
  96. package/src/components/resources/pod-file-upload.test.tsx +223 -0
  97. package/src/components/resources/pod-file-upload.ts +266 -0
  98. package/src/components/resources/renderers/HTTPRouteRenderer.test.tsx +50 -0
  99. package/src/components/resources/renderers/HTTPRouteRenderer.tsx +27 -0
  100. package/src/components/resources/renderers/PodRenderer.tsx +26 -1
  101. package/src/components/resources/renderers/SecretProviderClassRenderer.tsx +25 -0
  102. package/src/components/resources/renderers/UpgradePlanRenderer.test.tsx +20 -0
  103. package/src/components/resources/renderers/UpgradePlanRenderer.tsx +22 -0
  104. package/src/components/resources/renderers/VeleroBackupRenderer.tsx +16 -36
  105. package/src/components/resources/renderers/VeleroRestoreRenderer.tsx +6 -19
  106. package/src/components/resources/renderers/WorkloadRenderer.tsx +8 -0
  107. package/src/components/rightsizing/RightsizingScanView.tsx +19 -3
  108. package/src/components/rightsizing/model.test.ts +11 -0
  109. package/src/components/rightsizing/model.ts +3 -1
  110. package/src/components/rightsizing/presentation.test.ts +46 -0
  111. package/src/components/rightsizing/presentation.ts +17 -2
  112. package/src/components/shared/LargeClusterNamespacePicker.test.tsx +27 -0
  113. package/src/components/shared/LargeClusterNamespacePicker.tsx +8 -2
  114. package/src/components/timeline/TimelineView.tsx +3 -1
  115. package/src/components/traffic/TrafficConnectionsTable.test.tsx +94 -0
  116. package/src/components/traffic/TrafficConnectionsTable.tsx +21 -5
  117. package/src/components/traffic/TrafficData.test.tsx +37 -0
  118. package/src/components/traffic/TrafficData.tsx +27 -0
  119. package/src/components/traffic/TrafficFlowList.tsx +9 -7
  120. package/src/components/traffic/TrafficGraph.layoutEngine.test.tsx +193 -0
  121. package/src/components/traffic/TrafficGraph.test.tsx +269 -0
  122. package/src/components/traffic/TrafficGraph.tsx +135 -64
  123. package/src/components/traffic/TrafficGraphUnavailable.tsx +57 -0
  124. package/src/components/traffic/TrafficView.layoutUnavailable.test.tsx +211 -0
  125. package/src/components/traffic/TrafficView.tsx +72 -155
  126. package/src/components/traffic/trafficFilters.test.ts +189 -1
  127. package/src/components/traffic/trafficFilters.ts +169 -1
  128. package/src/components/ui/DiagnosticsOverlay.tsx +14 -1
  129. package/src/components/ui/Omnibar.tsx +4 -1
  130. package/src/components/ui/RadarOmnibar.test.tsx +55 -2
  131. package/src/components/ui/RadarOmnibar.tsx +7 -1
  132. package/src/components/ui/SearchSyntaxHelp.test.tsx +9 -2
  133. package/src/components/ui/SearchSyntaxHelp.tsx +3 -2
  134. package/src/components/ui/UpdateNotification.manual.test.tsx +5 -2
  135. package/src/components/ui/UpdateNotification.test.tsx +54 -3
  136. package/src/components/ui/UpdateNotification.tsx +60 -19
  137. package/src/components/ui/command-items.ts +24 -1
  138. package/src/components/ui/omnibar-match.test.ts +7 -0
  139. package/src/components/ui/omnibar-match.ts +1 -0
  140. package/src/components/ui/searchCoverageNote.test.ts +17 -0
  141. package/src/components/ui/searchCoverageNote.ts +31 -7
  142. package/src/components/useContextSwitchFlow.tsx +9 -1
  143. package/src/components/velero/VeleroBackupNow.test.tsx +165 -0
  144. package/src/components/velero/VeleroBackupNow.tsx +143 -0
  145. package/src/components/velero/VeleroDeleteBackup.test.tsx +364 -0
  146. package/src/components/velero/VeleroDeleteBackup.tsx +306 -0
  147. package/src/components/velero/VeleroDetailPage.tsx +148 -0
  148. package/src/components/velero/VeleroKindLists.test.tsx +48 -0
  149. package/src/components/velero/VeleroKindLists.tsx +43 -0
  150. package/src/components/velero/VeleroLocations.expand.test.tsx +27 -0
  151. package/src/components/velero/VeleroLocations.test.tsx +86 -0
  152. package/src/components/velero/VeleroLocations.tsx +240 -0
  153. package/src/components/velero/VeleroOverview.test.tsx +311 -0
  154. package/src/components/velero/VeleroOverview.tsx +485 -0
  155. package/src/components/velero/VeleroPages.test.tsx +516 -0
  156. package/src/components/velero/VeleroPages.tsx +1056 -0
  157. package/src/components/velero/VeleroRunLists.tsx +309 -0
  158. package/src/components/velero/VeleroRunMessagesHost.test.tsx +25 -0
  159. package/src/components/velero/VeleroRunMessagesHost.tsx +54 -0
  160. package/src/components/velero/VeleroScheduleStatusBadge.test.tsx +28 -0
  161. package/src/components/velero/VeleroScheduleStatusBadge.tsx +21 -0
  162. package/src/components/velero/VeleroSchedules.tsx +255 -0
  163. package/src/components/velero/VeleroView.tsx +59 -0
  164. package/src/components/velero/VeleroWorkspace.gate.test.tsx +97 -0
  165. package/src/components/velero/attention.test.ts +178 -0
  166. package/src/components/velero/attention.ts +281 -0
  167. package/src/components/velero/backupDelete.test.tsx +91 -0
  168. package/src/components/velero/backupDelete.tsx +182 -0
  169. package/src/components/velero/coverage.test.ts +87 -0
  170. package/src/components/velero/coverage.ts +150 -0
  171. package/src/components/velero/host.tsx +86 -0
  172. package/src/components/velero/routes.ts +78 -0
  173. package/src/components/velero/runs.tsx +121 -0
  174. package/src/components/velero/shared.test.ts +84 -0
  175. package/src/components/velero/shared.tsx +423 -0
  176. package/src/components/velero/useVeleroSidebarWorkspace.test.tsx +28 -0
  177. package/src/components/velero/useVeleroSidebarWorkspace.ts +71 -0
  178. package/src/components/velero/velero.fixtures.ts +61 -0
  179. package/src/components/velero/workspaceRoute.ts +21 -0
  180. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.tsx +167 -0
  181. package/src/components/vulnerabilities/parts.test.ts +72 -0
  182. package/src/components/vulnerabilities/parts.tsx +291 -0
  183. package/src/components/workload/NodeCertificateEvidence.test.tsx +51 -0
  184. package/src/components/workload/NodeCertificateEvidence.tsx +44 -0
  185. package/src/components/workload/WorkloadView.tsx +114 -37
  186. package/src/components/workspace/DrawerTrailBack.tsx +32 -0
  187. package/src/components/workspace/WorkspaceFrame.tsx +71 -0
  188. package/src/components/workspace/coverage.ts +61 -0
  189. package/src/components/workspace/layout.test.tsx +29 -1
  190. package/src/components/workspace/layout.tsx +15 -5
  191. package/src/components/workspace/sidebar.ts +9 -0
  192. package/src/components/workspace/useWorkspaceDrawer.ts +63 -0
  193. package/src/components/workspace/useWorkspaceNavigate.ts +21 -0
  194. package/src/context/ConnectionContext.test.ts +1 -0
  195. package/src/context/ConnectionContext.tsx +2 -2
  196. package/src/desktop/AboutDialog.test.ts +12 -0
  197. package/src/desktop/AboutDialog.tsx +151 -0
  198. package/src/desktop/WindowsTitleBar.tsx +359 -0
  199. package/src/desktop/titleBar.test.ts +61 -0
  200. package/src/desktop/titleBar.ts +45 -0
  201. package/src/index.css +19 -0
  202. package/src/integrations/resourceHost.ts +5 -1
  203. package/src/integrations/resourceHosts.test.tsx +15 -3
  204. package/src/integrations/resourceHosts.tsx +26 -6
  205. package/src/integrations/workspaceRoute.ts +1 -1
  206. package/src/integrations/workspaceRoutes.test.ts +11 -0
  207. package/src/integrations/workspaceRoutes.ts +3 -1
  208. package/src/integrations/workspaceScreens.tsx +2 -0
  209. package/src/main.tsx +8 -0
  210. package/src/utils/desktop-zoom.test.ts +53 -0
  211. package/src/utils/desktop-zoom.ts +30 -0
  212. package/src/utils/namespacePick.test.ts +87 -0
  213. package/src/utils/namespacePick.ts +88 -0
  214. package/src/utils/staleAssetPrompt.test.tsx +76 -0
  215. package/src/utils/staleAssetPrompt.tsx +32 -0
@@ -213,10 +213,10 @@ function FitCard({ row, window }: { row: RightsizingRow; window: string }) {
213
213
  <div className="flex items-baseline gap-2 tabular-nums">
214
214
  <div>
215
215
  <div className="text-[10px] uppercase tracking-wide text-theme-text-quaternary">
216
- Current request
216
+ {row.podLevelRequest ? 'Pod-level request' : 'Current request'}
217
217
  </div>
218
218
  <div className="text-lg font-semibold text-theme-text-primary">
219
- {row.currentRequest ?? 'Unset'}
219
+ {row.podLevelRequest ?? row.currentRequest ?? 'Unset'}
220
220
  </div>
221
221
  </div>
222
222
  <ArrowRight className="h-4 w-4 text-theme-text-quaternary" />
@@ -247,7 +247,9 @@ function CompactFitRow({ row }: { row: RightsizingRow }) {
247
247
  <span className="w-12 text-[10px] uppercase tracking-wide text-theme-text-quaternary">
248
248
  {row.resource}
249
249
  </span>
250
- <span className="min-w-14 text-theme-text-secondary">{row.currentRequest ?? 'unset'}</span>
250
+ <span className="min-w-14 text-theme-text-secondary">
251
+ {row.podLevelRequest ? `pod ${row.podLevelRequest}` : (row.currentRequest ?? 'unset')}
252
+ </span>
251
253
  {row.recommendedRequest && (
252
254
  <>
253
255
  <ArrowRight className="h-3 w-3 text-theme-text-quaternary" />
@@ -298,6 +300,7 @@ export function getRightsizingPresentation(fit: RightsizingFit, queryError?: str
298
300
  under_requested: 'Under-requested',
299
301
  missing_request: 'Missing request',
300
302
  insufficient_history: 'Insufficient history',
303
+ pod_level_request: 'Pod-level request',
301
304
  }
302
305
  const severities: Record<RightsizingFit, 'success' | 'info' | 'warning' | 'neutral'> = {
303
306
  balanced: 'success',
@@ -305,8 +308,10 @@ export function getRightsizingPresentation(fit: RightsizingFit, queryError?: str
305
308
  under_requested: 'warning',
306
309
  missing_request: 'warning',
307
310
  insufficient_history: 'neutral',
311
+ pod_level_request: 'neutral',
308
312
  }
309
- return { label: labels[fit], severity: severities[fit] }
313
+ // An older frontend can meet a fit added by a newer agent.
314
+ return { label: labels[fit] ?? fit, severity: severities[fit] ?? ('neutral' as const) }
310
315
  }
311
316
 
312
317
  function FitExplanation({ row }: { row: RightsizingRow }) {
@@ -327,6 +332,8 @@ export function getRightsizingExplanation(row: RightsizingRow): string | undefin
327
332
  'Radar could not verify recent OOM history, so it withheld a lower memory request.',
328
333
  recommended_request_exceeds_limit:
329
334
  'The evidence-based request would exceed the current limit; review the limit first.',
335
+ requests_exceed_pod_limit:
336
+ "Together with the other containers' requests and suggested increases, this request would take the pod above its pod-level limit (spec.resources), which Kubernetes rejects. Decide how to split the limit between containers, or raise the pod limit.",
330
337
  }
331
338
  // A denied pod read leaves currentPodOOM unknown rather than false, so it
332
339
  // qualifies whatever else is said instead of replacing it — including a
@@ -336,6 +343,8 @@ export function getRightsizingExplanation(row: RightsizingRow): string | undefin
336
343
  ? "Radar could not read this workload's pods, so it could not check them for out-of-memory restarts."
337
344
  : undefined
338
345
  const qualified = (base: string) => (inventoryNote ? `${base} ${inventoryNote}` : base)
346
+ if (row.fit === 'pod_level_request' && row.podLevelRequest && !row.queryError)
347
+ return qualified(podLevelRequestExplanation(row, row.podLevelRequest))
339
348
  if (row.reductionLimited && row.calculatedRequest && row.recommendedRequest) {
340
349
  const burstNote = row.bursty && row.peak ? ` CPU P99 reached ${row.peak.formatted}.` : ''
341
350
  return qualified(
@@ -352,6 +361,46 @@ export function getRightsizingExplanation(row: RightsizingRow): string | undefin
352
361
  )
353
362
  }
354
363
 
364
+ function podLevelRequestExplanation(row: RightsizingRow, podLevelRequest: string): string {
365
+ const overUse = podLevelOverUseNote(row)
366
+ if (overUse) return overUse
367
+ const resource = row.resource === 'cpu' ? 'CPU' : 'memory'
368
+ const own = row.currentRequest
369
+ ? ` This container's own request (${row.currentRequest}) no longer decides what is reserved.`
370
+ : ''
371
+ return `This pod sets one ${resource} request for all its containers: ${podLevelRequest} in spec.resources. The scheduler reserves that instead of container requests, so Radar doesn't suggest a request per container; check the pod-level request against the usage of its containers.${own}`
372
+ }
373
+
374
+ /**
375
+ * One container's usage above the pod's whole request is a sound lower bound on
376
+ * the pod's own use. Adding containers up would overstate it, so only this case
377
+ * is called out.
378
+ */
379
+ export function podLevelOverUseNote(row: RightsizingRow): string | undefined {
380
+ if (
381
+ row.fit !== 'pod_level_request' ||
382
+ row.sampleCount < RIGHTSIZING_MIN_SAMPLES ||
383
+ !row.observed ||
384
+ !row.podLevelRequest ||
385
+ row.podLevelRequestValue == null ||
386
+ row.observed.value <= row.podLevelRequestValue
387
+ )
388
+ return undefined
389
+ const resource = row.resource === 'cpu' ? 'CPU' : 'memory'
390
+ const finding = `This container alone used ${row.observed.formatted} (${row.observed.name}), more than the pod's whole ${row.podLevelRequest} ${resource} request. Radar can't size pod-level requests yet.`
391
+ // An HPA scaling on this resource divides usage by the pod request, so
392
+ // raising it changes scaling; Radar never suggests that unreviewed.
393
+ if (row.hpaManaged)
394
+ return `${finding} The HPA scales on this request, so review its target before raising spec.resources.requests.${row.resource}.`
395
+ if (!row.hpaEvidenceAvailable)
396
+ return `${finding} Radar couldn't check for an HPA on this resource, so check autoscaling before raising spec.resources.requests.${row.resource}.`
397
+ return `${finding} Consider raising spec.resources.requests.${row.resource}.`
398
+ }
399
+
400
+ // Mirrors rightsizingMinSamples (six hours of 5-minute samples) in
401
+ // internal/prometheus/rightsizing.go: below it Radar draws no conclusion.
402
+ const RIGHTSIZING_MIN_SAMPLES = 72
403
+
355
404
  function confidenceLabel(row: RightsizingRow) {
356
405
  return `${row.confidence[0].toUpperCase()}${row.confidence.slice(1)} confidence`
357
406
  }
@@ -0,0 +1,143 @@
1
+ import { renderToStaticMarkup } from 'react-dom/server'
2
+ import { describe, expect, it, vi } from 'vitest'
3
+ import type { SubstrateHealth } from '../../api/substrateHealth'
4
+
5
+ let health: { data?: SubstrateHealth; error?: unknown; upgrade?: unknown; blockedReason?: string; support?: string } = {}
6
+ let promStatus: { connected: boolean; discovering?: boolean; error?: string } = { connected: true }
7
+
8
+ vi.mock('../../api/client', async (orig) => ({
9
+ ...(await orig<typeof import('../../api/client')>()),
10
+ useAutoPromConnect: () => {},
11
+ usePrometheusStatus: () => ({ data: promStatus }),
12
+ usePrometheusConnect: () => ({ mutate: () => {}, isPending: false }),
13
+ }))
14
+ vi.mock('../../api/substrateHealth', async (orig) => ({
15
+ ...(await orig<typeof import('../../api/substrateHealth')>()),
16
+ useSubstrateHealth: () => health,
17
+ }))
18
+
19
+ const { SubstrateHealthCharts } = await import('./SubstrateHealthCharts')
20
+ const { ApiError } = await import('../../api/client')
21
+
22
+ const pool = { kind: 'workerpool' as const, namespace: 'agents', name: 'pool' }
23
+ const node = { kind: 'node' as const, name: 'worker-1' }
24
+ const base = { range: '1h', start: 1000, end: 4600, stepSeconds: 60, charts: [] }
25
+ const render = (target: typeof pool | typeof node) => renderToStaticMarkup(<SubstrateHealthCharts target={target} />)
26
+
27
+ function chart(overrides: Partial<SubstrateHealth['charts'][number]>): SubstrateHealth['charts'][number] {
28
+ return {
29
+ id: 'workers', title: 'Workers by state', unit: 'workers', population: 'Every worker Pod.', source: 'ate_workerpool_workers',
30
+ state: 'ok', isolation: { mode: 'unverified', note: 'Radar couldn\'t confirm these series belong to this exact cluster' },
31
+ series: [
32
+ { labels: { series: 'idle (gvisor)' }, dataPoints: [{ timestamp: 4600, value: 1.5 }] },
33
+ { labels: { series: 'partial (gvisor)' }, dataPoints: [{ timestamp: 4600, value: 1.5 }] },
34
+ ],
35
+ ...overrides,
36
+ }
37
+ }
38
+
39
+ describe('SubstrateHealthCharts', () => {
40
+ it('offers to connect Prometheus only where it is the whole tab', () => {
41
+ promStatus = { connected: false }
42
+ health = {}
43
+ expect(render(pool)).toBe('')
44
+ expect(renderToStaticMarkup(<SubstrateHealthCharts target={pool} standalone />)).toContain('Discover Prometheus')
45
+ promStatus = { connected: true }
46
+ })
47
+
48
+ it('says why there are no charts when Radar support could not be checked', () => {
49
+ health = { blockedReason: "Couldn't check this cluster's Radar support. Refresh to try again." }
50
+ expect(render(pool)).toContain('Refresh to try again')
51
+ expect(render(node)).toBe('')
52
+ })
53
+
54
+ it('shows a metrics error even when a capabilities refresh failed after support was known', () => {
55
+ health = { support: 'supported', blockedReason: "Couldn't check this cluster's Radar support. Refresh to try again.", error: new Error('Prometheus timed out') }
56
+ expect(render(pool)).toContain('Prometheus timed out')
57
+ expect(render(pool)).not.toContain('Refresh to try again')
58
+ })
59
+
60
+ it('says what it looked for when a pool has no Substrate series', () => {
61
+ health = { data: { ...base, status: 'notFound' } }
62
+ expect(render(pool)).toContain('Prometheus has no Agent Substrate metrics for this pool')
63
+ })
64
+
65
+ it('says a pool reports no worker Pods, without the metric-naming hint', () => {
66
+ health = { data: { ...base, status: 'notFound' } }
67
+ const none = renderToStaticMarkup(<SubstrateHealthCharts target={pool} workerPods={0} />)
68
+ expect(none).toContain('The controller reports 0 worker Pods for this pool')
69
+ expect(none).not.toContain('underscore names')
70
+ expect(renderToStaticMarkup(<SubstrateHealthCharts target={pool} workerPods={2} />)).toContain('underscore names')
71
+ })
72
+
73
+ it('stays out of the way on a node that runs no Substrate', () => {
74
+ health = { data: { ...base, status: 'notFound' } }
75
+ expect(render(node)).toBe('')
76
+ health = { data: { ...base, status: 'notOnNode' } }
77
+ expect(render(node)).toBe('')
78
+ })
79
+
80
+ it('explains a node whose series cannot be attributed', () => {
81
+ health = { data: { ...base, status: 'notAttributable', reason: 'atelet\'s series carry no node label' } }
82
+ expect(render(node)).toContain('carry no node label')
83
+ })
84
+
85
+ it('shows a denial instead of an empty chart', () => {
86
+ health = { error: new ApiError('forbidden', 403) }
87
+ expect(render(pool)).toContain('You don&#x27;t have access to these metrics')
88
+ })
89
+
90
+ it('keeps unrounded values readable and explains charts it cannot draw', () => {
91
+ health = { data: { ...base, status: 'available', charts: [
92
+ chart({}),
93
+ chart({ id: 'resumeTime', title: 'Resume time', state: 'duplicateSources', reason: 'reported through more than one scrape job (a, b)', series: [] }),
94
+ ] } }
95
+ const html = render(pool)
96
+ // Each line's latest value sits in its legend entry, unrounded.
97
+ expect(html).toMatch(/idle \(gvisor\)<\/span><span class="tabular-nums[^"]*">1\.5</)
98
+ expect(html).toMatch(/partial \(gvisor\)<\/span><span class="tabular-nums[^"]*">1\.5</)
99
+ expect(html).toContain('Not shown: reported through more than one scrape job (a, b).')
100
+ expect(html).toContain('Aggregates: Substrate keeps actor names out')
101
+ expect(html).toContain('confirm these series belong to this exact cluster')
102
+ })
103
+
104
+ it('collapses among drawer sections, but is a plain heading on a Metrics tab', () => {
105
+ health = { data: { ...base, status: 'available', charts: [chart({})] } }
106
+ expect(render(pool)).toContain('aria-expanded')
107
+ const tab = renderToStaticMarkup(<SubstrateHealthCharts target={pool} collapsible={false} />)
108
+ expect(tab).not.toContain('aria-expanded')
109
+ expect(tab).toContain('Agent Substrate · last 1h')
110
+ })
111
+
112
+ it('states a reason shared by several charts once', () => {
113
+ const refused = { state: 'duplicateSources' as const, reason: 'reported through more than one scrape job (a, b)', series: [] }
114
+ health = { data: { ...base, status: 'available', charts: [
115
+ chart({ id: 'resumeTime', title: 'Resume time', ...refused }),
116
+ chart({ id: 'crashes', title: 'Actor crashes', ...refused }),
117
+ ] } }
118
+ const html = render(pool)
119
+ expect(html).toContain('Resume time · Actor crashes')
120
+ expect(html.split('more than one scrape job').length - 1).toBe(1)
121
+ })
122
+ it('does not call an hour-old sample "now"', () => {
123
+ health = { data: { ...base, status: 'available', charts: [chart({ series: [
124
+ { labels: { series: 'idle (gvisor)' }, dataPoints: [{ timestamp: 1000, value: 2 }, { timestamp: 4600, value: null }] },
125
+ { labels: { series: 'partial (gvisor)' }, dataPoints: [{ timestamp: 1000, value: 1 }] },
126
+ ] })] } }
127
+ expect(render(pool)).not.toMatch(/<\/span><span class="tabular-nums/)
128
+ })
129
+
130
+ it('says when samples begin only when they begin well after the range', () => {
131
+ const late = new Date(4000 * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
132
+ // Gaps and non-finite values before the first sample don't count; a zero does.
133
+ health = { data: { ...base, status: 'available', charts: [chart({ series: [
134
+ { labels: { series: 'idle (gvisor)' }, dataPoints: [{ timestamp: 1000, value: null }, { timestamp: 4000, value: 0 }] },
135
+ { labels: { series: 'partial (gvisor)' }, dataPoints: [{ timestamp: 4300, value: 1 }] },
136
+ ] })] } }
137
+ expect(render(pool)).toContain(`No samples before ${late}.`)
138
+ health = { data: { ...base, status: 'available', charts: [chart({ series: [
139
+ { labels: { series: 'idle (gvisor)' }, dataPoints: [{ timestamp: 1060, value: 2 }, { timestamp: 4600, value: 2 }] },
140
+ ] })] } }
141
+ expect(render(pool)).not.toContain('No samples before')
142
+ })
143
+ })
@@ -0,0 +1,254 @@
1
+ import { Info, LineChart, Loader2, Lock, Wifi } from 'lucide-react'
2
+ import { clsx } from 'clsx'
3
+ import { AlertBanner, RadarUpgradeNote, Section, Tooltip, toneTextClass } from '@skyhook-io/k8s-ui'
4
+ import { AreaChart, SeriesLegend, formatMetricValue, formatTimestamp, type TimeSeries, type TimeSeriesPoint } from '@skyhook-io/k8s-ui/components/charts'
5
+ import { isForbiddenError, useAutoPromConnect, usePrometheusConnect, usePrometheusStatus } from '../../api/client'
6
+ import { SUBSTRATE_RANGE, useSubstrateHealth, type SubstrateChart, type SubstrateHealth, type SubstrateTarget } from '../../api/substrateHealth'
7
+
8
+ const NO_WORKERS = 'The controller reports 0 worker Pods for this pool, and Prometheus has no Agent Substrate metrics for it.'
9
+
10
+ const NOT_FOUND = {
11
+ workerpool: 'Prometheus has no Agent Substrate metrics for this pool. Radar reads them under the underscore names Substrate\'s exporter gives them by default (ate_workerpool_workers) or the dotted ones Google Managed Prometheus keeps (ate.workerpool.workers); native histograms are not read.',
12
+ node: '',
13
+ } as const
14
+
15
+ /**
16
+ * Agent Substrate charts for one WorkerPool or Node, from the curated
17
+ * /prometheus/substrate endpoints. Aggregates only: Substrate keeps actor
18
+ * identity out of metric labels. Hidden on a Node that runs no Substrate, and
19
+ * when Prometheus is not connected unless standalone (the only content of its
20
+ * tab), which offers to connect; every other state says why there is no chart.
21
+ */
22
+ export function SubstrateHealthCharts({ target, standalone = false, collapsible = true, workerPods }: {
23
+ target: SubstrateTarget
24
+ standalone?: boolean
25
+ collapsible?: boolean
26
+ /** A WorkerPool's status.replicas, when the caller has it: with none, the empty charts need no metric-naming hint. */
27
+ workerPods?: number
28
+ }) {
29
+ useAutoPromConnect()
30
+ const { data: status } = usePrometheusStatus()
31
+ const connect = usePrometheusConnect()
32
+ const connected = status?.connected === true
33
+ const { data, error, upgrade, blockedReason, support } = useSubstrateHealth(target, connected && Boolean(target.name))
34
+
35
+ if (!connected) {
36
+ if (!standalone || !status) return null
37
+ return (
38
+ <Frame collapsible={collapsible}>
39
+ <Muted>{status.discovering ? 'Discovering Prometheus…' : status.error || 'Connect Prometheus to chart this pool\'s workers, resumes and crashes.'}</Muted>
40
+ {!status.discovering && (
41
+ <button type="button" onClick={() => connect.mutate()} disabled={connect.isPending} className="btn-brand mt-3 inline-flex items-center gap-2 rounded-lg px-3 py-1.5 text-xs font-medium">
42
+ {connect.isPending ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Wifi className="h-3.5 w-3.5" />}
43
+ Discover Prometheus
44
+ </button>
45
+ )}
46
+ </Frame>
47
+ )
48
+ }
49
+ if (upgrade && target.kind === 'workerpool') {
50
+ return <Frame collapsible={collapsible}><RadarUpgradeNote requirement={upgrade} /></Frame>
51
+ }
52
+ // Until this Radar is known to serve the charts, the query never runs.
53
+ if (!data && support !== 'supported' && blockedReason && target.kind === 'workerpool') {
54
+ return <Frame collapsible={collapsible}><Muted>{blockedReason}</Muted></Frame>
55
+ }
56
+ if (isForbiddenError(error)) {
57
+ return (
58
+ <Frame collapsible={collapsible}>
59
+ <AlertBanner
60
+ variant="info"
61
+ icon={Lock}
62
+ title="You don't have access to these metrics"
63
+ message={target.kind === 'workerpool'
64
+ ? 'Agent Substrate charts are available to users who can read this WorkerPool.'
65
+ : 'Agent Substrate charts for a node are available to users who can read Nodes.'}
66
+ />
67
+ </Frame>
68
+ )
69
+ }
70
+ if (error) {
71
+ return <Frame collapsible={collapsible}><Muted tone="warning">Agent Substrate metrics could not be read: {error.message}</Muted></Frame>
72
+ }
73
+ if (!data) return null
74
+
75
+ switch (data.status) {
76
+ case 'notOnNode':
77
+ return null
78
+ case 'notFound':
79
+ if (target.kind !== 'workerpool') return null
80
+ return <Frame collapsible={collapsible}><Muted>{workerPods === 0 ? NO_WORKERS : NOT_FOUND.workerpool}</Muted></Frame>
81
+ case 'notAttributable':
82
+ case 'error':
83
+ return <Frame collapsible={collapsible}><Muted tone={data.status === 'error' ? 'warning' : undefined}>{data.reason}</Muted></Frame>
84
+ }
85
+ return <Frame collapsible={collapsible}><Charts health={data} /></Frame>
86
+ }
87
+
88
+ // A section like its neighbours, not a card: the charts are the only cards.
89
+ // Collapsible among the drawer's sections; a plain heading on a Metrics tab,
90
+ // where collapsing it would only empty the tab.
91
+ function Frame({ children, collapsible }: { children: React.ReactNode; collapsible: boolean }) {
92
+ const title = `Agent Substrate · last ${SUBSTRATE_RANGE}`
93
+ return (
94
+ <section aria-label="Agent Substrate metrics">
95
+ {collapsible ? (
96
+ <Section title={title} icon={LineChart}>{children}</Section>
97
+ ) : (
98
+ <>
99
+ <h3 className="mb-2 flex items-center gap-2 text-sm font-medium text-theme-text-secondary">
100
+ <LineChart className="h-4 w-4" />
101
+ {title}
102
+ </h3>
103
+ {children}
104
+ </>
105
+ )}
106
+ </section>
107
+ )
108
+ }
109
+
110
+ // Averaged worker counts can be fractional; their axis stays on whole numbers.
111
+ function chartUnit(unit: string): string {
112
+ return unit === 'workers' ? 'avgCount' : unit
113
+ }
114
+
115
+ function Muted({ children, tone }: { children: React.ReactNode; tone?: 'warning' }) {
116
+ return <p className={clsx('text-xs', tone === 'warning' ? toneTextClass('degraded') : 'text-theme-text-tertiary')}>{children}</p>
117
+ }
118
+
119
+ function Charts({ health }: { health: SubstrateHealth }) {
120
+ const unverified = health.charts.find(c => c.state === 'ok' && c.isolation.mode === 'unverified')
121
+ return (
122
+ <>
123
+ <p className="mb-3 text-xs text-theme-text-tertiary">
124
+ Aggregates: Substrate keeps actor names out of its metrics.
125
+ </p>
126
+ <div className="grid grid-cols-1 gap-3">
127
+ {groupCharts(health.charts).map(group => group.length === 1
128
+ ? <Chart key={group[0].id} chart={group[0]} health={health} />
129
+ : <SharedReason key={group[0].id} charts={group} />)}
130
+ </div>
131
+ {unverified && <p className="mt-3 text-xs text-theme-text-tertiary">{unverified.isolation.note}.</p>}
132
+ </>
133
+ )
134
+ }
135
+
136
+ // Charts that cannot be drawn for the same reason share one note instead of
137
+ // repeating it card after card.
138
+ function groupCharts(charts: SubstrateChart[]): SubstrateChart[][] {
139
+ const groups: SubstrateChart[][] = []
140
+ const byReason = new Map<string, SubstrateChart[]>()
141
+ for (const chart of charts) {
142
+ if (chart.state === 'ok') {
143
+ groups.push([chart])
144
+ continue
145
+ }
146
+ const key = `${chart.state}\u0000${chart.reason ?? ''}`
147
+ const group = byReason.get(key)
148
+ if (group) {
149
+ group.push(chart)
150
+ } else {
151
+ const created = [chart]
152
+ byReason.set(key, created)
153
+ groups.push(created)
154
+ }
155
+ }
156
+ return groups
157
+ }
158
+
159
+ function SharedReason({ charts }: { charts: SubstrateChart[] }) {
160
+ return (
161
+ <section className="rounded-lg border border-theme-border bg-theme-surface/30 p-3 min-w-0">
162
+ <h4 className="mb-1 text-xs font-medium text-theme-text-secondary">{charts.map(c => c.title).join(' · ')}</h4>
163
+ <Muted tone={charts[0].state === 'empty' || charts[0].state === 'noSeries' ? undefined : 'warning'}>{chartReason(charts[0])}</Muted>
164
+ </section>
165
+ )
166
+ }
167
+
168
+ function Chart({ chart, health }: { chart: SubstrateChart; health: SubstrateHealth }) {
169
+ const series = chart.series
170
+ const seriesLabels = series.map(s => s.labels.series || chart.title)
171
+ // Only a sample from the last two steps is "now"; an older one ended earlier in the range.
172
+ const since = health.end - 2 * health.stepSeconds
173
+ const unit = chartUnit(chart.unit)
174
+ const latest = chart.state === 'ok' && series.length === 1 ? lastValue(series[0].dataPoints, since) : undefined
175
+ // Each line's latest value sits in its legend entry: lines that share a
176
+ // value hide one another on the plot.
177
+ const legendValues = series.map(s => {
178
+ const v = lastValue(s.dataPoints, since)
179
+ return v === undefined ? undefined : formatMetricValue(v, unit)
180
+ })
181
+ const lateStart = chart.state === 'ok' ? lateFirstSample(series, health) : undefined
182
+ return (
183
+ <section className="rounded-lg border border-theme-border bg-theme-surface/30 p-3 flex flex-col min-w-0">
184
+ <header className="flex items-baseline justify-between gap-2 mb-1">
185
+ <h4 className="flex items-center gap-1 text-xs font-medium text-theme-text-secondary">
186
+ {chart.title}
187
+ <Tooltip content={`${chart.population} Source: ${chart.source}.`}>
188
+ <Info className="w-3 h-3 text-theme-text-tertiary" aria-label={`About ${chart.title}`} />
189
+ </Tooltip>
190
+ </h4>
191
+ {latest !== undefined && (
192
+ <span className="text-sm font-semibold tabular-nums text-theme-text-primary">{formatMetricValue(latest, unit)}</span>
193
+ )}
194
+ </header>
195
+ {chart.state === 'ok' ? (
196
+ <>
197
+ <AreaChart
198
+ series={series}
199
+ unit={unit}
200
+ color="var(--accent)"
201
+ fillColor="var(--accent-muted)"
202
+ layout="dashboard"
203
+ height={140}
204
+ seriesLabels={seriesLabels}
205
+ domain={{ start: health.start, end: health.end }}
206
+ stepSeconds={health.stepSeconds}
207
+ />
208
+ {series.length > 1 && <SeriesLegend series={series} color="var(--accent)" seriesLabels={seriesLabels} values={legendValues} />}
209
+ {lateStart !== undefined && <Muted>No samples before {formatTimestamp(lateStart)}.</Muted>}
210
+ {chart.omitted ? <Muted>{chart.omitted} more series not shown.</Muted> : null}
211
+ {chart.reason ? <Muted>{capitalize(chart.reason)}.</Muted> : null}
212
+ </>
213
+ ) : (
214
+ <Muted tone={chart.state === 'empty' || chart.state === 'noSeries' ? undefined : 'warning'}>{chartReason(chart)}</Muted>
215
+ )}
216
+ </section>
217
+ )
218
+ }
219
+
220
+ function capitalize(text: string): string {
221
+ return text.charAt(0).toUpperCase() + text.slice(1)
222
+ }
223
+
224
+ function chartReason(chart: SubstrateChart): string {
225
+ const reason = chart.reason ?? ''
226
+ switch (chart.state) {
227
+ case 'empty':
228
+ return `No data: ${reason}.`
229
+ case 'noSeries':
230
+ return `Not reported: ${reason}.`
231
+ default:
232
+ return `Not shown: ${reason}.`
233
+ }
234
+ }
235
+
236
+ // The first sample, when it comes well after the range starts: a mostly empty
237
+ // plot otherwise reads as a broken chart. It says when samples begin, not why.
238
+ function lateFirstSample(series: TimeSeries[], health: SubstrateHealth): number | undefined {
239
+ let first: number | undefined
240
+ for (const s of series) {
241
+ const p = s.dataPoints.find(d => d.value != null && Number.isFinite(d.value))
242
+ if (p && (first === undefined || p.timestamp < first)) first = p.timestamp
243
+ }
244
+ const gap = Math.max(2 * health.stepSeconds, (health.end - health.start) / 10)
245
+ return first !== undefined && first - health.start > gap ? first : undefined
246
+ }
247
+
248
+ function lastValue(points: TimeSeriesPoint[], since: number): number | undefined {
249
+ for (let i = points.length - 1; i >= 0 && points[i].timestamp >= since; i--) {
250
+ const v = points[i].value
251
+ if (v != null && Number.isFinite(v)) return v
252
+ }
253
+ return undefined
254
+ }
@@ -0,0 +1,131 @@
1
+ import { renderToStaticMarkup } from 'react-dom/server'
2
+ import { describe, expect, it, vi } from 'vitest'
3
+ import type { SubstrateFact, SubstrateHealth, SubstrateVerdict } from '../../api/substrateHealth'
4
+
5
+ let health: { data?: SubstrateHealth; error?: Error } = {}
6
+ let connected = true
7
+
8
+ // Tooltips render their content on hover; the mock puts it in the markup.
9
+ vi.mock('@skyhook-io/k8s-ui', async (orig) => ({
10
+ ...(await orig<typeof import('@skyhook-io/k8s-ui')>()),
11
+ Tooltip: ({ content, children }: { content: string; children: React.ReactNode }) => <span data-tooltip={content}>{children}</span>,
12
+ }))
13
+ vi.mock('../../api/client', async (orig) => ({
14
+ ...(await orig<typeof import('../../api/client')>()),
15
+ usePrometheusStatus: () => ({ data: { connected } }),
16
+ }))
17
+ vi.mock('../../api/substrateHealth', async (orig) => ({
18
+ ...(await orig<typeof import('../../api/substrateHealth')>()),
19
+ useSubstrateHealth: () => health,
20
+ }))
21
+
22
+ const { SubstrateVerdictLine } = await import('./SubstrateVerdictLine')
23
+
24
+ const pool = { kind: 'workerpool' as const, namespace: 'agents', name: 'pool' }
25
+ const node = { kind: 'node' as const, name: 'worker-1' }
26
+ const base = { range: '1h', start: 1000, end: 4600, stepSeconds: 60, charts: [] }
27
+
28
+ function withVerdict(verdict: SubstrateVerdict, status: SubstrateHealth['status'] = 'available') {
29
+ health = { data: { ...base, status, verdict } }
30
+ }
31
+ const render = (target: typeof pool | typeof node) => renderToStaticMarkup(<SubstrateVerdictLine target={target} onOpenMetrics={() => {}} />)
32
+ const ok = (id: string, label: string, unit: SubstrateFact['unit'], value: number, extra: Partial<SubstrateFact> = {}): SubstrateFact => ({ id, label, unit, state: 'ok', value, ...extra })
33
+
34
+ describe('SubstrateVerdictLine', () => {
35
+ it('flags a pool short of workers in amber and keeps its facts uncolored', () => {
36
+ withVerdict({ state: 'workerShortfall', facts: [ok('schedulableWorkers', 'Schedulable workers', 'workers', 4, { of: 6 }), ok('workersWithFreeActorSlots', 'Workers with free slots', 'workers', 0, { of: 3 })] })
37
+ const html = render(pool)
38
+ // Titled for a reader who has never heard of Substrate, with what the state means.
39
+ expect(html).toContain('Agent Substrate capacity')
40
+ expect(html).toContain('Short of workers')
41
+ expect(html).toContain('stayed that way for five minutes')
42
+ expect(html).toMatch(/bg-amber-100/)
43
+ expect(html).toMatch(/Schedulable workers<\/span>.*?4 of 6 desired/)
44
+ expect(html).toContain('0 of 3')
45
+ expect(html).toContain('View metrics')
46
+ })
47
+
48
+ it('reads full as neutral and free slots as plain text', () => {
49
+ withVerdict({ state: 'noFreeActorSlots', facts: [] })
50
+ expect(render(pool)).toContain('bg-theme-hover/50')
51
+ withVerdict({ state: 'freeActorSlots', facts: [] })
52
+ const html = render(pool)
53
+ expect(html).toContain('Free slots')
54
+ expect(html).not.toMatch(/bg-amber|bg-red|bg-emerald/)
55
+ expect(html).not.toContain('aria-label="Qualified"')
56
+ })
57
+
58
+ it('says an unjudged shortfall in the section and marks an unconfirmed cluster', () => {
59
+ withVerdict({ state: 'freeActorSlots', reason: "Radar cannot tell whether the pool is short of workers: Substrate's controller reported no desired worker count", facts: [] })
60
+ // Every pool on Substrate's default install: said in plain view, not only on hover.
61
+ expect(render(pool)).toContain('Radar cannot tell whether the pool is short of workers')
62
+ expect(render(pool)).not.toContain('aria-label="Qualified"')
63
+ const unverified = { isolation: { mode: 'unverified' as const, note: "Radar couldn't confirm these Substrate series belong to this exact cluster" } }
64
+ health = { data: { ...base, status: 'available', verdict: { state: 'noFreeActorSlots', facts: [] }, charts: [{ id: 'workers', title: '', unit: 'workers', population: '', source: '', state: 'ok', series: [], ...unverified }] } }
65
+ expect(render(pool)).toContain('aria-label="Qualified"')
66
+ // An unconfirmed cluster alone says nothing about the shortfall.
67
+ expect(render(pool)).not.toContain('cannot tell whether the pool is short')
68
+ })
69
+
70
+ it('shows fractional replica averages as approximate, never rounded', () => {
71
+ withVerdict({ state: 'freeActorSlots', facts: [ok('workersWithFreeActorSlots', 'Workers with free slots', 'workers', 1.5, { of: 4 }), ok('crashes', 'Crashes', 'count', 2.4)] })
72
+ const html = render(pool)
73
+ expect(html).toContain('≈1.5 of 4')
74
+ expect(html).toContain('Crashes (1h)')
75
+ expect(html).toContain('≈2.4')
76
+ })
77
+
78
+ it('says an hourly fact covers only the data Prometheus collected', () => {
79
+ withVerdict({ state: 'freeActorSlots', facts: [ok('crashes', 'Crashes', 'count', 0), ok('workersWithFreeActorSlots', 'Workers with free slots', 'workers', 2, { of: 4 })] })
80
+ const html = render(pool)
81
+ expect(html).toMatch(/data-tooltip="Computed from the data Prometheus holds for the last hour[^"]*"><span>Crashes \(1h\)/)
82
+ expect(html).not.toMatch(/data-tooltip="[^"]*last hour[^"]*"><span>Workers with free slots/)
83
+ })
84
+
85
+ it('says Unavailable, never 0, for a fact Radar could not read, and None for one with nothing recorded', () => {
86
+ withVerdict({ state: 'unknown', reason: 'reported through more than one scrape job', facts: [
87
+ { id: 'workersWithFreeActorSlots', label: 'Workers with free slots', unit: 'workers', state: 'unavailable', reason: 'reported through more than one scrape job' },
88
+ { id: 'resumeP95', label: 'Resume p95', unit: 'seconds', state: 'empty', reason: 'no actor resumed on this pool in this range' },
89
+ ] })
90
+ const html = render(pool)
91
+ expect(html).toContain('Unknown')
92
+ expect(html).toContain('Unavailable')
93
+ expect(html).toContain('None')
94
+ expect(html.replace(/<[^>]+>/g, ' ')).toMatch(/Workers with free slots\s+Unavailable/)
95
+ })
96
+
97
+ it('names overdue bands on a node, worst first', () => {
98
+ withVerdict({ state: 'uploadsOverdue', facts: [ok('overdueUploads', 'Overdue uploads', 'count', 3, { parts: [{ label: 'over_15m', value: 1 }, { label: '1m_to_5m', value: 2 }] })] })
99
+ const html = render(node)
100
+ expect(html).toContain('Agent Substrate snapshots')
101
+ expect(html).toContain('Uploads overdue')
102
+ expect(html).toContain('overdue for upload to object storage')
103
+ expect(html).toContain('3 (over 15m: 1, 1–5m: 2)')
104
+ })
105
+
106
+ it('does not keep asserting a cached verdict after a failed refresh or a disconnect', () => {
107
+ withVerdict({ state: 'freeActorSlots', facts: [] })
108
+ health = { ...health, error: new Error('timeout') }
109
+ const html = render(pool)
110
+ expect(html).toContain('Unknown')
111
+ expect(html).not.toContain('Free slots')
112
+ health = { data: health.data }
113
+ connected = false
114
+ expect(render(pool)).toBe('')
115
+ connected = true
116
+ })
117
+
118
+ it('claims no more than the overdue count proves on a node', () => {
119
+ withVerdict({ state: 'noUploadsOverdue', facts: [] })
120
+ const html = render(node)
121
+ expect(html).toContain('No overdue uploads')
122
+ expect(html).not.toContain('Up to date')
123
+ })
124
+
125
+ it('renders nothing without a verdict', () => {
126
+ health = { data: { ...base, status: 'notFound' } }
127
+ expect(render(pool)).toBe('')
128
+ health = {}
129
+ expect(render(pool)).toBe('')
130
+ })
131
+ })