@skyhook-io/radar-app 1.19.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +1 -1
  2. package/package.json +5 -5
  3. package/src/App.tsx +31 -5
  4. package/src/api/application-evidence.ts +63 -0
  5. package/src/api/argoSync.test.ts +22 -0
  6. package/src/api/client.audit-gating.test.tsx +48 -0
  7. package/src/api/client.kueuePosition.test.ts +32 -0
  8. package/src/api/client.kueueQueueWorkloads.test.tsx +71 -0
  9. package/src/api/client.resource-identity.test.ts +3 -0
  10. package/src/api/client.resourceIssues.test.tsx +239 -0
  11. package/src/api/client.resourcePath.test.ts +3 -0
  12. package/src/api/client.ts +285 -55
  13. package/src/api/config.ts +21 -0
  14. package/src/api/diagnose.ts +4 -0
  15. package/src/api/radarFeatures.render.test.tsx +33 -1
  16. package/src/api/radarFeatures.test.ts +47 -0
  17. package/src/api/radarFeatures.ts +40 -1
  18. package/src/api/rbac.settled.test.tsx +42 -0
  19. package/src/api/rbac.test.ts +18 -0
  20. package/src/api/rbac.ts +37 -7
  21. package/src/api/traffic.ts +9 -4
  22. package/src/api/usage-data.fixtures.ts +3 -1
  23. package/src/api/usage-data.test.tsx +134 -0
  24. package/src/api/usage-data.ts +35 -7
  25. package/src/api/workloadPodsPolling.test.ts +26 -0
  26. package/src/components/CloudConnectFlow.test.tsx +86 -0
  27. package/src/components/CloudConnectFlow.tsx +65 -27
  28. package/src/components/CloudFunnelButton.test.tsx +140 -5
  29. package/src/components/CloudFunnelButton.tsx +50 -9
  30. package/src/components/ConnectionErrorView.test.tsx +34 -0
  31. package/src/components/ConnectionErrorView.tsx +35 -11
  32. package/src/components/ContextSwitcher.tsx +5 -2
  33. package/src/components/SwitchAwareConnectionError.test.tsx +43 -0
  34. package/src/components/SwitchAwareConnectionError.tsx +85 -0
  35. package/src/components/application-evidence/ApplicationEvidenceAction.flow.test.tsx +234 -0
  36. package/src/components/application-evidence/ApplicationEvidenceAction.test.tsx +144 -0
  37. package/src/components/application-evidence/ApplicationEvidenceAction.tsx +218 -0
  38. package/src/components/capacity/CapacityDemand.tsx +3 -2
  39. package/src/components/capacity/demandSummary.test.ts +38 -0
  40. package/src/components/capacity/shared.tsx +12 -1
  41. package/src/components/cost/ApplicationCostTab.tsx +4 -0
  42. package/src/components/cost/CostTrendChart.tsx +2 -0
  43. package/src/components/cost/WorkloadCostTab.tsx +4 -0
  44. package/src/components/cost/source.test.ts +5 -0
  45. package/src/components/cost/source.ts +11 -0
  46. package/src/components/diagnose/AIMarkdown.tsx +3 -0
  47. package/src/components/diagnose/AgentSetupNotice.test.tsx +17 -0
  48. package/src/components/diagnose/AgentSetupNotice.tsx +21 -3
  49. package/src/components/diagnose/ContinueInAgentButton.mounted.test.tsx +182 -0
  50. package/src/components/diagnose/ContinueInAgentButton.test.tsx +128 -0
  51. package/src/components/diagnose/ContinueInAgentButton.tsx +303 -0
  52. package/src/components/diagnose/DiagnoseContext.question.test.tsx +1 -1
  53. package/src/components/diagnose/DiagnoseContext.tsx +68 -2
  54. package/src/components/diagnose/DiagnoseSurface.tsx +58 -113
  55. package/src/components/diagnose/ExampleInvestigationLink.tsx +20 -0
  56. package/src/components/diagnose/Home.test.tsx +26 -0
  57. package/src/components/diagnose/Home.tsx +20 -1
  58. package/src/components/diagnose/InvestigationEvidenceSections.tsx +45 -22
  59. package/src/components/diagnose/InvestigationView.tsx +94 -26
  60. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +450 -0
  61. package/src/components/diagnose/LocalDiagnoseAction.tsx +354 -35
  62. package/src/components/diagnose/NextStepJump.test.tsx +92 -0
  63. package/src/components/diagnose/NextStepJump.tsx +75 -0
  64. package/src/components/diagnose/QuestionComposer.tsx +8 -0
  65. package/src/components/diagnose/exampleInvestigation.events.json +191 -0
  66. package/src/components/diagnose/exampleInvestigation.loadFailure.test.tsx +94 -0
  67. package/src/components/diagnose/exampleInvestigation.test.tsx +248 -0
  68. package/src/components/diagnose/exampleInvestigation.ts +121 -0
  69. package/src/components/diagnose/investigationCase.test.tsx +9 -1
  70. package/src/components/diagnose/investigationEvidence/adapters/applicationFindings.test.ts +739 -0
  71. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +50 -2
  72. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +9 -0
  73. package/src/components/diagnose/investigationEvidence/builder.ts +30 -0
  74. package/src/components/diagnose/investigationEvidence/observations.ts +121 -2
  75. package/src/components/diagnose/investigationEvidence/projection.test.ts +85 -3
  76. package/src/components/diagnose/investigationEvidence/types.ts +5 -0
  77. package/src/components/diagnose/investigationState.ts +28 -0
  78. package/src/components/diagnose/lastInvestigation.test.ts +95 -0
  79. package/src/components/diagnose/lastInvestigation.ts +58 -0
  80. package/src/components/diagnose/launch.test.ts +125 -1
  81. package/src/components/diagnose/launch.ts +57 -10
  82. package/src/components/diagnose/toolCallLabel.test.ts +10 -4
  83. package/src/components/execution/BatchExecutionView.tsx +24 -11
  84. package/src/components/execution/JobSetAdmission.test.tsx +42 -0
  85. package/src/components/execution/JobSetAdmission.tsx +18 -3
  86. package/src/components/execution/JobSetMemberComparison.tsx +2 -1
  87. package/src/components/execution/runState.test.ts +14 -0
  88. package/src/components/execution/runState.ts +8 -0
  89. package/src/components/gitops/GitOpsView.rollbackGate.test.tsx +202 -0
  90. package/src/components/gitops/GitOpsView.syncRequest.test.tsx +369 -0
  91. package/src/components/gitops/GitOpsView.tsx +86 -17
  92. package/src/components/gitops/RemoteDestinationCloudHint.tsx +2 -3
  93. package/src/components/gitops/destination-toast.test.ts +1 -1
  94. package/src/components/gitops/destination-toast.ts +2 -2
  95. package/src/components/home/ClusterHealthCard.tsx +1 -1
  96. package/src/components/home/HomeAgentBlock.test.tsx +31 -3
  97. package/src/components/home/HomeAgentBlock.tsx +13 -4
  98. package/src/components/home/HomeDiagramCard.tsx +47 -0
  99. package/src/components/home/HomeView.tsx +81 -41
  100. package/src/components/home/MCPSetupDialog.test.tsx +95 -5
  101. package/src/components/home/MCPSetupDialog.tsx +30 -5
  102. package/src/components/home/ProblemsPanel.investigate.test.tsx +171 -0
  103. package/src/components/home/ProblemsPanel.test.tsx +3 -1
  104. package/src/components/home/TopologyPreview.test.tsx +73 -0
  105. package/src/components/home/TopologyPreview.tsx +120 -233
  106. package/src/components/home/TrafficSummary.test.tsx +63 -0
  107. package/src/components/home/TrafficSummary.tsx +135 -138
  108. package/src/components/home/mcpToolCatalog.ts +23 -10
  109. package/src/components/issues/IssuesPane.test.ts +11 -0
  110. package/src/components/issues/IssuesPane.tsx +15 -5
  111. package/src/components/issues/uncheckedSources.test.ts +20 -1
  112. package/src/components/issues/uncheckedSources.ts +18 -0
  113. package/src/components/kueue/KueuePendingPosition.tsx +35 -0
  114. package/src/components/kueue/useRelatedObjects.test.tsx +219 -0
  115. package/src/components/kueue/useRelatedReads.test.ts +56 -0
  116. package/src/components/kueue/useRelatedReads.ts +205 -0
  117. package/src/components/logs/MultiPodLogsTab.test.tsx +93 -0
  118. package/src/components/logs/MultiPodLogsTab.tsx +120 -0
  119. package/src/components/logs/PodLogsUnavailable.test.tsx +18 -0
  120. package/src/components/logs/PodLogsUnavailable.tsx +21 -0
  121. package/src/components/logs/RayClusterLogsTab.reselect.test.tsx +67 -0
  122. package/src/components/logs/RayClusterLogsTab.test.tsx +167 -0
  123. package/src/components/logs/RayClusterLogsTab.tsx +109 -0
  124. package/src/components/logs/ScheduledWorkloadLogsViewer.tsx +3 -2
  125. package/src/components/logs/rayClusterPods.ts +32 -0
  126. package/src/components/outageSince.test.ts +21 -0
  127. package/src/components/outageSince.ts +10 -0
  128. package/src/components/resource/PrometheusCharts.overlays.test.ts +12 -0
  129. package/src/components/resource/PrometheusCharts.tsx +3 -40
  130. package/src/components/resources/crd/CRDSchemaTab.test.tsx +28 -0
  131. package/src/components/resources/crd/CRDSchemaTab.tsx +13 -0
  132. package/src/components/resources/crd/host.tsx +14 -0
  133. package/src/components/resources/renderers/CustomResourceDefinitionRenderer.test.tsx +27 -0
  134. package/src/components/resources/renderers/CustomResourceDefinitionRenderer.tsx +12 -0
  135. package/src/components/resources/renderers/JobAdmissionRenderers.test.tsx +4 -1
  136. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +4 -3
  137. package/src/components/resources/renderers/KueueHostRenderers.test.tsx +117 -0
  138. package/src/components/resources/renderers/KueueQueueRenderers.test.tsx +97 -0
  139. package/src/components/resources/renderers/KueueQueueRenderers.tsx +139 -0
  140. package/src/components/resources/renderers/KueueWorkloadRenderer.test.tsx +7 -1
  141. package/src/components/resources/renderers/KueueWorkloadRenderer.tsx +47 -7
  142. package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.test.tsx +67 -0
  143. package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.tsx +31 -0
  144. package/src/components/resources/renderers/RayClusterRenderer.test.tsx +81 -3
  145. package/src/components/resources/renderers/RayClusterRenderer.tsx +19 -4
  146. package/src/components/traffic/TrafficView.tsx +3 -3
  147. package/src/components/ui/command-items-crd.test.tsx +23 -0
  148. package/src/components/ui/command-items.ts +2 -1
  149. package/src/components/useContextSwitchFlow.test.tsx +61 -0
  150. package/src/components/useContextSwitchFlow.tsx +21 -4
  151. package/src/components/whats-new/WhatsNew.test.ts +10 -3
  152. package/src/components/whats-new/WhatsNew.tsx +5 -1
  153. package/src/components/whats-new/WhatsNewDialog.test.tsx +17 -3
  154. package/src/components/whats-new/releaseNotes.ts +77 -4
  155. package/src/components/workload/RelatedFindingsSection.test.tsx +126 -0
  156. package/src/components/workload/RelatedFindingsSection.tsx +80 -0
  157. package/src/components/workload/WorkloadView.test.ts +10 -1
  158. package/src/components/workload/WorkloadView.tsx +85 -98
  159. package/src/components/workload/issueResourceOpener.test.ts +20 -0
  160. package/src/components/workload/issueResourceOpener.ts +17 -0
  161. package/src/context/ConnectionContext.tsx +133 -60
  162. package/src/context/ConnectionProvider.retry.test.tsx +176 -0
  163. package/src/context/ContextSwitchContext.tsx +14 -1
  164. package/src/context/DiagnoseCustomization.tsx +3 -0
  165. package/src/context/clusterConnected.ts +10 -0
  166. package/src/contexts/CapabilitiesContext.tsx +6 -4
  167. package/src/hooks/useElementSize.ts +30 -0
  168. package/src/integrations/resourceHost.test.tsx +1 -0
  169. package/src/integrations/resourceHost.ts +5 -1
  170. package/src/integrations/resourceHosts.test.tsx +21 -4
  171. package/src/integrations/resourceHosts.tsx +12 -0
  172. package/src/main.tsx +5 -0
  173. package/src/utils/related-findings.ts +46 -0
@@ -0,0 +1,144 @@
1
+ import { renderToStaticMarkup } from 'react-dom/server'
2
+ import { describe, expect, it } from 'vitest'
3
+ import type { ApplicationEvidenceResult } from '../../api/application-evidence'
4
+ import { ApplicationEvidenceObservation } from './ApplicationEvidenceAction'
5
+
6
+ const result: ApplicationEvidenceResult = {
7
+ adapter: 'rabbitmq', target: { namespace: 'demo', pod: 'rabbit-0', uid: 'uid', container: 'rabbitmq' },
8
+ observedAt: '2026-09-22T10:00:00Z', source: 'selected_pod_endpoint', outcome: 'observed',
9
+ limitations: ['One Pod only; other replicas were not checked.'],
10
+ }
11
+
12
+ describe('application observations', () => {
13
+ it('shows absent alarms as source observations, not a health verdict', () => {
14
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, facts: { rabbitmq: { diskAlarm: false, memoryAlarm: true } } }} />)
15
+ expect(html).toContain('Not reported')
16
+ expect(html).toContain('Reported')
17
+ expect(html).toContain('demo/rabbit-0')
18
+ expect(html).toContain('other replicas were not checked')
19
+ expect(html).not.toContain('Healthy')
20
+ })
21
+ it('shows reported resource values without inferring alarms or percentages', () => {
22
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, facts: { rabbitmq: {
23
+ diskAlarm: false, memoryAlarm: true, diskAvailableBytes: 0, diskWatermarkBytes: 50 * 1024 * 1024,
24
+ memoryUsedBytes: 128 * 1024 * 1024, memoryWatermarkBytes: 512 * 1024 * 1024,
25
+ } } }} />)
26
+ expect(html).toContain('Free disk</dt><dd class="break-words"><span class="block">0 B')
27
+ expect(html).toContain('Disk alarm below</dt><dd class="break-words"><span class="block">50 MiB')
28
+ expect(html).toContain('Memory used (RabbitMQ)</dt><dd class="break-words"><span class="block">128 MiB')
29
+ expect(html).toContain('Memory alarm above</dt><dd class="break-words"><span class="block">512 MiB')
30
+ expect(html).toContain('Disk alarm</dt><dd>Not reported')
31
+ expect(html).toContain('Memory alarm</dt><dd>Reported')
32
+ expect(html).toContain('can lag the alarm state')
33
+ expect(html).not.toContain('%')
34
+ })
35
+ it('keeps absent measurements unknown while preserving alarms and handles large exact values', () => {
36
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, facts: { rabbitmq: {
37
+ diskAlarm: false, memoryAlarm: false, diskAvailableBytes: Number.MAX_SAFE_INTEGER,
38
+ } } }} />)
39
+ expect(html).toContain('GiB')
40
+ expect(html.match(/Unknown<\/dd>/g)).toHaveLength(3)
41
+ expect(html).toContain('Disk alarm</dt><dd>Not reported')
42
+ expect(html).not.toContain('undefined')
43
+ expect(html).not.toContain('NaN')
44
+ })
45
+ it.each([
46
+ [49900000, 50000000, 2415000000, 2412409651],
47
+ [1048500, 1048576, 1073700000, 1073741824],
48
+ ])('keeps exact measurements visible near thresholds and unit boundaries (%d, %d, %d, %d)', (diskAvailableBytes, diskWatermarkBytes, memoryUsedBytes, memoryWatermarkBytes) => {
49
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, facts: { rabbitmq: {
50
+ diskAlarm: true, memoryAlarm: true, diskAvailableBytes, diskWatermarkBytes, memoryUsedBytes, memoryWatermarkBytes,
51
+ } } }} />)
52
+ for (const value of [diskAvailableBytes, diskWatermarkBytes, memoryUsedBytes, memoryWatermarkBytes]) {
53
+ expect(html).toContain(`>${value.toLocaleString()} bytes</span>`)
54
+ }
55
+ expect(html).toContain('can lag the alarm state')
56
+ })
57
+ it('does not display facts when collection is unavailable', () => {
58
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, outcome: 'unavailable', reason: 'endpoint_denied', facts: { rabbitmq: { diskAlarm: false, memoryAlarm: false } } }} />)
59
+ expect(html).toContain('Evidence unavailable')
60
+ expect(html).toContain('requires authorization')
61
+ expect(html).not.toContain('Disk alarm')
62
+ })
63
+ it('keeps NATS partial coverage and account identity visible', () => {
64
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, adapter: 'nats', facts: { nats: { jetStreamEnabled: true, coverage: 'partial', returnedAccounts: 1, returnedStreams: 1, returnedConsumers: 1, truncated: true, consumers: [{ account: '$G', stream: 'events', name: 'worker', pending: 5, ackPending: 0, redelivered: 0 }] } } }} />)
65
+ expect(html).toContain('partial')
66
+ expect(html).toContain('Truncated')
67
+ expect(html).toContain('$G / events / worker')
68
+ expect(html).not.toContain('stuck')
69
+ })
70
+ it('preserves exact NATS positions and shows missing activity as unavailable', () => {
71
+ const facts: ApplicationEvidenceResult['facts'] = { nats: { jetStreamEnabled: true, coverage: 'node_reported', returnedAccounts: 1, returnedStreams: 1, returnedConsumers: 1, truncated: false, consumers: [{ account: '$G', stream: 'events', name: 'worker', pending: 5, ackPending: 0, redelivered: 0, delivered: { consumerSequence: '18446744073709551615', streamSequence: '9007199254740993' }, ackFloor: { consumerSequence: '0', streamSequence: '0', lastActive: '2026-11-03T01:44:18.902568436Z' }, waitingPullRequests: 0 }] } }
72
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, adapter: 'nats', facts }} />)
73
+ expect(html).toContain('18446744073709551615')
74
+ expect(html).toContain('9007199254740993')
75
+ expect(html).toContain(new Date('2026-11-03T01:44:18.902568436Z').toLocaleString())
76
+ expect(html).toContain('Last delivery</dt><dd class="break-words">Unavailable')
77
+ expect(html).toContain('Waiting pull requests on this node</dt><dd>0')
78
+ expect(html).toContain('zero can also reflect a push consumer or non-leader replica')
79
+ expect(html).toContain('a non-leader replica can report zero pending messages')
80
+ expect(html).toContain('one snapshot cannot establish stalled progress')
81
+ expect(html).not.toContain('never active')
82
+ const unavailable = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, adapter: 'nats', outcome: 'unavailable', reason: 'endpoint_denied', facts }} />)
83
+ expect(unavailable).not.toContain('Consumer progress')
84
+ expect(unavailable).not.toContain('18446744073709551615')
85
+ })
86
+ it.each([
87
+ { initialized: false, sealed: true },
88
+ { initialized: true, sealed: true },
89
+ ])('does not present a Vault role while initialized=$initialized sealed=$sealed', state => {
90
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, adapter: 'vault', facts: { vault: { ...state, standby: true, performanceStandby: false } } }} />)
91
+ expect(html).toContain('Initialized')
92
+ expect(html).toContain('Sealed')
93
+ expect(html).not.toContain('Standby')
94
+ expect(html).not.toContain('Performance standby')
95
+ })
96
+ it('shows reported Vault roles after initialization and unsealing', () => {
97
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, adapter: 'vault', facts: { vault: { initialized: true, sealed: false, standby: true, performanceStandby: false } } }} />)
98
+ expect(html).toContain('Standby')
99
+ expect(html).toContain('Performance standby')
100
+ })
101
+ })
102
+
103
+ it.each(['pod_not_running', 'container_not_running', 'endpoint_port_not_declared', 'unsupported_image', 'ambiguous_target', 'host_network_unsupported', 'cluster_unavailable', 'invalid_target'])('explains %s without exposing a raw code', reason => {
104
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, outcome: 'unavailable', reason }} />)
105
+ expect(html).not.toContain(reason)
106
+ expect(html).toContain('No conclusion about application health')
107
+ })
108
+
109
+
110
+ describe('Vault HA observations', () => {
111
+ it.each([
112
+ { value: true, text: 'Reported healthy' },
113
+ { value: false, text: 'Reported unhealthy' },
114
+ { value: undefined, text: 'Unknown' },
115
+ ])('keeps standby connection $value distinct from unknown', ({ value, text }) => {
116
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, adapter: 'vault', facts: { vault: { initialized: true, sealed: false, standby: true, haConnectionHealthy: value } } }} />)
117
+ expect(html).toContain('Connection to active node')
118
+ expect(html).toContain(text)
119
+ if (value === undefined) expect(html).toContain('Connectivity is unknown')
120
+ else expect(html).not.toContain('Connectivity is unknown')
121
+ expect(html).toContain('other replicas were not checked')
122
+ expect(html).not.toContain('Removal from HA cluster')
123
+ })
124
+ it.each([
125
+ { initialized: false, sealed: true, standby: true },
126
+ { initialized: true, sealed: true, standby: true },
127
+ { initialized: true, sealed: false, standby: false },
128
+ ])('does not present inapplicable HA connection for $initialized/$sealed/$standby', state => {
129
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, adapter: 'vault', facts: { vault: { ...state, haConnectionHealthy: false } } }} />)
130
+ expect(html).not.toContain('Connection to active node')
131
+ expect(html).not.toContain('Reported unhealthy')
132
+ })
133
+ it('keeps performance standby connection evidence applicable', () => {
134
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, adapter: 'vault', facts: { vault: { initialized: true, sealed: false, standby: false, performanceStandby: true, haConnectionHealthy: false } } }} />)
135
+ expect(html).toContain('Connection to active node')
136
+ expect(html).toContain('Reported unhealthy')
137
+ })
138
+ it.each([{ initialized: true, removedFromCluster: true }, { initialized: true, removedFromCluster: false }, { initialized: false, removedFromCluster: false }])('shows removal $removedFromCluster with initialized=$initialized even while sealed', ({ initialized, removedFromCluster }) => {
139
+ const html = renderToStaticMarkup(<ApplicationEvidenceObservation result={{ ...result, adapter: 'vault', facts: { vault: { initialized, sealed: true, standby: true, removedFromCluster } } }} />)
140
+ expect(html).toContain(`<dt>Removal from HA cluster</dt><dd>${removedFromCluster ? 'Reported' : 'Not reported'}</dd>`)
141
+ expect(html).not.toContain('Standby')
142
+ expect(html).not.toContain('Connection to active node')
143
+ })
144
+ })
@@ -0,0 +1,218 @@
1
+ import { useEffect, useRef, useState, useId } from 'react'
2
+ import { useQuery } from '@tanstack/react-query'
3
+ import { AlertBanner } from '@skyhook-io/k8s-ui/components/ui/drawer-components'
4
+ import { SelectMenu } from '@skyhook-io/k8s-ui/components/ui/SelectMenu'
5
+ import { copyText } from '@skyhook-io/k8s-ui/utils/clipboard'
6
+ import { DialogPortal } from '@skyhook-io/k8s-ui/components/ui/DialogPortal'
7
+ import { TimeValue } from '@skyhook-io/k8s-ui/components/ui/ScheduleValue'
8
+ import { Disclosure } from '@skyhook-io/k8s-ui/components/ui/Disclosure'
9
+ import { Tooltip } from '@skyhook-io/k8s-ui/components/ui/Tooltip'
10
+ import { formatMemoryBytes } from '@skyhook-io/k8s-ui/utils/format'
11
+ import { pluralize } from '@skyhook-io/k8s-ui/utils/pluralize'
12
+ import { ApiError, fetchJSON, useClusterInfo, useCapabilities, useRadarFeature } from '../../api/client'
13
+ import { collectApplicationEvidence, type ApplicationEvidenceResult, type EvidenceCandidate, type EvidenceCandidates } from '../../api/application-evidence'
14
+
15
+ const unavailableReasons: Record<string, string> = {
16
+ pod_not_running: 'The selected Pod is no longer running.',
17
+ container_not_running: 'The selected application container is not running.',
18
+ endpoint_port_not_declared: 'The Pod no longer declares the supported application endpoint port.',
19
+ unsupported_image: 'The Pod no longer uses a supported application image.',
20
+ ambiguous_target: 'Radar could not identify one supported application container in this Pod.',
21
+ host_network_unsupported: 'Evidence collection is not supported for Pods using host networking.',
22
+ cluster_unavailable: 'The Kubernetes connection is unavailable.',
23
+ invalid_target: 'The selected Pod identity is incomplete.',
24
+ unsupported_adapter: 'The requested application is not supported.',
25
+ endpoint_denied: 'The application endpoint requires authorization.',
26
+ endpoint_unavailable: 'The application endpoint could not be reached.',
27
+ endpoint_response_unavailable: 'The application endpoint did not return a readable response.',
28
+ port_forward_unavailable: 'Radar could not open a Kubernetes port-forward to this Pod.',
29
+ pod_read_unavailable: 'Radar could not read the selected Pod.',
30
+ pod_recheck_unavailable: 'Radar could not verify the Pod identity after collection.',
31
+ target_changed: 'The selected Pod changed. Select a current Pod before collecting again.',
32
+ collection_busy: 'Other evidence collections are running. Try again shortly.',
33
+ collection_cancelled: 'Collection was cancelled or timed out.',
34
+ response_too_large: 'The endpoint response exceeded the collection size limit.',
35
+ missing_alarm_metrics: 'The response did not include the required RabbitMQ alarm metrics.',
36
+ invalid_alarm_metric: 'The endpoint returned invalid RabbitMQ metrics.',
37
+ ambiguous_alarm_metric: 'The endpoint returned conflicting alarm values.',
38
+ unexpected_shape: 'The response did not match the supported application format.',
39
+ unexpected_http_status: 'The endpoint returned an unsupported HTTP status.',
40
+ redirect_refused: 'The endpoint redirected the request; Radar does not follow redirects.',
41
+ }
42
+ const refreshTargetReasons = new Set(['target_changed', 'pod_not_running', 'container_not_running', 'endpoint_port_not_declared', 'unsupported_image', 'ambiguous_target', 'host_network_unsupported'])
43
+ const applicationNames = { rabbitmq: 'RabbitMQ', nats: 'NATS', vault: 'Vault' }
44
+ type AvailableCandidates = EvidenceCandidates & { context: string }
45
+ interface Props { kind: string; group?: string; namespace: string; name: string; uid: string }
46
+
47
+ export function ApplicationEvidenceAction(props: Props) {
48
+ const { data: cluster } = useClusterInfo()
49
+ const { data: capabilities } = useCapabilities()
50
+ const { guard, gatedKey, support } = useRadarFeature('applicationEvidence')
51
+ const context = cluster?.context
52
+ const subjectKey = `${context}:${props.kind}:${props.group}:${props.namespace}:${props.name}:${props.uid}`
53
+ const permissionRetryTarget = useRef<string | undefined>(undefined)
54
+ const { data, dataUpdatedAt, error, refetch, isFetching } = useQuery({
55
+ queryKey: ['application-evidence-candidates', context, props.kind, props.group, props.namespace, props.name, props.uid, ...gatedKey],
56
+ queryFn: ({ signal }) => guard(() => fetchJSON<EvidenceCandidates>(`/application-evidence/candidates?${new URLSearchParams({ kind: props.kind, group: props.group ?? '', namespace: props.namespace, name: props.name, retryPermissions: String(permissionRetryTarget.current === subjectKey) })}`, signal)),
57
+ enabled: support !== 'unsupported' && !!context && !!props.uid && !!props.namespace && capabilities?.deployment?.mode === 'local',
58
+ placeholderData: previous => previous,
59
+ retry: (failures, failure) => failures < 1 && failure instanceof ApiError && (failure.status === 503 || failure.status === 409),
60
+ staleTime: 30_000,
61
+ refetchOnWindowFocus: false,
62
+ })
63
+ const available = data
64
+ const retry = () => { if (available?.permissionCheckTimedOut || available?.permissionCheckFailed) permissionRetryTarget.current = subjectKey; void refetch() }
65
+ if (support === 'unsupported' || !context || !props.namespace || capabilities?.deployment?.mode !== 'local') return null
66
+ const retryError = error && (permissionRetryTarget.current === subjectKey || available?.enabled && available.context === context && available.subjectUID === props.uid && available.candidates.length > 0) ? <div className="mt-3"><AlertBanner variant="warning" title="Could not refresh application evidence" message={<>{error instanceof Error ? error.message : 'Could not verify application evidence permissions.'} <button type="button" className="text-accent-text hover:underline disabled:opacity-50" disabled={isFetching} onClick={retry}>{isFetching ? 'Checking…' : available?.permissionCheckTimedOut || available?.permissionCheckFailed ? 'Retry permission check' : 'Retry'}</button></>} /></div> : null
67
+ if (!available?.enabled || !available.context || available.context !== context || available.subjectUID !== props.uid) return retryError
68
+ const candidates = error instanceof ApiError && [403, 404, 409, 503].includes(error.status) ? [] : available.candidates
69
+ return <>
70
+ {retryError}
71
+ {!retryError && (available.permissionCheckTimedOut || available.permissionCheckFailed) && <div className="mt-3 text-sm text-theme-text-secondary">Application evidence permissions could not be verified{available.permissionCheckTimedOut ? ' in time' : ''}. <button type="button" className="text-accent-text hover:underline disabled:opacity-50" disabled={isFetching} onClick={retry}>{isFetching ? 'Checking…' : 'Retry permission check'}</button></div>}
72
+ <EvidenceControl key={`${context}:${props.uid}`} data={{ ...available, context: available.context, candidates }} refreshing={isFetching} dataUpdatedAt={dataUpdatedAt} onTargetChanged={retry} />
73
+ </>
74
+ }
75
+
76
+ function EvidenceControl({ data, refreshing, dataUpdatedAt, onTargetChanged }: { data: AvailableCandidates; refreshing: boolean; dataUpdatedAt: number; onTargetChanged: () => void }) {
77
+ const [snapshot, setSnapshot] = useState<AvailableCandidates>()
78
+ const [open, setOpen] = useState(false)
79
+ const [session, setSession] = useState(0)
80
+ const [rejectedAt, setRejectedAt] = useState<number>()
81
+ const current = { ...data, candidates: rejectedAt !== undefined && (rejectedAt === dataUpdatedAt || refreshing) ? [] : data.candidates }
82
+ if (!snapshot && current.candidates.length === 0) return null
83
+ const names = [...new Set(current.candidates.map(item => applicationNames[item.application]))].join(', ')
84
+ return <div className="mt-3">
85
+ {current.candidates.length > 0 && <button type="button" className="text-sm text-accent-text hover:underline disabled:opacity-50" disabled={refreshing} onClick={() => { setSnapshot(current); setSession(value => value + 1); setOpen(true) }}>Collect {names} evidence</button>}
86
+ {snapshot && <EvidenceDialog key={session} open={open} data={snapshot} currentData={current} refreshing={refreshing} onTargetChanged={() => { setRejectedAt(dataUpdatedAt); onTargetChanged() }} onClose={() => setOpen(false)} />}
87
+ </div>
88
+ }
89
+
90
+ function EvidenceDialog({ open, data, currentData, refreshing, onClose, onTargetChanged }: { open: boolean; data: AvailableCandidates; currentData: AvailableCandidates; refreshing: boolean; onClose: () => void; onTargetChanged: () => void }) {
91
+ const titleId = useId()
92
+ const targetId = useId()
93
+ const [selected, setSelected] = useState<EvidenceCandidate | undefined>(data.candidates[0])
94
+ const [useCurrentTargets, setUseCurrentTargets] = useState(false)
95
+ const [result, setResult] = useState<ApplicationEvidenceResult>()
96
+ const [error, setError] = useState<string>()
97
+ const [copied, setCopied] = useState(false)
98
+ const [pending, setPending] = useState(false)
99
+ const request = useRef<AbortController | undefined>(undefined)
100
+ useEffect(() => () => request.current?.abort(), [])
101
+ const choices = useCurrentTargets ? currentData : data
102
+ const candidate = choices.candidates.find(item => item.application === selected?.application && item.target.uid === selected?.target.uid && item.target.container === selected?.target.container)
103
+ const collect = async () => {
104
+ if (!candidate) return
105
+ request.current?.abort()
106
+ const controller = new AbortController()
107
+ request.current = controller
108
+ setPending(true)
109
+ setResult(undefined)
110
+ setCopied(false)
111
+ setError(undefined)
112
+ try {
113
+ const response = await collectApplicationEvidence(candidate, data.context, controller.signal)
114
+ if (!controller.signal.aborted) {
115
+ setResult(response)
116
+ if (response.reason && refreshTargetReasons.has(response.reason)) {
117
+ setSelected(undefined)
118
+ setUseCurrentTargets(true)
119
+ onTargetChanged()
120
+ }
121
+ }
122
+ } catch (e) {
123
+ if (!controller.signal.aborted) setError(e instanceof Error ? e.message : 'Collection failed')
124
+ } finally {
125
+ if (!controller.signal.aborted) setPending(false)
126
+ }
127
+ }
128
+ const close = () => { request.current?.abort(); onClose() }
129
+ return <DialogPortal ariaLabelledBy={titleId} open={open} onClose={close} className="w-[min(92vw,640px)] max-h-[85vh] overflow-y-auto p-5">
130
+ <h2 id={titleId} className="text-lg font-semibold text-theme-text-primary">Collect application evidence</h2>
131
+ <p className="mt-2 text-sm text-theme-text-secondary">Read one Pod’s application endpoint through a temporary Kubernetes port-forward using your current permissions.</p>
132
+ <p className="mt-2 break-all text-xs text-theme-text-tertiary">Context: {data.context}</p>
133
+ <label className="mt-4 block text-sm text-theme-text-primary" htmlFor={targetId}>Pod endpoint</label>
134
+ <SelectMenu id={targetId} ariaLabel="Pod endpoint" className="mt-1" value={candidate ? String(choices.candidates.indexOf(candidate)) : ''} placeholder="Select a current Pod" disabled={pending || useCurrentTargets && refreshing || choices.candidates.length === 0}
135
+ options={choices.candidates.map((item, index) => ({ value: String(index), label: `${applicationNames[item.application]} · ${item.target.namespace}/${item.target.pod} · ${item.target.container}` }))}
136
+ onChange={value => { setSelected(choices.candidates[Number(value)]); setError(undefined); setCopied(false) }} />
137
+ {candidate ? <>
138
+ <p className="mt-2 text-sm text-theme-text-secondary">Collects: {candidate.expectedEvidence.join(', ')}.</p>
139
+ <p className="mt-1 text-xs text-theme-text-tertiary">{candidate.coverage}</p>
140
+ </> : <p className="mt-2 text-sm text-theme-text-secondary">{refreshing ? 'Refreshing available Pods…' : choices.candidates.length > 0 ? 'Select a current Pod before collecting again.' : <>A current Pod endpoint has not been verified. <button type="button" className="text-accent-text hover:underline" onClick={onTargetChanged}>Refresh Pod choices</button></>}</p>}
141
+ {(choices.truncated || choices.coverageLimited) && <p className="mt-2 text-xs text-theme-text-secondary">Discovery or permission limits may exclude endpoints. To inspect another endpoint, open that Pod directly.</p>}
142
+ <p className="mt-2 text-xs text-theme-text-tertiary">Requires a reachable default plaintext endpoint; credentials, TLS and custom ports are not supported.</p>
143
+ {error && <div role="alert" className="mt-4"><AlertBanner variant="error" title="Could not complete the request" message={error} /></div>}
144
+ {result && <ApplicationEvidenceObservation result={result} />}
145
+ <div className="mt-5 flex flex-wrap justify-end gap-2">
146
+ {result && <button type="button" className="btn-brand-muted px-3 py-2 text-sm" onClick={async () => { const success = await copyText(JSON.stringify({ context: data.context, ...result }, null, 2)); setCopied(success); if (!success) setError('Could not copy the observation.'); }}>{copied ? 'Copied' : 'Copy observation'}</button>}
147
+ <button type="button" className="btn-brand-muted px-3 py-2 text-sm" onClick={close}>{pending ? 'Cancel' : 'Close'}</button>
148
+ <button type="button" className="btn-brand px-3 py-2 text-sm" disabled={pending || !candidate} onClick={collect}>{pending ? 'Collecting…' : result ? 'Collect again' : 'Collect evidence'}</button>
149
+ </div>
150
+ </DialogPortal>
151
+ }
152
+
153
+ function RabbitMQMeasurement({ value }: { value: number | undefined }) {
154
+ return <dd className="break-words">{value === undefined ? 'Unknown' : <>
155
+ <span className="block">{formatMemoryBytes(value)}</span>
156
+ <span className="block text-xs text-theme-text-tertiary">{value.toLocaleString()} bytes</span>
157
+ </>}</dd>
158
+ }
159
+
160
+ export function ApplicationEvidenceObservation({ result }: { result: ApplicationEvidenceResult }) {
161
+ const facts = result.outcome === 'observed' ? result.facts : undefined
162
+ const rabbitmq = facts?.rabbitmq
163
+ const nats = facts?.nats
164
+ const vault = facts?.vault
165
+ return <section aria-label="Application observations" className="card-inner mt-4 p-3 text-sm text-theme-text-primary">
166
+ <h3 className="font-semibold">{result.outcome === 'observed' ? 'Endpoint observations' : 'Evidence unavailable'}</h3>
167
+ <p className="mt-1 break-all text-xs text-theme-text-secondary">{result.target.namespace}/{result.target.pod}{result.target.container && ` · ${result.target.container}`}</p>
168
+ <p className="mt-1 text-xs text-theme-text-tertiary"><TimeValue timestamp={result.observedAt} /> · {result.source.replaceAll('_', ' ')}{result.httpStatus !== undefined && ` · Endpoint status: HTTP ${result.httpStatus}`}</p>
169
+ {facts && <p className="mt-2 text-xs text-theme-text-secondary">This Pod at collection time; other replicas were not checked.</p>}
170
+ {result.reason && <p className="mt-2">{unavailableReasons[result.reason] ?? `Collection unavailable (${result.reason}).`} No conclusion about application health can be drawn from unavailable evidence.</p>}
171
+ {rabbitmq && <>
172
+ <dl className="mt-3 grid grid-cols-2 gap-2">
173
+ <dt>Disk alarm</dt><dd>{rabbitmq.diskAlarm ? 'Reported' : 'Not reported'}</dd>
174
+ <dt>Free disk</dt><RabbitMQMeasurement value={rabbitmq.diskAvailableBytes} />
175
+ <dt>Disk alarm below</dt><RabbitMQMeasurement value={rabbitmq.diskWatermarkBytes} />
176
+ <dt>Memory alarm</dt><dd>{rabbitmq.memoryAlarm ? 'Reported' : 'Not reported'}</dd>
177
+ <dt>Memory used (RabbitMQ)</dt><RabbitMQMeasurement value={rabbitmq.memoryUsedBytes} />
178
+ <dt>Memory alarm above</dt><RabbitMQMeasurement value={rabbitmq.memoryWatermarkBytes} />
179
+ </dl>
180
+ <p className="mt-2 text-xs text-theme-text-secondary">Measurements are RabbitMQ’s periodic statistics and can lag the alarm state. Its memory watermark is not the container memory limit; the container can be OOM-killed before this alarm fires. Unknown values were absent or could not be interpreted.</p>
181
+ <p className="mt-2 text-xs text-theme-text-secondary">A disk or memory alarm on another node can block publishers across the cluster.</p>
182
+ </>}
183
+ {vault && <dl className="mt-3 grid grid-cols-2 gap-2">
184
+ <dt>Initialized</dt><dd>{vault.initialized ? 'Yes' : 'No'}</dd>
185
+ <dt>Sealed</dt><dd>{vault.sealed ? 'Yes' : 'No'}</dd>
186
+ {vault.initialized && !vault.sealed && <>
187
+ <dt>Standby</dt><dd>{vault.standby ? 'Yes' : 'No'}</dd>
188
+ {vault.performanceStandby !== undefined && <><dt>Performance standby</dt><dd>{vault.performanceStandby ? 'Yes' : 'No'}</dd></>}
189
+ {(vault.standby || vault.performanceStandby) && <><dt>Connection to active node</dt><dd>{vault.haConnectionHealthy === undefined ? 'Unknown' : vault.haConnectionHealthy ? 'Reported healthy' : 'Reported unhealthy'}</dd></>}
190
+ </>}
191
+ {vault.removedFromCluster !== undefined && <><dt>Removal from HA cluster</dt><dd>{vault.removedFromCluster ? 'Reported' : 'Not reported'}</dd></>}
192
+ </dl>}
193
+ {vault?.initialized && !vault.sealed && (vault.standby || vault.performanceStandby) && vault.haConnectionHealthy === undefined && <p className="mt-2 text-xs text-theme-text-secondary">Vault can omit the heartbeat report after a leader change. Connectivity is unknown.</p>}
194
+ {nats && <div className="mt-3 space-y-2">
195
+ <p>JetStream: {nats.jetStreamEnabled ? 'Enabled' : 'Disabled'}</p>
196
+ <p className="text-xs text-theme-text-secondary">Coverage: {nats.coverage.replaceAll('_', ' ')} · {pluralize(nats.returnedAccounts, 'account')} · {pluralize(nats.returnedStreams, 'stream')} · {pluralize(nats.returnedConsumers, 'consumer')} returned{nats.truncated ? ' · Truncated' : ''}</p>
197
+ {nats.totals && <p>Node reports {pluralize(nats.totals.messages, 'message')} across {pluralize(nats.totals.streams, 'stream')} and {pluralize(nats.totals.consumers, 'consumer')}.</p>}
198
+ {nats.consumers.length > 0 && <div className="overflow-x-auto"><table className="w-full min-w-[480px] text-left text-xs"><thead><tr><th className="pr-3">Account / stream / consumer</th><th className="pr-3">Pending</th><th className="pr-3">Ack pending</th><th>Redelivered</th></tr></thead><tbody>{nats.consumers.map(item => <tr key={JSON.stringify([item.account, item.stream, item.name])}><td className="py-2 pr-3 break-all">{item.account} / {item.stream} / {item.name}</td><td>{item.pending}</td><td>{item.ackPending}</td><td>{item.redelivered}</td></tr>)}</tbody></table></div>}
199
+ {nats.consumers.length > 0 && <p className="text-xs text-theme-text-secondary">Counts are node-reported; a non-leader replica can report zero pending messages.</p>}
200
+ {nats.consumers.length > 0 && <Disclosure summary="Consumer progress" summaryClassName="text-xs text-theme-text-secondary">
201
+ <p className="mt-2 text-xs text-theme-text-secondary">Positions are not lag; one snapshot cannot establish stalled progress. Missing or invalid values are unavailable, not proof of inactivity. Waiting requests apply to pull consumers; zero can also reflect a push consumer or non-leader replica.</p>
202
+ <div className="mt-2 space-y-3">{nats.consumers.map(item => <div key={JSON.stringify([item.account, item.stream, item.name])} className="card-inner p-2 text-xs">
203
+ <p className="break-all font-medium">{item.account} / {item.stream} / {item.name}</p>
204
+ <dl className="mt-2 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-2">
205
+ <dt>Delivered</dt><dd className="break-words">Consumer seq {item.delivered?.consumerSequence ?? 'unavailable'} · Stream seq {item.delivered?.streamSequence ?? 'unavailable'}</dd>
206
+ <dt>Last delivery</dt><dd className="break-words">{item.delivered?.lastActive ? <Tooltip content={item.delivered.lastActive}><span>{new Date(item.delivered.lastActive).toLocaleString()}</span></Tooltip> : 'Unavailable'}</dd>
207
+ <dt>Ack floor</dt><dd className="break-words">Consumer seq {item.ackFloor?.consumerSequence ?? 'unavailable'} · Stream seq {item.ackFloor?.streamSequence ?? 'unavailable'}</dd>
208
+ <dt>Last ack</dt><dd className="break-words">{item.ackFloor?.lastActive ? <Tooltip content={item.ackFloor.lastActive}><span>{new Date(item.ackFloor.lastActive).toLocaleString()}</span></Tooltip> : 'Unavailable'}</dd>
209
+ <dt className="max-w-36">Waiting pull requests on this node</dt><dd>{item.waitingPullRequests ?? 'Unavailable'}</dd>
210
+ </dl>
211
+ </div>)}</div>
212
+ </Disclosure>}
213
+ </div>}
214
+ {result.limitations.length > 0 && <Disclosure summary="Collection limits" className="mt-3" summaryClassName="text-xs text-theme-text-secondary">
215
+ <ul className="mt-2 space-y-1 text-xs text-theme-text-secondary">{result.limitations.map(item => <li key={item}>{item}</li>)}</ul>
216
+ </Disclosure>}
217
+ </section>
218
+ }
@@ -49,7 +49,8 @@ export function updateDemandSearchParam(
49
49
  // demandGroupVerdict synthesizes the one-line answer for the archetypal case:
50
50
  // every evaluated pool ruled the group out. The dominant leading reason across
51
51
  // incompatible pools headlines; the predicate tables below stay the receipts.
52
- // Anything short of all-pools-incompatible keeps the neutral counts line —
52
+ // Anything short of all-pools-incompatible — including a pool Radar could not
53
+ // evaluate — keeps the neutral counts line:
53
54
  // declared compatibility is not a scheduling guarantee, and a synthesized
54
55
  // verdict must not overclaim past what the evidence supports.
55
56
  export function demandGroupVerdict(group: CapacityDemandGroup): {
@@ -58,7 +59,7 @@ export function demandGroupVerdict(group: CapacityDemandGroup): {
58
59
  poolCount: number;
59
60
  } | null {
60
61
  const counts = group.poolEvaluationCounts;
61
- if (counts.declaredCompatible > 0 || counts.incompatible === 0) return null;
62
+ if (counts.declaredCompatible > 0 || counts.incompatible === 0 || counts.unknown > 0) return null;
62
63
  const leading = group.poolEvaluations
63
64
  .filter((e) => e.result === "incompatible" && e.evidence.length > 0)
64
65
  .map((e) => e.evidence[0]);
@@ -0,0 +1,38 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import type { CapacityDemandGroup } from "@skyhook-io/k8s-ui";
3
+ import { demandGroupVerdict } from "./CapacityDemand";
4
+ import { quantityText } from "./shared";
5
+
6
+ function group(counts: { declaredCompatible: number; incompatible: number; unknown: number }): CapacityDemandGroup {
7
+ const incompatible = Array.from({ length: counts.incompatible }, (_, i) => ({
8
+ result: "incompatible",
9
+ evidence: [{ predicate: "requirements", explanation: `pool ${i} requires arm64` }],
10
+ }));
11
+ return { poolEvaluationCounts: counts, poolEvaluations: incompatible } as unknown as CapacityDemandGroup;
12
+ }
13
+
14
+ describe("demandGroupVerdict", () => {
15
+ it("rules a group out when every evaluated pool is incompatible", () => {
16
+ expect(demandGroupVerdict(group({ declaredCompatible: 0, incompatible: 2, unknown: 0 }))?.poolCount).toBe(2);
17
+ });
18
+
19
+ it("gives no verdict while any pool is unknown", () => {
20
+ expect(demandGroupVerdict(group({ declaredCompatible: 0, incompatible: 5, unknown: 1 }))).toBeNull();
21
+ });
22
+ });
23
+
24
+ describe("quantityText", () => {
25
+ it("names GPU, pod and extended quantities", () => {
26
+ const observation = {
27
+ certainty: "exact",
28
+ resources: { cpu: "100m", memory: "32Mi", "nvidia.com/gpu": "2", pods: "1" },
29
+ };
30
+ expect(quantityText(observation as never)).toBe("0.10 cores · 32 MiB · gpu 2 · 1 pod");
31
+ expect(quantityText({ certainty: "exact", resources: { pods: "3", "example.com/fpga": "1" } } as never)).toBe(
32
+ "example.com/fpga 1 · 3 pods",
33
+ );
34
+ expect(quantityText({ certainty: "exact", resources: { "gpu.intel.com/millicores": "500" } } as never)).toBe(
35
+ "gpu.intel.com/millicores 500",
36
+ );
37
+ });
38
+ });
@@ -51,6 +51,7 @@ import {
51
51
  type StatusTone,
52
52
  } from "@skyhook-io/k8s-ui";
53
53
  import { Badge } from "@skyhook-io/k8s-ui/components/ui/Badge";
54
+ import { isGpuCountKey } from "@skyhook-io/k8s-ui/utils/extended-resources";
54
55
  import {
55
56
  formatCPUString,
56
57
  formatMemoryString,
@@ -302,6 +303,16 @@ export function sortedResourceEntries(
302
303
  }
303
304
 
304
305
  /** "8 CPU · 32Gi" style compact one-liner for a quantity observation. */
306
+ // CPU and memory read by their units; every other quantity is a bare number
307
+ // without its resource name.
308
+ function labeledQuantity(resource: string, value: string): string {
309
+ const quantity = formatQuantity(resource, value);
310
+ if (resource === "cpu" || resource === "memory") return quantity;
311
+ if (resource === "pods") return `${quantity} ${quantity === "1" ? "pod" : "pods"}`;
312
+ if (isGpuCountKey(resource)) return `gpu ${quantity}`;
313
+ return `${resource} ${quantity}`;
314
+ }
315
+
305
316
  export function quantityText(
306
317
  observation: CapacityQuantityObservation | undefined,
307
318
  options?: { max?: number },
@@ -312,7 +323,7 @@ export function quantityText(
312
323
  const max = options?.max ?? 4;
313
324
  const shown = entries
314
325
  .slice(0, max)
315
- .map(([resource, value]) => formatQuantity(resource, value));
326
+ .map(([resource, value]) => labeledQuantity(resource, value));
316
327
  if (entries.length > max) shown.push(`+${entries.length - max}`);
317
328
  return shown.join(" · ");
318
329
  }
@@ -129,6 +129,8 @@ export function ApplicationCostTab({
129
129
  state === 'not_found' ||
130
130
  state === 'no_cost_source' ||
131
131
  state === 'source_unavailable' ||
132
+ state === 'metrics_port_forward_disabled' ||
133
+ state === 'kubecost_port_forward_disabled' ||
132
134
  state === 'authentication_error' ||
133
135
  state === 'configuration_mismatch' ||
134
136
  state === 'deployment_configuration_error' ||
@@ -401,6 +403,8 @@ export function getApplicationCostState(
401
403
  reason === 'access_denied' ||
402
404
  reason === 'not_found' ||
403
405
  reason === 'source_unavailable' ||
406
+ reason === 'metrics_port_forward_disabled' ||
407
+ reason === 'kubecost_port_forward_disabled' ||
404
408
  reason === 'authentication_error' ||
405
409
  reason === 'configuration_mismatch' ||
406
410
  reason === 'deployment_configuration_error' ||
@@ -511,6 +511,8 @@ export function kubecostTrendUnavailableMessage(
511
511
  return 'Kubecost rejected Radar’s API key. Check Settings → Cost.'
512
512
  case 'source_unavailable':
513
513
  return 'Radar could not reach Kubecost. Check Settings → Cost.'
514
+ case 'kubecost_port_forward_disabled':
515
+ return 'Automatic port-forwarding is turned off, so Radar can’t reach the Kubecost Aggregator it found in this cluster. Set the Kubecost URL in Settings → Cost.'
514
516
  case 'configuration_mismatch':
515
517
  return 'Kubecost returned data for a different cluster. Check the cluster ID in Settings → Cost.'
516
518
  case 'cost_settings_error':
@@ -96,6 +96,8 @@ export function WorkloadCostTab({ kind, namespace, name }: WorkloadCostTabProps)
96
96
  state === 'not_found' ||
97
97
  state === 'no_cost_source' ||
98
98
  state === 'source_unavailable' ||
99
+ state === 'metrics_port_forward_disabled' ||
100
+ state === 'kubecost_port_forward_disabled' ||
99
101
  state === 'authentication_error' ||
100
102
  state === 'configuration_mismatch' ||
101
103
  state === 'deployment_configuration_error' ||
@@ -307,6 +309,8 @@ export function getWorkloadCostState(
307
309
  reason === 'access_denied' ||
308
310
  reason === 'not_found' ||
309
311
  reason === 'source_unavailable' ||
312
+ reason === 'metrics_port_forward_disabled' ||
313
+ reason === 'kubecost_port_forward_disabled' ||
310
314
  reason === 'authentication_error' ||
311
315
  reason === 'configuration_mismatch' ||
312
316
  reason === 'deployment_configuration_error' ||
@@ -12,6 +12,11 @@ describe('cost source presentation', () => {
12
12
  expect(costConfigurationAction('authentication_error', { ...both, cost: undefined }).label).toBe('Configure cost source')
13
13
  expect(costConfigurationAction('configuration_mismatch', both).section).toBe('cost')
14
14
  })
15
+ it('sends a turned-off port-forward to the integration that needed it', () => {
16
+ const both = { metrics: 'previous', cost: 'previous', explicitCostBackend: true } as const
17
+ expect(costConfigurationAction('metrics_port_forward_disabled', both).section).toBe('prometheus')
18
+ expect(costConfigurationAction('kubecost_port_forward_disabled', both).section).toBe('cost')
19
+ })
15
20
  it('keeps the neutral action and explains reuse in the note', () => {
16
21
  const copy = { metrics: 'copy', explicitCostBackend: false } as const
17
22
  expect(costConfigurationAction('no_prometheus', copy)).toMatchObject({ section: 'prometheus', label: 'Configure metrics' })
@@ -3,6 +3,7 @@ import { previousSettingsNote, type PreviousIntegrationSettings } from '../../ho
3
3
 
4
4
  export function isCostConfigurable(reason?: string): boolean {
5
5
  return reason === 'no_prometheus' || reason === 'no_cost_source' || reason === 'source_unavailable'
6
+ || reason === 'metrics_port_forward_disabled' || reason === 'kubecost_port_forward_disabled'
6
7
  || reason === 'authentication_error' || reason === 'configuration_mismatch'
7
8
  || reason === 'metrics_settings_error' || reason === 'cost_settings_error'
8
9
  }
@@ -34,6 +35,8 @@ export function costConfigurationAction(reason?: CostUnavailableReason, offers?:
34
35
  } {
35
36
  if (reason === 'metrics_settings_error') return { section: 'prometheus', label: 'Review metrics settings' }
36
37
  if (reason === 'cost_settings_error') return { section: 'cost', label: 'Review cost settings' }
38
+ if (reason === 'metrics_port_forward_disabled') return { section: 'prometheus', label: 'Configure metrics' }
39
+ if (reason === 'kubecost_port_forward_disabled') return { section: 'cost', label: 'Configure cost source' }
37
40
  const previousKind = reason === 'no_prometheus'
38
41
  ? offers?.metrics ? 'metrics' : offers?.explicitCostBackend ? 'cost' : undefined
39
42
  : reason === 'no_cost_source'
@@ -119,6 +122,14 @@ export function costIntegrationUnavailableMessage(
119
122
  return settingsAvailable
120
123
  ? 'Kubecost Aggregator is unavailable. Check the URL, network path, and cluster ID in Settings → Cost.'
121
124
  : 'Kubecost Aggregator is unavailable. Update this cluster’s cost-source configuration in the host application or Radar deployment.'
125
+ case 'metrics_port_forward_disabled':
126
+ return settingsAvailable
127
+ ? 'Automatic port-forwarding is turned off, and Prometheus isn’t reachable directly from this machine. Set a metrics URL in Settings → Metrics.'
128
+ : 'Automatic port-forwarding is turned off, and Prometheus isn’t reachable directly. Configure its URL in the host application or Radar deployment.'
129
+ case 'kubecost_port_forward_disabled':
130
+ return settingsAvailable
131
+ ? 'Automatic port-forwarding is turned off, so Radar can’t reach the Kubecost Aggregator it found in this cluster. Set the Kubecost URL in Settings → Cost.'
132
+ : 'Automatic port-forwarding is turned off, so Radar can’t reach the Kubecost Aggregator it found in this cluster. Configure its URL in the host application or Radar deployment.'
122
133
  case 'metrics_settings_error':
123
134
  return 'This cluster’s saved metrics settings need review before cost data can load. Review them in Settings → Metrics.'
124
135
  case 'cost_settings_error':
@@ -2,10 +2,13 @@ import { useState, type ComponentProps } from "react";
2
2
  import { AlertTriangle, Copy, Check } from "lucide-react";
3
3
  import { Markdown } from "../ui/Markdown";
4
4
  import { Tooltip } from "../ui/Tooltip";
5
+ import { useInExampleInvestigation } from "./exampleInvestigation";
5
6
 
6
7
  export function CopyButton({ text, label }: { text: string; label: string }) {
7
8
  const [state, setState] = useState<"idle" | "copied" | "failed">("idle");
9
+ const inExample = useInExampleInvestigation();
8
10
  const copied = state === "copied";
11
+ if (inExample) return null;
9
12
  return (
10
13
  <Tooltip
11
14
  content={
@@ -55,4 +55,21 @@ describe("AgentSetupNotice", () => {
55
55
  expect(html).not.toContain("Install one of these");
56
56
  expect(html).toContain("Check again");
57
57
  });
58
+
59
+ it("links to the example in every setup state that offers it", () => {
60
+ for (const state of ["needs-install", "needs-restart"] as const) {
61
+ expect(render(state)).not.toContain("See an example investigation");
62
+ const html = renderToStaticMarkup(
63
+ <AgentSetupNotice
64
+ setupState={state}
65
+ cliOverride={false}
66
+ checkingAgents={false}
67
+ agentsCheckFailed={false}
68
+ recheckAgents={async () => {}}
69
+ onOpenExample={() => {}}
70
+ />,
71
+ );
72
+ expect(html).toContain("See an example investigation");
73
+ }
74
+ });
58
75
  });