@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
@@ -1,26 +1,63 @@
1
+ import { KueuePendingPosition } from '../../kueue/KueuePendingPosition'
1
2
  import { Boxes } from 'lucide-react'
2
3
  import { KueueWorkloadRenderer as BaseRenderer } from '@skyhook-io/k8s-ui/components/resources/renderers/KueueWorkloadRenderer'
3
- import { getProvisioningRequestStatus, getProvisioningRequestMessage } from '@skyhook-io/k8s-ui/components/resources/resource-utils-kueue'
4
- import { Badge, ResourceLink, Section, type ResourceRef } from '@skyhook-io/k8s-ui'
4
+ import { getProvisioningRequestStatus, getProvisioningRequestMessage, isKueueWorkloadEligibleForPendingPosition } from '@skyhook-io/k8s-ui/components/resources/resource-utils-kueue'
5
+ import { Badge, ResourceLink, Section, type Relationships, type ResourceRef } from '@skyhook-io/k8s-ui'
6
+ import { needsNamespaceLabels } from '@skyhook-io/k8s-ui/components/kueue/eligibility'
7
+ import { KUEUE_GROUP } from '@skyhook-io/k8s-ui/components/kueue/constants'
5
8
  import { useKueueProvisioning } from '../../../api/client'
9
+ import { relatedReadKey, useRelatedObjects, useRelatedReads } from '../../kueue/useRelatedReads'
6
10
 
7
- export function KueueWorkloadRenderer({ data, onNavigate }: { data: any; onNavigate?: (ref: ResourceRef) => void }) {
11
+ // Reads the Workload's admission path as the viewer: its LocalQueue, the
12
+ // ClusterQueue that LocalQueue names, the ClusterQueue holding a reservation
13
+ // when that differs, and the namespace's labels only when a selector needs them.
14
+ function useAdmissionPathReads(data: any) {
15
+ const namespace: string = data.metadata?.namespace ?? ''
16
+ const queueName: string = data.spec?.queueName ?? ''
17
+ const reserved: string = data.status?.admission?.clusterQueue ?? ''
18
+ const flavorNames = [...new Set<string>((data.status?.admission?.podSetAssignments ?? []).flatMap((assignment: any) => Object.values(assignment?.flavors ?? {}).map(String)))]
19
+ const key = relatedReadKey(data, [queueName, reserved, ...flavorNames], ['QuotaReserved', 'Admitted', 'Finished'])
20
+ const localQueue = useRelatedObjects('localqueues', KUEUE_GROUP, namespace, [queueName], !!queueName && !!namespace, key).byName[queueName]
21
+ const configured: string = localQueue?.state === 'found' ? localQueue.object?.spec?.clusterQueue ?? '' : ''
22
+ const names = [...new Set([configured, reserved].filter(Boolean))]
23
+ const queues = useRelatedObjects('clusterqueues', KUEUE_GROUP, undefined, names, names.length > 0, key)
24
+ const flavors = useRelatedObjects('resourceflavors', KUEUE_GROUP, undefined, flavorNames, flavorNames.length > 0, key)
25
+ const configuredRead = configured ? queues.byName[configured] : undefined
26
+ // Eligibility is shown only while unreserved, so a reserved Workload skips the Namespace read.
27
+ const needsLabels = !reserved && configuredRead?.state === 'found' && needsNamespaceLabels(configuredRead.object?.spec?.namespaceSelector)
28
+ const namespaceState = JSON.stringify([key, configured, needsLabels, configuredRead?.state === 'found' ? configuredRead.object?.spec?.namespaceSelector : null])
29
+ const [namespaceRead] = useRelatedReads([{ kind: 'namespaces', name: namespace }], needsLabels && !!namespace, namespaceState)
30
+ return {
31
+ localQueue: queueName ? localQueue : undefined,
32
+ clusterQueues: queues.byName,
33
+ flavors: flavors.byName,
34
+ namespace: needsLabels ? namespaceRead : undefined,
35
+ }
36
+ }
37
+
38
+ // Keyed by UID so moving the drawer to another Workload starts its reads (and their mount time) afresh.
39
+ export function KueueWorkloadRenderer(props: { data: any; onNavigate?: (ref: ResourceRef) => void; relationships?: Relationships }) {
40
+ return <KueueWorkloadReads key={props.data.metadata?.uid} {...props} />
41
+ }
42
+
43
+ function KueueWorkloadReads({ data, onNavigate, relationships }: { data: any; onNavigate?: (ref: ResourceRef) => void; relationships?: Relationships }) {
44
+ const reads = useAdmissionPathReads(data)
8
45
  const namespace = data.metadata?.namespace ?? ''
9
46
  const uid = data.metadata?.uid
10
47
  const hasChecks = (data.status?.admissionChecks?.length ?? 0) > 0
11
48
  const requests = useKueueProvisioning(namespace, data.metadata?.name ?? '', uid, hasChecks)
12
49
  const current = requests.data?.uid === uid ? requests.data : undefined
13
- const provisioning = hasChecks ? <Section title="Provisioning Requests" icon={Boxes} defaultExpanded>
50
+ const provisioning = hasChecks ? <Section variant="card" title="Provisioning Requests" icon={Boxes} defaultExpanded>
14
51
  {requests.error ? <p className="text-sm text-warning-text">Could not observe provisioning requests: {requests.error.message}</p>
15
52
  : !current ? <p className="text-sm text-theme-text-tertiary">Looking for provisioning requests…</p>
16
53
  : !current.installed ? <p className="text-sm text-theme-text-tertiary">The ProvisioningRequest API is not served by this cluster.</p>
17
54
  : current.requests.length === 0 ? <p className="text-sm text-theme-text-tertiary">No retained provisioning requests found on this cluster. A request may not be needed or may have been cleaned up. Check results above retain the controller’s explanation; requests on a MultiKueue worker cluster are not included.</p>
18
- : <div className="space-y-2">
55
+ : <div className="space-y-3">
19
56
  <p className="text-xs text-theme-text-tertiary">Currently retained requests owned by this Workload, not a retry history. Requests may be removed after completion or eviction.</p>
20
57
  {current.requests.map(request => {
21
58
  const status = getProvisioningRequestStatus(request)
22
59
  const message = getProvisioningRequestMessage(request)
23
- return <div key={request.metadata.uid} className="card-inner">
60
+ return <div key={request.metadata.uid} className="border-t border-theme-border pt-3">
24
61
  <div className="flex flex-wrap items-center gap-2 break-all [&_button]:text-left">
25
62
  <ResourceLink kind="provisioningrequests" group="autoscaling.x-k8s.io" namespace={namespace} name={request.metadata.name} onNavigate={onNavigate} />
26
63
  <Badge colorClass={status.color} size="sm">{status.text}</Badge>
@@ -33,5 +70,8 @@ export function KueueWorkloadRenderer({ data, onNavigate }: { data: any; onNavig
33
70
  {current.truncated && <p className="text-xs text-theme-text-tertiary">Showing {current.requests.length} of {current.total} retained requests, newest first.</p>}
34
71
  </div>}
35
72
  </Section> : undefined
36
- return <BaseRenderer data={data} onNavigate={onNavigate} provisioning={provisioning} />
73
+ const pendingPosition = isKueueWorkloadEligibleForPendingPosition(data)
74
+ ? <KueuePendingPosition namespace={namespace} name={data.metadata?.name ?? ''} uid={uid} queueName={data.spec?.queueName} requeueAt={data.status?.requeueState?.requeueAt} />
75
+ : undefined
76
+ return <BaseRenderer pendingPosition={pendingPosition} data={data} onNavigate={onNavigate} provisioning={provisioning} relationships={relationships} reads={reads} />
37
77
  }
@@ -0,0 +1,67 @@
1
+ import { renderToStaticMarkup } from 'react-dom/server'
2
+ import { beforeEach, expect, it, vi } from 'vitest'
3
+ import { OpenTelemetryCollectorRenderer } from './OpenTelemetryCollectorRenderer'
4
+
5
+ const read = vi.hoisted(() => vi.fn())
6
+ vi.mock('../../../api/client', () => ({ useResource: read }))
7
+ const root = { apiVersion: 'opentelemetry.io/v1beta1', kind: 'OpenTelemetryCollector', metadata: { name: 'collector', namespace: 'observe', uid: 'root' }, spec: { mode: 'deployment', config: {} } }
8
+ const reference = { group: 'apps', kind: 'Deployment', namespace: 'observe', name: 'runtime' }
9
+ const workload = { apiVersion: 'apps/v1', kind: 'Deployment', metadata: { namespace: 'observe', ownerReferences: [{ apiVersion: 'opentelemetry.io/v1beta1', kind: 'OpenTelemetryCollector', name: 'collector', uid: 'root', controller: true }] }, spec: { replicas: 0 }, status: {} }
10
+
11
+ beforeEach(() => read.mockReset())
12
+
13
+ it('separates current scaled-to-zero workload state from operator readiness', () => {
14
+ read.mockImplementation((kind: string) => kind === 'opentelemetrycollectors' ? { relationships: { children: [reference], ownership: { children: { complete: true } } } } : { data: workload })
15
+ const html = renderToStaticMarkup(<OpenTelemetryCollectorRenderer data={root} />)
16
+ expect(html).toContain('Current Workloads')
17
+ expect(html).toContain('Deployment / runtime')
18
+ expect(html).toContain('Scaled to 0')
19
+ expect(html).not.toContain('Not currently controlled')
20
+ })
21
+
22
+ it('does not attribute a replaced workload to the current Collector', () => {
23
+ const replaced = structuredClone(workload)
24
+ replaced.metadata.ownerReferences[0].uid = 'old-root'
25
+ read.mockImplementation((kind: string) => kind === 'opentelemetrycollectors' ? { relationships: { children: [reference], ownership: { children: { complete: true } } } } : { data: replaced })
26
+ const html = renderToStaticMarkup(<OpenTelemetryCollectorRenderer data={root} />)
27
+ expect(html).toContain('Not currently controlled')
28
+ expect(html).not.toContain('Scaled to 0')
29
+ })
30
+
31
+ it('keeps unknown evidence and sidecar emptiness neutral and explicit', () => {
32
+ read.mockReturnValue({})
33
+ expect(renderToStaticMarkup(<OpenTelemetryCollectorRenderer data={root} />)).toContain('Owned-workload evidence is unavailable')
34
+ read.mockReturnValue({ relationships: { children: [], ownership: { children: { complete: true, narrowed: true } } } })
35
+ const html = renderToStaticMarkup(<OpenTelemetryCollectorRenderer data={{ ...root, spec: { ...root.spec, mode: 'sidecar' } }} />)
36
+ expect(html).toContain('Sidecar mode runs inside annotated application Pods')
37
+ expect(html).toContain('Only resources you can read are shown')
38
+ })
39
+
40
+ it('bounds automatic workload reads while leaving additional objects followable', () => {
41
+ const children = Array.from({ length: 30 }, (_, index) => ({ ...reference, name: `runtime-${index}` }))
42
+ read.mockImplementation((kind: string) => kind === 'opentelemetrycollectors' ? { relationships: { children, ownership: { children: { complete: true } } } } : { data: workload })
43
+ const html = renderToStaticMarkup(<OpenTelemetryCollectorRenderer data={root} />)
44
+ expect(read).toHaveBeenCalledTimes(4)
45
+ expect(html).toContain('This workload preview is incomplete')
46
+ })
47
+
48
+ it('does not warn about workload coverage because unrelated CRD kinds are uncollected', () => {
49
+ read.mockImplementation((kind: string) => kind === 'opentelemetrycollectors' ? { relationships: { children: [reference], ownership: { children: { complete: false, notChecked: [{ group: 'example.io', kind: 'Widget', reason: 'radar_kind_not_collected' }] } } } } : { data: workload })
50
+ const html = renderToStaticMarkup(<OpenTelemetryCollectorRenderer data={root} />)
51
+ expect(html).toContain('Scaled to 0')
52
+ expect(html).not.toContain('preview is incomplete')
53
+ })
54
+
55
+ it('shows an explicit partial workload preview when an apps inventory is unavailable', () => {
56
+ read.mockReturnValue({ relationships: { children: [], ownership: { children: { complete: false, notChecked: [{ group: 'apps', kind: 'DaemonSet', reason: 'kind_sync_pending' }] } } } })
57
+ expect(renderToStaticMarkup(<OpenTelemetryCollectorRenderer data={root} />)).toContain('This workload preview is incomplete')
58
+ read.mockReturnValue({ isLoading: true })
59
+ expect(renderToStaticMarkup(<OpenTelemetryCollectorRenderer data={root} />)).toContain('Reading owned workloads')
60
+ })
61
+
62
+ it('pauses root and child reads while the resource view is inactive', () => {
63
+ read.mockImplementation((kind: string) => kind === 'opentelemetrycollectors' ? { relationships: { children: [reference], ownership: { children: { complete: true } } } } : { data: workload })
64
+ renderToStaticMarkup(<OpenTelemetryCollectorRenderer data={root} active={false} />)
65
+ expect(read).toHaveBeenCalledTimes(2)
66
+ for (const call of read.mock.calls) expect(call[4]).toMatchObject({ enabled: false, refetchInterval: false })
67
+ })
@@ -0,0 +1,31 @@
1
+ import { OpenTelemetryCollectorRenderer as BaseRenderer } from '@skyhook-io/k8s-ui/components/resources/renderers/OpenTelemetryRenderers'
2
+ import { getWorkloadStatus } from '@skyhook-io/k8s-ui/components/resources/resource-utils'
3
+ import { Badge } from '@skyhook-io/k8s-ui/components/ui/Badge'
4
+ import { healthToSeverity } from '@skyhook-io/k8s-ui/utils/badge-colors'
5
+ import { Property, PropertyList, ResourceLink, Section } from '@skyhook-io/k8s-ui/components/ui/drawer-components'
6
+ import { apiVersionToGroup } from '@skyhook-io/k8s-ui/utils/navigation'
7
+ import type { ResourceRef } from '@skyhook-io/k8s-ui'
8
+ import { useResource } from '../../../api/client'
9
+
10
+ function OwnedWorkload({ root, reference, onNavigate, active }: { root: any; reference: ResourceRef; onNavigate?: (ref: ResourceRef) => void; active: boolean }) {
11
+ const kind = `${reference.kind.toLowerCase()}s`
12
+ const query = useResource<any>(kind, reference.namespace, reference.name, reference.group, { enabled: active, refetchInterval: active ? 30000 : false })
13
+ const workload = query.data
14
+ const owned = root.metadata.uid && workload?.metadata?.namespace === root.metadata.namespace && workload.metadata.ownerReferences?.some((owner: any) => owner.controller === true && apiVersionToGroup(owner.apiVersion) === 'opentelemetry.io' && owner.kind === 'OpenTelemetryCollector' && owner.name === root.metadata.name && owner.uid === root.metadata.uid)
15
+ const status = owned ? getWorkloadStatus(workload, kind) : undefined
16
+ return <Property label={<ResourceLink {...reference} label={`${reference.kind} / ${reference.name}`} onNavigate={onNavigate} />} value={query.error ? 'Could not read workload; open it for details.' : !workload ? 'Reading current status…' : !owned ? 'Not currently controlled by this Collector; status not attributed.' : <Badge severity={healthToSeverity(status!.level)}>{status!.text}</Badge>} />
17
+ }
18
+
19
+ export function OpenTelemetryCollectorRenderer({ data, onNavigate, active = true }: { data: any; onNavigate?: (ref: ResourceRef) => void; active?: boolean }) {
20
+ const root = useResource<any>('opentelemetrycollectors', data.metadata.namespace, data.metadata.name, 'opentelemetry.io', { enabled: active, refetchInterval: active ? 30000 : false })
21
+ const coverage = root.relationships?.ownership
22
+ const children = (root.relationships?.children ?? []).filter(ref => ref.group === 'apps' && ['Deployment', 'StatefulSet', 'DaemonSet'].includes(ref.kind))
23
+ const runtimeGap = coverage?.children.notChecked?.some(gap => !gap.kind || gap.group === 'apps' && ['Deployment', 'StatefulSet', 'DaemonSet'].includes(gap.kind))
24
+ const partial = !coverage || coverage.unavailableReason || runtimeGap || coverage.children.truncated
25
+ return <BaseRenderer data={data} workloadEvidence={<Section title="Current Workloads" defaultExpanded>
26
+ <p className="mb-2 text-xs text-theme-text-tertiary">Workloads this Collector runs. Ready Pods do not confirm that telemetry is delivered.</p>
27
+ {root.isLoading ? <p className="text-sm text-theme-text-secondary">Reading owned workloads…</p> : root.error ? <p className="text-sm text-theme-text-secondary">Could not read owned workloads. Retry or inspect Related Resources.</p> : !coverage ? <p className="text-sm text-theme-text-secondary">Owned-workload evidence is unavailable. Related Resources may provide more detail.</p> : children.length ? <PropertyList>{children.slice(0, 3).map(ref => <OwnedWorkload key={`${ref.group}/${ref.kind}/${ref.namespace}/${ref.name}`} root={data} reference={ref} onNavigate={onNavigate} active={active} />)}</PropertyList> : <p className="text-sm text-theme-text-secondary">No standalone workloads observed{partial ? ' in the available evidence' : ''}. {data.spec?.mode === 'sidecar' ? 'Sidecar mode runs inside annotated application Pods.' : 'Inspect reconciliation and management state if you expected a runtime.'}</p>}
28
+ {(partial || children.length > 3) && <p className="mt-2 text-xs text-theme-text-tertiary">This workload preview is incomplete. Inspect Related Resources for coverage and additional owned objects.</p>}
29
+ {coverage?.children.narrowed && <p className="mt-2 text-xs text-theme-text-tertiary">Only resources you can read are shown.</p>}
30
+ </Section>} />
31
+ }
@@ -1,11 +1,24 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
1
4
  import { renderToStaticMarkup } from 'react-dom/server'
2
5
  import { beforeEach, describe, expect, it, vi } from 'vitest'
3
6
  import { RayClusterRenderer } from './RayClusterRenderer'
4
- const mock = vi.hoisted(() => ({ result: {} as any, calls: [] as any[] }))
5
- vi.mock('../../../api/client', () => ({ useWorkloadPods: (...args: any[]) => { mock.calls.push(args); return mock.result } }))
7
+ const mock = vi.hoisted(() => ({ result: {} as any, calls: [] as any[], canViewLogs: true, opened: [] as any[], support: 'supported' as string, logsUnknown: false, capsFailed: false }))
8
+ vi.mock('../../../api/client', () => ({
9
+ ApiError: class ApiError extends Error { constructor(message: string, public status: number) { super(message) } },
10
+ useWorkloadPods: (...args: any[]) => { mock.calls.push(args); return mock.result },
11
+ useCapabilities: () => ({ data: mock.capsFailed ? undefined : { features: { rayClusterPods: true, podSidecarMarks: true } }, isError: mock.capsFailed }),
12
+ isStableClientError: (e: any) => [400, 403, 404, 409].includes(e?.status),
13
+ useRadarFeature: () => ({ support: mock.support, upgrade: mock.support === 'unsupported' ? { feature: 'RayCluster runtime Pods', minimumVersion: 'v1.15.0' } : null }),
14
+ }))
15
+ vi.mock('../../../contexts/CapabilitiesContext', () => ({ useNamespacedCapabilities: () => ({ canViewLogs: mock.canViewLogs, logsUnknown: mock.logsUnknown }) }))
16
+ vi.mock('../../dock', () => ({ useOpenLogs: () => (opts: any) => mock.opened.push(opts) }))
17
+ ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
6
18
  const root = { apiVersion: 'ray.io/v1', kind: 'RayCluster', metadata: { name: 'cluster', namespace: 'ml', uid: 'current' } }
19
+ const worker = { name: 'cluster-cpu-worker-def', ready: true, containers: ['wait-gcs-ready', 'ray-worker'], containerStatuses: [{ name: 'ray-worker', ready: true, restartCount: 0 }, { name: 'wait-gcs-ready', init: true, ready: true, restartCount: 0 }] }
7
20
  describe('RayCluster host evidence', () => {
8
- beforeEach(() => { mock.result = {}; mock.calls = [] })
21
+ beforeEach(() => { mock.result = {}; mock.calls = []; mock.canViewLogs = true; mock.opened = []; mock.support = 'supported'; mock.logsUnknown = false; mock.capsFailed = false })
9
22
  it('makes one bounded UID-bound query with polling', () => {
10
23
  renderToStaticMarkup(<RayClusterRenderer data={root} />)
11
24
  expect(mock.calls).toEqual([['rayclusters', 'ml', 'cluster', { ownerUID: 'current', limit: 200, refetchInterval: 5000 }]])
@@ -15,4 +28,69 @@ describe('RayCluster host evidence', () => {
15
28
  const html = renderToStaticMarkup(<RayClusterRenderer data={root} />)
16
29
  expect(html).toContain(message); expect(html).not.toContain('No directly owned Pods')
17
30
  })
31
+ it('opens a verified Pod in the logs dock on its application container', () => {
32
+ mock.result = { data: { pods: [worker], total: 1, truncated: false } }
33
+ const host = document.createElement('div')
34
+ const view = createRoot(host)
35
+ act(() => view.render(<RayClusterRenderer data={root} />))
36
+ act(() => host.querySelector<HTMLButtonElement>('[aria-label="Open logs for cluster-cpu-worker-def"]')!.click())
37
+ expect(mock.opened).toEqual([{ namespace: 'ml', podName: 'cluster-cpu-worker-def', containers: ['wait-gcs-ready', 'ray-worker'], containerName: 'ray-worker' }])
38
+ act(() => view.unmount())
39
+ })
40
+ it('opens a Pending worker in the init container it waits on', () => {
41
+ mock.result = { data: { pods: [{ ...worker, phase: 'Pending', containerStatuses: [{ name: 'wait-gcs-ready', init: true, ready: false, restartCount: 0 }, { name: 'ray-worker', ready: false, restartCount: 0 }] }], total: 1, truncated: false } }
42
+ const host = document.createElement('div')
43
+ const view = createRoot(host)
44
+ act(() => view.render(<RayClusterRenderer data={root} />))
45
+ act(() => host.querySelector<HTMLButtonElement>('[aria-label="Open logs for cluster-cpu-worker-def"]')!.click())
46
+ expect(mock.opened.at(-1).containerName).toBe('wait-gcs-ready')
47
+ act(() => view.unmount())
48
+ })
49
+ it('keeps the last Pod list, with its Logs buttons, through a passing refresh failure', async () => {
50
+ const { ApiError } = await import('../../../api/client') as any
51
+ mock.result = { data: { pods: [worker], total: 1, truncated: false }, error: new ApiError('Cluster connection changed; retry the Pod request', 503) }
52
+ const html = renderToStaticMarkup(<RayClusterRenderer data={root} />)
53
+ expect(html).toContain('Open logs for cluster-cpu-worker-def')
54
+ expect(html).toContain('Pod list not refreshed: Cluster connection changed')
55
+ expect(html).not.toContain('Pod evidence unavailable')
56
+ })
57
+ it('offers no log links without permission to read Pod logs, and says so', () => {
58
+ mock.canViewLogs = false
59
+ mock.result = { data: { pods: [worker], total: 1, truncated: false } }
60
+ const html = renderToStaticMarkup(<RayClusterRenderer data={root} />)
61
+ expect(html).not.toContain('Open logs for'); expect(html).toContain('Pod logs need get on pods/log')
62
+ })
63
+ it('keeps log links while the namespace permission is unconfirmed', () => {
64
+ mock.canViewLogs = false
65
+ mock.logsUnknown = true
66
+ mock.result = { data: { pods: [worker], total: 1, truncated: false } }
67
+ expect(renderToStaticMarkup(<RayClusterRenderer data={root} />)).toContain('Open logs for')
68
+ })
69
+ it('keeps log links when the global permission check has failed without an answer', () => {
70
+ mock.canViewLogs = false
71
+ mock.capsFailed = true
72
+ mock.result = { data: { pods: [worker], total: 1, truncated: false } }
73
+ expect(renderToStaticMarkup(<RayClusterRenderer data={root} />)).toContain('Open logs for')
74
+ })
75
+ it('withholds cached Pod evidence after a definitive access denial', async () => {
76
+ const { ApiError } = await import('../../../api/client') as any
77
+ mock.result = { data: { pods: [worker], total: 1, truncated: false }, error: new ApiError('Reading RayCluster Pods requires get rayclusters and list pods', 403) }
78
+ const html = renderToStaticMarkup(<RayClusterRenderer data={root} />)
79
+ expect(html).toContain('Pod evidence unavailable')
80
+ expect(html).not.toContain('Open logs for')
81
+ expect(html).not.toContain('Pod list not refreshed')
82
+ })
83
+ it('names an unsupporting Radar rather than echoing its 400 when support is unknown', async () => {
84
+ const { ApiError } = await import('../../../api/client') as any
85
+ mock.support = 'unknown'
86
+ mock.result = { error: new ApiError('only deployments, statefulsets, daemonsets, rollouts, jobs, and workflows are supported', 400) }
87
+ const html = renderToStaticMarkup(<RayClusterRenderer data={root} />)
88
+ expect(html).toContain('Radar v1.15 and later'); expect(html).not.toContain('only deployments')
89
+ })
90
+ it('does not ask an older Radar for Pods it cannot list, and says which Radar can', () => {
91
+ mock.support = 'unsupported'
92
+ const html = renderToStaticMarkup(<RayClusterRenderer data={root} />)
93
+ expect(mock.calls[0][2]).toBe('')
94
+ expect(html).toContain('RayCluster runtime Pods'); expect(html).toContain('v1.15')
95
+ })
18
96
  })
@@ -1,7 +1,10 @@
1
1
  import { useState } from 'react'
2
2
  import { RayClusterRenderer as BaseRenderer, type RayClusterPodSelection } from '@skyhook-io/k8s-ui/components/resources/renderers/RayClusterRenderer'
3
- import type { ResourceRef } from '@skyhook-io/k8s-ui'
4
- import { useWorkloadPods } from '../../../api/client'
3
+ import type { ResourceRef, WorkloadPodInfo } from '@skyhook-io/k8s-ui'
4
+ import { isStableClientError, useRadarFeature, useWorkloadPods } from '../../../api/client'
5
+ import { useOpenLogs } from '../../dock'
6
+ import { logsContainer } from '@skyhook-io/k8s-ui/components/resources/resource-utils-ray'
7
+ import { rayClusterPodsError, useLogsReadability, useSidecarsMarked } from '../../logs/rayClusterPods'
5
8
 
6
9
  export function RayClusterRenderer(props: { data: any; onNavigate?: (ref: ResourceRef) => void }) {
7
10
  return <RayClusterEvidence key={props.data.metadata.uid} {...props} />
@@ -10,8 +13,20 @@ export function RayClusterRenderer(props: { data: any; onNavigate?: (ref: Resour
10
13
  function RayClusterEvidence({ data, onNavigate }: { data: any; onNavigate?: (ref: ResourceRef) => void }) {
11
14
  const [requestedSelection, setSelection] = useState<RayClusterPodSelection>({})
12
15
  const selection = requestedSelection.workerGroup != null && !(data.spec?.workerGroupSpecs ?? []).some((group: any) => group.groupName === requestedSelection.workerGroup) ? {} : requestedSelection
13
- const query = useWorkloadPods('rayclusters', data.metadata.namespace, data.metadata.uid ? data.metadata.name : '', {
16
+ const { support, upgrade } = useRadarFeature('rayClusterPods')
17
+ const query = useWorkloadPods('rayclusters', data.metadata.namespace, data.metadata.uid && support !== 'unsupported' ? data.metadata.name : '', {
14
18
  ownerUID: data.metadata.uid, ...selection, limit: 200, refetchInterval: 5000,
15
19
  })
16
- return <BaseRenderer data={data} onNavigate={onNavigate} selection={selection} onSelectPods={setSelection} podEvidence={query.data} podsLoading={query.isLoading} podsError={query.error?.message} />
20
+ const logsReadable = useLogsReadability(data.metadata.namespace) !== 'denied'
21
+ // A refresh that fails for a passing reason keeps the last list, as the Logs tab does.
22
+ const kept = query.data && query.error && !isStableClientError(query.error)
23
+ const openLogs = useOpenLogs()
24
+ const sidecarsMarked = useSidecarsMarked()
25
+ const openPodLogs = (pod: WorkloadPodInfo) => openLogs({
26
+ namespace: data.metadata.namespace,
27
+ podName: pod.name,
28
+ containers: pod.containers,
29
+ containerName: logsContainer(pod, sidecarsMarked),
30
+ })
31
+ return <BaseRenderer data={data} onNavigate={onNavigate} selection={selection} onSelectPods={setSelection} podEvidence={query.data} podsLoading={query.isLoading} podsError={kept ? undefined : rayClusterPodsError(query.error, support)} podsNote={kept ? `Pod list not refreshed: ${rayClusterPodsError(query.error, support)}` : undefined} onOpenPodLogs={logsReadable ? openPodLogs : undefined} podLogsNote={logsReadable ? undefined : 'Pod logs need get on pods/log in this namespace.'} podsUpgrade={support === 'unsupported' ? upgrade : null} />
17
32
  }
@@ -1308,7 +1308,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1308
1308
  // source it names may since have gone. A retry detects again first, which
1309
1309
  // also picks another available source, and the first failed connect gets
1310
1310
  // one such retry on its own.
1311
- const handleConnect = useCallback((redetect: boolean) => {
1311
+ const handleConnect = useCallback((redetect: boolean, automatic = false) => {
1312
1312
  setIsConnecting(true)
1313
1313
  setConnectionError(null)
1314
1314
  queryClient.removeQueries({ queryKey: ['traffic-flows'] })
@@ -1324,7 +1324,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1324
1324
  }
1325
1325
  const detected = fresh ? detectSourcesAgain() : Promise.resolve(undefined)
1326
1326
  detected.then(
1327
- () => connectMutation.mutate(undefined, {
1327
+ () => connectMutation.mutate({ automatic }, {
1328
1328
  onSuccess: (data) => {
1329
1329
  if (!data.connected && data.error) {
1330
1330
  fail(data.error)
@@ -1355,7 +1355,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1355
1355
  useEffect(() => {
1356
1356
  if (wizardState === 'ready' && !hasAutoConnectedRef.current && !isConnecting) {
1357
1357
  hasAutoConnectedRef.current = true
1358
- handleConnect(false)
1358
+ handleConnect(false, true)
1359
1359
  }
1360
1360
  }, [wizardState, isConnecting, handleConnect])
1361
1361
 
@@ -0,0 +1,23 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { expect, it, vi } from 'vitest'
5
+ import { bestScore, useCommandItems } from './command-items'
6
+ vi.mock('../../api/client', () => ({ useNamespaces: () => ({ data: [] }), useContexts: () => ({ data: [] }) }))
7
+ vi.mock('../../api/apiResources', () => ({ CORE_RESOURCES: [], useAPIResources: () => ({ data: [{ group: 'apiextensions.k8s.io', kind: 'CustomResourceDefinition', name: 'customresourcedefinitions', verbs: ['list'] }, { group: '', kind: 'Pod', name: 'pods', verbs: ['list'] }] }) }))
8
+ ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true
9
+ it('uses the shared CRD aliases in command items', () => {
10
+ let scores: number[] = []
11
+ function Probe() {
12
+ const cb = { onNavigateView: vi.fn(), onNavigateKind: vi.fn(), onSwitchContext: vi.fn(), onSetNamespaces: vi.fn(), onToggleTheme: vi.fn() }
13
+ const items = useCommandItems(cb)
14
+ scores = items.filter(i => i.category === 'Resource Kinds').map(i => bestScore(i, 'crd'))
15
+ return null
16
+ }
17
+ const host = document.createElement('div'); const root = createRoot(host)
18
+ act(() => root.render(<Probe />))
19
+ expect(scores).toHaveLength(2)
20
+ expect(scores[0]).toBeGreaterThan(0)
21
+ expect(scores[1]).toBe(0)
22
+ act(() => root.unmount())
23
+ })
@@ -1,3 +1,4 @@
1
+ import { resourceSearchAliases } from "@skyhook-io/k8s-ui/utils/api-resources";
1
2
  import { useMemo } from "react";
2
3
  import {
3
4
  Home,
@@ -184,7 +185,7 @@ export function useCommandItems(cb: CommandItemCallbacks): CommandItem[] {
184
185
  category: "Resource Kinds",
185
186
  icon: getResourceIcon(r.kind),
186
187
  action: () => cb.onNavigateKind(r.name, r.group),
187
- searchTerms: [r.name, r.kind],
188
+ searchTerms: [r.name, r.kind, ...resourceSearchAliases(r)],
188
189
  priorityBonus: groupPriorityBonus(r.group),
189
190
  });
190
191
  }
@@ -0,0 +1,61 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5
+ import type { ContextInfo } from '../types'
6
+
7
+ const mocks = vi.hoisted(() => ({
8
+ mutateAsync: vi.fn(),
9
+ setFailedSwitch: vi.fn(),
10
+ startSwitch: vi.fn(),
11
+ }))
12
+ vi.mock('../api/client', () => ({
13
+ useSwitchContext: () => ({ mutateAsync: mocks.mutateAsync, isPending: false, isError: false, error: null }),
14
+ fetchSessionCounts: async () => ({ portForwards: 0 }),
15
+ SwitchContextError: class extends Error {},
16
+ }))
17
+ vi.mock('../context/ContextSwitchContext', () => ({
18
+ useContextSwitch: () => ({
19
+ startSwitch: mocks.startSwitch,
20
+ endSwitch: vi.fn(),
21
+ setOpenAfterSwitch: vi.fn(),
22
+ setFailedSwitch: mocks.setFailedSwitch,
23
+ }),
24
+ }))
25
+ vi.mock('./ui/Toast', () => ({ useToast: () => ({ showError: vi.fn() }) }))
26
+ vi.mock('./dock', () => ({ useDock: () => ({ tabs: [] }) }))
27
+
28
+ const { useContextSwitchFlow } = await import('./useContextSwitchFlow')
29
+
30
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
31
+ let root: Root
32
+ const seen = vi.fn<(flow: ReturnType<typeof useContextSwitchFlow>) => void>()
33
+ const flow = () => seen.mock.lastCall![0]
34
+
35
+ function Probe() {
36
+ seen(useContextSwitchFlow())
37
+ return null
38
+ }
39
+
40
+ beforeEach(() => {
41
+ vi.clearAllMocks()
42
+ root = createRoot(document.createElement('div'))
43
+ act(() => root.render(<Probe />))
44
+ })
45
+ afterEach(() => act(() => root.unmount()))
46
+
47
+ const ctx = (name: string, isCurrent: boolean) => ({ name, cluster: name, user: 'u', namespace: '', isCurrent }) as ContextInfo
48
+
49
+ describe('useContextSwitchFlow', () => {
50
+ it('picking the cluster you are still on dismisses a refused switch without switching', async () => {
51
+ await act(() => flow().requestSwitch(ctx('current', true)))
52
+ expect(mocks.setFailedSwitch).toHaveBeenCalledWith(null)
53
+ expect(mocks.startSwitch).not.toHaveBeenCalled()
54
+ expect(mocks.mutateAsync).not.toHaveBeenCalled()
55
+ })
56
+
57
+ it('picking another cluster still switches', async () => {
58
+ await act(() => flow().requestSwitch(ctx('staging', false)))
59
+ expect(mocks.mutateAsync).toHaveBeenCalledWith({ name: 'staging' })
60
+ })
61
+ })
@@ -1,7 +1,7 @@
1
1
  import { useState, type ReactNode } from 'react'
2
2
  import { AlertTriangle } from 'lucide-react'
3
3
  import { pluralize } from '@skyhook-io/k8s-ui'
4
- import { useSwitchContext, fetchSessionCounts, type SessionCounts } from '../api/client'
4
+ import { useSwitchContext, fetchSessionCounts, SwitchContextError, type SessionCounts } from '../api/client'
5
5
  import { useContextSwitch } from '../context/ContextSwitchContext'
6
6
  import { useToast } from './ui/Toast'
7
7
  import { useDock } from './dock'
@@ -13,6 +13,12 @@ function shouldSuppressSwitchErrorToast(error: unknown): boolean {
13
13
  return message.includes('cluster connection failed:')
14
14
  }
15
15
 
16
+ // A switch the server refused before leaving the current cluster, because the
17
+ // new one didn't answer. Those show the full connection error screen.
18
+ function refusedBeforeLeaving(error: unknown): error is SwitchContextError & { errorType: string } {
19
+ return error instanceof SwitchContextError && !!error.errorType
20
+ }
21
+
16
22
  interface PendingSwitch {
17
23
  context: ContextInfo
18
24
  openAfter?: SelectedResource
@@ -24,7 +30,7 @@ interface PendingSwitch {
24
30
  // live. Callers render `confirmDialog`.
25
31
  export function useContextSwitchFlow() {
26
32
  const switchContext = useSwitchContext()
27
- const { startSwitch, endSwitch, setOpenAfterSwitch } = useContextSwitch()
33
+ const { startSwitch, endSwitch, setOpenAfterSwitch, setFailedSwitch } = useContextSwitch()
28
34
  const { showError } = useToast()
29
35
  const { tabs } = useDock()
30
36
  const [pending, setPending] = useState<PendingSwitch | null>(null)
@@ -48,7 +54,9 @@ export function useContextSwitchFlow() {
48
54
  endSwitch()
49
55
  // Backend may not transition to StateDisconnected on client-side errors
50
56
  // (network, timeout) — without this toast the user gets no feedback.
51
- if (!shouldSuppressSwitchErrorToast(error)) {
57
+ if (refusedBeforeLeaving(error)) {
58
+ setFailedSwitch({ context: context.name, error: error.message, errorType: error.errorType })
59
+ } else if (!shouldSuppressSwitchErrorToast(error)) {
52
60
  const message = error instanceof Error ? error.message : 'Unknown error'
53
61
  showError('Failed to switch context', message)
54
62
  }
@@ -56,7 +64,12 @@ export function useContextSwitchFlow() {
56
64
  }
57
65
 
58
66
  const requestSwitch = async (context: ContextInfo, openAfter?: SelectedResource) => {
59
- if (context.isCurrent || switchContext.isPending) return
67
+ if (switchContext.isPending) return
68
+ // Picking the cluster you're still on dismisses a refused switch's screen.
69
+ if (context.isCurrent) {
70
+ setFailedSwitch(null)
71
+ return
72
+ }
60
73
  // Active sessions (port forwards from API + terminal tabs from dock) get
61
74
  // a confirmation prompt — switching contexts kills both.
62
75
  try {
@@ -142,6 +155,10 @@ export function useContextSwitchFlow() {
142
155
  requestSwitch,
143
156
  isPending: switchContext.isPending,
144
157
  error: switchContext.isError ? switchContext.error : null,
158
+ // The picker's inline line is for failures that don't get the full screen.
159
+ errorText: switchContext.isError && switchContext.error && !refusedBeforeLeaving(switchContext.error)
160
+ ? switchContext.error.message
161
+ : null,
145
162
  confirmDialog,
146
163
  }
147
164
  }
@@ -95,17 +95,24 @@ describe('composeReleaseNotes', () => {
95
95
 
96
96
  it('turns highlights past the cards into lines ahead of the improvements, within the line cap', () => {
97
97
  const notes = composeReleaseNotes([
98
- entry('v1.16.0', [7, 7, 7, 7, 7, 2], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']),
98
+ entry('v1.16.0', [7, 7, 7, 7, 7, 7, 7, 2], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']),
99
99
  entry('v1.15.0', [1], ['old']),
100
100
  ])
101
101
  expect(notes.highlights).toHaveLength(MAX_CARDS)
102
102
  expect(notes.lines).toHaveLength(MAX_LINES)
103
- expect(notes.lines.slice(0, 2).map(l => l.text)).toEqual(['v1.16.0-5', 'v1.15.0-0'])
103
+ expect(notes.lines.slice(0, 2).map(l => l.text)).toEqual(['v1.16.0-7', 'v1.15.0-0'])
104
104
  expect(notes.lines.map(l => l.text)).not.toContain('old')
105
105
  })
106
106
 
107
- it('scores the dialog by the cards it shows', () => {
107
+ it('scores the dialog by the strongest cards it shows', () => {
108
108
  expect(composeReleaseNotes([entry('v1.16.0', [4, 4, 4, 4, 4, 10])]).score).toBe(10 + 4 * 4)
109
+ expect(composeReleaseNotes([entry('v1.16.0', [5, 3, 3, 3, 3, 3, 3])]).score).toBe(5 + 3 * 4)
110
+ })
111
+
112
+ it("doesn't count cards past the strongest five toward opening", () => {
113
+ const notes = composeReleaseNotes([entry('v1.16.0', [4, 4, 4, 4, 4, 4, 4])])
114
+ expect(notes.highlights).toHaveLength(MAX_CARDS)
115
+ expect(notes.score).toBeLessThan(AUTO_OPEN_SCORE)
109
116
  })
110
117
  })
111
118
 
@@ -19,6 +19,7 @@ import {
19
19
  type ComposedHighlight,
20
20
  type ComposedNotes,
21
21
  type ReleaseNotes,
22
+ MAX_CARDS,
22
23
  } from './releaseNotes'
23
24
  import type { UsageDataStatus } from '../../api/usage-data'
24
25
  import { UsageDataAsk } from '../usage-data/UsageDataAsk'
@@ -276,8 +277,11 @@ export function WhatsNew({ onNavigate, usageData }: WhatsNewProps) {
276
277
 
277
278
  if (isCloud) return null
278
279
 
280
+ // A full grid wraps most descriptions a line longer at the default width.
281
+ const width = view?.notes.highlights.length === MAX_CARDS ? 'w-[840px]' : 'w-[760px]'
282
+
279
283
  return (
280
- <DialogPortal open={open} onClose={close} ariaLabelledBy={titleId} className="w-[760px] max-w-[calc(100vw-2rem)] max-h-[min(840px,calc(100vh-4rem))] flex flex-col overflow-hidden rounded-xl">
284
+ <DialogPortal open={open} onClose={close} ariaLabelledBy={titleId} className={clsx(width, 'max-w-[calc(100vw-2rem)] max-h-[min(980px,calc(100vh-4rem))] flex flex-col overflow-hidden rounded-xl')}>
281
285
  {view && (
282
286
  <WhatsNewContent
283
287
  titleId={titleId}
@@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
7
7
  import { Megaphone } from 'lucide-react'
8
8
  import type { WhatsNewState } from '../../api/client'
9
9
  import { openWhatsNew, useWhatsNewStatus, WhatsNew } from './WhatsNew'
10
- import { RELEASE_NOTES, type ReleaseNotes } from './releaseNotes'
10
+ import { MAX_CARDS, RELEASE_NOTES, type ReleaseNotes } from './releaseNotes'
11
11
 
12
12
  Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
13
13
 
@@ -275,6 +275,20 @@ describe('WhatsNew', () => {
275
275
  expect(status.current.unread).toBe(true)
276
276
  })
277
277
 
278
+ it('widens the dialog only for a full set of cards', async () => {
279
+ serverState = { currentVersion: 'v1.15.0', storage: 'server', seenVersion: 'v1.14.1', priorInstall: true }
280
+ await render('/')
281
+ expect(document.querySelector('.w-\\[760px\\]')).not.toBeNull()
282
+ expect(document.querySelector('.w-\\[840px\\]')).toBeNull()
283
+ })
284
+
285
+ it('gives a full set of cards the wider dialog', async () => {
286
+ setCatalog({ ...HEADLINE, highlights: Array.from({ length: MAX_CARDS }, (_, i) => card(`card-${i}`, `Card ${i}`, 9)) })
287
+ serverState = { currentVersion: 'v1.15.0', storage: 'server', seenVersion: 'v1.14.1', priorInstall: true }
288
+ await render('/')
289
+ expect(document.querySelector('.w-\\[840px\\]')).not.toBeNull()
290
+ })
291
+
278
292
  it('composes the releases a user skipped, leading with the strongest', async () => {
279
293
  setCatalog(HEADLINE, QUIET)
280
294
  serverState = { currentVersion: 'v1.16.0', storage: 'server', seenVersion: 'v1.14.1', priorInstall: true }
@@ -300,11 +314,11 @@ describe('WhatsNew', () => {
300
314
  expect(seenPosts).toEqual([])
301
315
  })
302
316
 
303
- it.each(['', '=v1.19', '=1.19', '=v1.19.0'])('previews v1.19 on a Git development build with ?whats-new%s', async suffix => {
317
+ it.each(['', '=v1.20', '=1.20', '=v1.20.0'])('previews v1.20 on a Git development build with ?whats-new%s', async suffix => {
304
318
  setCatalog(...SHIPPED)
305
319
  serverState = { currentVersion: 'v1.18.0-113-gb49561b78', storage: 'server', seenVersion: 'v1.18.0', priorInstall: true }
306
320
  await render(`/resources/pods?whats-new${suffix}`)
307
- expect(dialog()?.textContent).toContain("What's new in Radar v1.19")
321
+ expect(dialog()?.textContent).toContain("What's new in Radar v1.20")
308
322
  expect(dialog()?.textContent).toContain(SHIPPED[0].highlights[0].title)
309
323
  await clickGotIt()
310
324
  expect(seenPosts).toEqual([])