@skyhook-io/radar-app 1.21.2 → 1.21.4

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 (103) hide show
  1. package/README.md +11 -0
  2. package/package.json +2 -2
  3. package/src/App.tsx +53 -28
  4. package/src/api/actions.test.ts +11 -0
  5. package/src/api/actions.ts +5 -0
  6. package/src/api/apiResources.navigation.test.tsx +58 -0
  7. package/src/api/apiResources.ts +22 -16
  8. package/src/api/client.diagnostics.test.ts +52 -0
  9. package/src/api/client.triggerCronJob.test.tsx +49 -0
  10. package/src/api/client.ts +140 -120
  11. package/src/api/connectionBinding.test.tsx +82 -0
  12. package/src/api/connectionBinding.ts +52 -0
  13. package/src/api/contextSwitch.test.ts +11 -0
  14. package/src/api/contextSwitch.ts +58 -0
  15. package/src/api/radarFeatures.ts +6 -0
  16. package/src/api/vulnerabilities.export.test.ts +44 -0
  17. package/src/api/vulnerabilities.ts +73 -4
  18. package/src/components/ConnectionErrorView.tsx +13 -0
  19. package/src/components/ContextSwitchActions.tsx +43 -0
  20. package/src/components/ContextSwitcher.tsx +13 -6
  21. package/src/components/SwitchAwareConnectionError.tsx +2 -2
  22. package/src/components/audit/VulnerabilitiesView.test.tsx +177 -0
  23. package/src/components/audit/VulnerabilitiesView.tsx +197 -48
  24. package/src/components/cost/ApplicationCostTab.test.ts +16 -0
  25. package/src/components/cost/ApplicationCostTab.tsx +41 -9
  26. package/src/components/cost/CostTrendChart.tsx +25 -2
  27. package/src/components/cost/CostTrendWithheld.render.test.tsx +105 -0
  28. package/src/components/cost/CostView.tsx +10 -2
  29. package/src/components/cost/CostViewTabs.test.tsx +18 -0
  30. package/src/components/cost/CostViewTabs.tsx +14 -22
  31. package/src/components/cost/WorkloadCostTab.test.ts +15 -0
  32. package/src/components/cost/WorkloadCostTab.tsx +42 -8
  33. package/src/components/cost/source.test.ts +16 -1
  34. package/src/components/cost/source.ts +34 -0
  35. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +35 -0
  36. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +16 -1
  37. package/src/components/dock/NodeTerminalTab.test.tsx +4 -2
  38. package/src/components/dock/NodeTerminalTab.tsx +8 -8
  39. package/src/components/dock/TerminalTab.test.tsx +12 -1
  40. package/src/components/dock/TerminalTab.tsx +6 -3
  41. package/src/components/home/CostCard.test.tsx +49 -0
  42. package/src/components/home/CostCard.tsx +98 -63
  43. package/src/components/home/mcpToolCatalog.ts +1 -0
  44. package/src/components/resource/DatadogRightsizingPanel.test.tsx +118 -0
  45. package/src/components/resource/DatadogRightsizingPanel.tsx +68 -0
  46. package/src/components/resource/DatadogWorkloadCharts.tsx +149 -0
  47. package/src/components/resource/HPACharts.render.test.tsx +42 -0
  48. package/src/components/resource/HPACharts.tsx +34 -1
  49. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +126 -3
  50. package/src/components/resource/PrometheusChartsGrid.tsx +58 -25
  51. package/src/components/resource/RestartChart.render.test.tsx +72 -0
  52. package/src/components/resource/RestartChart.tsx +31 -3
  53. package/src/components/resource/RightsizingPanel.access.test.tsx +24 -0
  54. package/src/components/resource/RightsizingStrip.render.test.tsx +44 -0
  55. package/src/components/resource/RightsizingStrip.test.ts +1 -188
  56. package/src/components/resource/RightsizingStrip.tsx +27 -300
  57. package/src/components/resource/WorkloadMetricsSection.render.test.tsx +22 -0
  58. package/src/components/resource/WorkloadMetricsSection.tsx +14 -4
  59. package/src/components/resource/nameMatchedScope.ts +39 -0
  60. package/src/components/resources/pod-file-upload.ts +3 -0
  61. package/src/components/resources/renderers/CAPIClusterRenderer.tsx +5 -2
  62. package/src/components/resources/renderers/LonghornVolumeRenderer.test.tsx +104 -0
  63. package/src/components/resources/renderers/LonghornVolumeRenderer.tsx +31 -0
  64. package/src/components/rightsizing/RightsizingScanLink.tsx +22 -0
  65. package/src/components/rightsizing/RightsizingScanView.tsx +65 -528
  66. package/src/components/rightsizing/model.test.ts +20 -9
  67. package/src/components/rightsizing/model.ts +17 -176
  68. package/src/components/rightsizing/notices.test.tsx +30 -29
  69. package/src/components/traffic/TrafficGraph.export.test.tsx +57 -0
  70. package/src/components/traffic/TrafficGraph.tsx +9 -4
  71. package/src/components/traffic/TrafficView.layoutUnavailable.test.tsx +1 -0
  72. package/src/components/traffic/TrafficView.tsx +17 -2
  73. package/src/components/ui/DiagnosticsOverlay.test.ts +3 -2
  74. package/src/components/ui/DiagnosticsOverlay.tsx +23 -13
  75. package/src/components/ui/command-items.ts +3 -4
  76. package/src/components/useContextSwitchFlow.test.tsx +9 -0
  77. package/src/components/useContextSwitchFlow.tsx +43 -5
  78. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.test.tsx +30 -1
  79. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.tsx +3 -2
  80. package/src/components/vulnerabilities/parts.test.ts +59 -3
  81. package/src/components/vulnerabilities/parts.tsx +199 -5
  82. package/src/components/workload/WorkloadRightsizingSource.test.tsx +83 -0
  83. package/src/components/workload/WorkloadView.test.ts +22 -1
  84. package/src/components/workload/WorkloadView.tsx +57 -16
  85. package/src/context/ConnectionContext.test.ts +1 -0
  86. package/src/context/ConnectionContext.tsx +58 -15
  87. package/src/context/ConnectionProvider.connectionId.test.tsx +92 -0
  88. package/src/context/ConnectionProvider.retry.test.tsx +174 -1
  89. package/src/context/ContextSwitchContext.tsx +15 -1
  90. package/src/context/NavCustomization.tsx +6 -3
  91. package/src/hooks/useDesktopDownload.test.tsx +57 -0
  92. package/src/hooks/useDesktopDownload.ts +31 -9
  93. package/src/hooks/useEventSource.test.tsx +85 -0
  94. package/src/hooks/useEventSource.ts +43 -16
  95. package/src/hooks/useResetViewsOnContextChange.test.tsx +34 -0
  96. package/src/hooks/useResetViewsOnContextChange.ts +27 -0
  97. package/src/index.ts +3 -0
  98. package/src/integrations/resourceHosts.test.tsx +1 -1
  99. package/src/integrations/resourceHosts.tsx +2 -0
  100. package/src/utils/navigation.ts +1 -15
  101. package/src/utils/page-links.ts +6 -0
  102. package/src/components/rightsizing/presentation.test.ts +0 -150
  103. package/src/components/rightsizing/presentation.ts +0 -109
@@ -1,12 +1,7 @@
1
1
  import { describe, expect, it } from 'vitest'
2
2
  import type { RightsizingScanResponse, RightsizingRow } from '../../api/client'
3
- import {
4
- calculateImpact,
5
- classifyRows,
6
- flattenScanResults,
7
- isActionableClass,
8
- scanClassCounts,
9
- } from './model'
3
+ import { calculateImpact, classifyRows, matchesResultClass, scanClassCounts } from '@skyhook-io/k8s-ui/components/rightsizing/results-model'
4
+ import { flattenScanResults } from './model'
10
5
 
11
6
  function metric(overrides: Partial<RightsizingRow> = {}): RightsizingRow {
12
7
  return {
@@ -29,7 +24,7 @@ function response(
29
24
  replicas = 1,
30
25
  namespace = 'shop',
31
26
  scaledToZero = false,
32
- ): RightsizingScanResponse {
27
+ ): RightsizingScanResponse & { workloads: NonNullable<RightsizingScanResponse['workloads']> } {
33
28
  return {
34
29
  scanId: 'rs_test', scanStatus: 'finished', deadlineAt: '2026-09-19T10:03:00Z',
35
30
  state: 'complete',
@@ -57,6 +52,10 @@ function response(
57
52
  }
58
53
 
59
54
  describe('rightsizing scan model', () => {
55
+ it('can render a retained unavailable scan from a disconnected spoke', () => {
56
+ expect(flattenScanResults({ ...response([]), state: 'unavailable', workloads: null })).toEqual([])
57
+ })
58
+
60
59
  it('prioritizes reliability guidance and explicit safety review', () => {
61
60
  expect(
62
61
  classifyRows([
@@ -193,7 +192,7 @@ describe('rightsizing scan model', () => {
193
192
  expect(rows[0].cpu).toBe(cpu)
194
193
  expect(rows[0].memory).toBe(memory)
195
194
  expect(scanClassCounts(rows)[rows[0].classification]).toBe(1)
196
- const actions = rows.filter((row) => isActionableClass(row.classification))
195
+ const actions = rows.filter((row) => matchesResultClass(row, 'actions'))
197
196
  expect(actions).toHaveLength(classification === 'need_data' ? 0 : 1)
198
197
  })
199
198
  })
@@ -354,3 +353,15 @@ describe('pod-level requests', () => {
354
353
  expect(calculateImpact(rows, 2)).toMatchObject({ cpuChange: 0, memoryChange: 0 })
355
354
  })
356
355
  })
356
+
357
+ it('finds independent actions on one container without counting a guarded proposal as capacity', () => {
358
+ const rows = flattenScanResults(response([
359
+ metric({ fit: 'under_requested', recommendedRequest: '250m', recommendedRequestValue: 0.25,
360
+ currentRequestValue: 0.1, decision: { status: 'review', reasons: ['hpa_evidence_unavailable'] } }),
361
+ metric({ resource: 'memory', fit: 'oversized', recommendedRequest: '128Mi',
362
+ recommendedRequestValue: 128 * 1024 ** 2, currentRequestValue: 256 * 1024 ** 2, decision: { status: 'actionable' } }),
363
+ ]));
364
+ expect(scanClassCounts(rows)).toEqual({ increase: 1, review: 1, reduction: 1, in_range: 0, need_data: 0 });
365
+ expect(matchesResultClass(rows[0], 'actions')).toBe(true);
366
+ expect(rows[0].impact.cpuChange).toBe(0);
367
+ });
@@ -1,183 +1,24 @@
1
- import type { RightsizingScanResponse, RightsizingRow } from '../../api/client'
1
+ import type { RightsizingScanResponse } from '../../api/client'
2
+ import {
3
+ compareScanResults,
4
+ workloadResultRows,
5
+ type RightsizingResultRow,
6
+ isSizingSystemNamespace,
7
+ } from '@skyhook-io/k8s-ui/components/rightsizing/results-model'
2
8
 
3
- export type ScanClass = 'increase' | 'reduction' | 'review' | 'in_range' | 'need_data'
9
+ export type { ScanClass } from '@skyhook-io/k8s-ui/components/rightsizing/results-model'
4
10
 
5
- export interface RightsizingImpact {
6
- replicas: number
7
- cpuChange: number
8
- memoryChange: number
9
- }
10
-
11
- export interface RightsizingScanRow {
12
- id: string
13
- kind: string
14
- namespace: string
15
- name: string
16
- container: string
17
- replicas: number
18
- cpu?: RightsizingRow
19
- memory?: RightsizingRow
20
- classification: ScanClass
21
- impact: RightsizingImpact
11
+ export interface RightsizingScanRow extends RightsizingResultRow {
22
12
  system: boolean
23
- scaledToZero: boolean
24
- }
25
-
26
- const CLASS_RANK: Record<ScanClass, number> = {
27
- increase: 1,
28
- reduction: 2,
29
- review: 3,
30
- need_data: 4,
31
- in_range: 5,
32
- }
33
-
34
- const MIN_CPU_REDUCTION = 0.05
35
- const MIN_MEMORY_REDUCTION = 64 * 1024 * 1024
36
-
37
- export function classifyRows(
38
- rows: RightsizingRow[],
39
- replicas = 1,
40
- scaledToZero = false,
41
- ): ScanClass {
42
- const evidenced = rows.filter((row) => !row.queryError && row.fit !== 'insufficient_history')
43
- if (evidenced.length === 0) return 'need_data'
44
- if (scaledToZero) return 'review'
45
- if (
46
- evidenced.some(
47
- (row) =>
48
- (row.fit === 'under_requested' || row.fit === 'missing_request') && row.recommendedRequest,
49
- )
50
- )
51
- return 'increase'
52
- if (evidenced.some(needsManualReview)) return 'review'
53
- const impact = calculateImpact(evidenced, replicas)
54
- if (-impact.cpuChange >= MIN_CPU_REDUCTION || -impact.memoryChange >= MIN_MEMORY_REDUCTION)
55
- return 'reduction'
56
- return evidenced.length === rows.length ? 'in_range' : 'need_data'
57
- }
58
-
59
- function needsManualReview(row: RightsizingRow): boolean {
60
- return (
61
- row.hpaManaged ||
62
- needsSafetyReview(row) ||
63
- (isReduction(row) && row.bursty === true) ||
64
- row.recommendationReason === 'hpa_evidence_unavailable' ||
65
- row.recommendationReason === 'oom_evidence_unavailable' ||
66
- // Mirrors ManualReviewReasons: Radar does not size a pod-level request.
67
- row.fit === 'pod_level_request'
68
- )
69
- }
70
-
71
- function needsSafetyReview(row: RightsizingRow): boolean {
72
- return (
73
- row.currentPodOOM === true ||
74
- row.windowOomEvidence === true ||
75
- row.limitConflict === true ||
76
- (isReduction(row) && (row.throttleRatio ?? 0) >= 0.1)
77
- )
78
- }
79
-
80
- function scanPriority(row: RightsizingScanRow): number {
81
- if (
82
- !row.scaledToZero &&
83
- [row.cpu, row.memory].some(
84
- (resource) =>
85
- resource &&
86
- !resource.queryError &&
87
- resource.fit !== 'insufficient_history' &&
88
- needsSafetyReview(resource),
89
- )
90
- )
91
- return 0
92
- return CLASS_RANK[row.classification]
93
- }
94
-
95
- function isReduction(row: RightsizingRow): boolean {
96
- return (
97
- row.recommendedRequestValue != null &&
98
- row.currentRequestValue != null &&
99
- row.recommendedRequestValue < row.currentRequestValue
100
- )
101
- }
102
-
103
- export function calculateImpact(rows: RightsizingRow[], replicas: number): RightsizingImpact {
104
- const count = Math.max(replicas, 0)
105
- let cpuChange = 0
106
- let memoryChange = 0
107
- for (const row of rows) {
108
- if (row.recommendedRequestValue == null || needsManualReview(row)) continue
109
- const change = (row.recommendedRequestValue - (row.currentRequestValue ?? 0)) * count
110
- if (row.resource === 'cpu') cpuChange += change
111
- else memoryChange += change
112
- }
113
- return { replicas: count, cpuChange, memoryChange }
114
13
  }
115
14
 
116
15
  export function flattenScanResults(scan: RightsizingScanResponse): RightsizingScanRow[] {
117
- const result: RightsizingScanRow[] = []
118
- for (const workload of scan.workloads ?? []) {
119
- const byContainer = new Map<string, RightsizingRow[]>()
120
- for (const row of workload.rows ?? []) {
121
- const rows = byContainer.get(row.container) ?? []
122
- rows.push(row)
123
- byContainer.set(row.container, rows)
124
- }
125
- for (const [container, rows] of byContainer) {
126
- const replicas = workload.replicas ?? 1
127
- result.push({
128
- id: `${workload.kind}/${workload.namespace}/${workload.name}/${container}`,
129
- kind: workload.kind,
130
- namespace: workload.namespace,
131
- name: workload.name,
132
- container,
133
- replicas,
134
- cpu: rows.find((row) => row.resource === 'cpu'),
135
- memory: rows.find((row) => row.resource === 'memory'),
136
- classification: classifyRows(rows, replicas, workload.scaledToZero),
137
- impact: calculateImpact(rows, replicas),
138
- system: isSystemNamespace(workload.namespace),
139
- scaledToZero: workload.scaledToZero,
140
- })
141
- }
142
- }
143
- return result.sort(
144
- (a, b) =>
145
- scanPriority(a) - scanPriority(b) ||
146
- impactScore(b) - impactScore(a) ||
147
- a.namespace.localeCompare(b.namespace) ||
148
- a.name.localeCompare(b.name) ||
149
- a.container.localeCompare(b.container),
150
- )
151
- }
152
-
153
- function impactScore(row: RightsizingScanRow): number {
154
- return Math.max(
155
- Math.abs(row.impact.cpuChange) / MIN_CPU_REDUCTION,
156
- Math.abs(row.impact.memoryChange) / MIN_MEMORY_REDUCTION,
157
- )
158
- }
159
-
160
- export function scanClassCounts(rows: RightsizingScanRow[]): Record<ScanClass, number> {
161
- const counts: Record<ScanClass, number> = {
162
- increase: 0,
163
- reduction: 0,
164
- review: 0,
165
- in_range: 0,
166
- need_data: 0,
167
- }
168
- for (const row of rows) counts[row.classification]++
169
- return counts
170
- }
171
-
172
- export function isActionableClass(value: ScanClass): boolean {
173
- return value === 'increase' || value === 'reduction' || value === 'review'
174
- }
175
-
176
- function isSystemNamespace(namespace: string): boolean {
177
- return (
178
- namespace === 'kube-system' ||
179
- namespace === 'kube-public' ||
180
- namespace === 'kube-node-lease' ||
181
- namespace.startsWith('gke-managed-')
182
- )
16
+ return (scan.workloads ?? [])
17
+ .flatMap((workload) =>
18
+ workloadResultRows(workload).map((row) => ({
19
+ ...row,
20
+ system: isSizingSystemNamespace(row.namespace),
21
+ })),
22
+ )
23
+ .sort(compareScanResults)
183
24
  }
@@ -1,7 +1,7 @@
1
1
  import { renderToStaticMarkup } from 'react-dom/server'
2
2
  import { describe, expect, it } from 'vitest'
3
- import type { RightsizingRow, RightsizingScanResponse } from '../../api/client'
4
- import { FitWhy, ScanNotices, ScanSummary } from './RightsizingScanView'
3
+ import type { RightsizingScanResponse } from '../../api/client'
4
+ import { ScanNotices, ScanSummary, ScanUnavailableState } from './RightsizingScanView'
5
5
 
6
6
  const scan: RightsizingScanResponse = {
7
7
  scanId: 'rs_test', scanStatus: 'finished', deadlineAt: '2026-09-19T10:03:00Z',
@@ -105,33 +105,6 @@ describe('rightsizing scan notices', () => {
105
105
  })
106
106
  })
107
107
 
108
- describe('rightsizing evidence explanation', () => {
109
- const row: RightsizingRow = {
110
- container: 'app',
111
- resource: 'cpu',
112
- fit: 'insufficient_history',
113
- confidence: 'low',
114
- coverage: 0,
115
- sampleCount: 0,
116
- expectedSamples: 2017,
117
- hpaManaged: false,
118
- hpaEvidenceAvailable: true,
119
- oomEvidenceAvailable: false,
120
- }
121
-
122
- it('distinguishes failed queries from successfully measured short history', () => {
123
- const failed = renderToStaticMarkup(
124
- <FitWhy label="CPU" row={{ ...row, queryError: 'usage query failed' }} />,
125
- )
126
- expect(failed).toContain('Metrics could not be queried')
127
- expect(failed).not.toContain('0.0 days')
128
- expect(failed).not.toContain('Wait for more runtime history')
129
- const short = renderToStaticMarkup(<FitWhy label="CPU" row={row} />)
130
- expect(short).toContain('0.0 days')
131
- expect(short).toContain('Wait for more runtime history')
132
- })
133
- })
134
-
135
108
  describe('rightsizing scope and coverage summary', () => {
136
109
  const counts = {
137
110
  increase: 1,
@@ -174,3 +147,31 @@ describe('rightsizing scope and coverage summary', () => {
174
147
  expect(html).toContain('All visible namespaces')
175
148
  })
176
149
  })
150
+
151
+ describe('rightsizing scan withheld cluster scope', () => {
152
+ it('shows the note once instead of the unavailable message', () => {
153
+ const html = renderToStaticMarkup(
154
+ <ScanUnavailableState
155
+ result={{
156
+ ...scan,
157
+ state: 'unavailable',
158
+ reason: 'cluster_scope_withheld',
159
+ warnings: [{ code: 'cluster_scope_withheld', message: 'This metrics store holds several clusters.' }],
160
+ clusterScope: { state: 'label_missing', note: "The container_cpu_usage_seconds_total series don't carry this cluster's label." },
161
+ }}
162
+ onRun={() => {}}
163
+ />,
164
+ )
165
+ expect(html.match(/role="note"/g)).toHaveLength(1)
166
+ expect(html).toContain("don&#x27;t carry this cluster&#x27;s label")
167
+ expect(html).not.toContain('Rightsizing is unavailable')
168
+ })
169
+
170
+ it('keeps the unavailable message for other reasons and older Radar', () => {
171
+ const html = renderToStaticMarkup(
172
+ <ScanUnavailableState result={{ ...scan, state: 'unavailable', reason: 'owner_metrics_missing' }} onRun={() => {}} />,
173
+ )
174
+ expect(html).toContain('Rightsizing is unavailable')
175
+ expect(html).not.toContain('role="note"')
176
+ })
177
+ })
@@ -0,0 +1,57 @@
1
+ // @vitest-environment jsdom
2
+ import { act, useState, type ReactNode } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
5
+ import type { Edge, Node } from '@xyflow/react'
6
+ import { ToastProvider } from '@skyhook-io/k8s-ui'
7
+ import type { AggregatedFlow } from '../../types'
8
+ import { TrafficGraph } from './TrafficGraph'
9
+
10
+ vi.mock('./TrafficView', () => ({ isClusterAddon: () => false }))
11
+ vi.mock('elkjs/lib/elk.bundled.js', () => ({
12
+ default: class {
13
+ async layout(graph: { children: Node[] }) {
14
+ return { ...graph, children: graph.children.map((node, index) => ({ ...node, x: index * 250, y: 0 })) }
15
+ }
16
+ },
17
+ }))
18
+ vi.mock('@xyflow/react', () => ({
19
+ ReactFlow: ({ children }: { children: ReactNode }) => <div>{children}</div>,
20
+ Background: () => null,
21
+ Controls: ({ children }: { children: ReactNode }) => <div data-testid="controls">{children}</div>,
22
+ Handle: () => null,
23
+ MarkerType: { ArrowClosed: 'arrowclosed' },
24
+ Position: { Left: 'left', Right: 'right' },
25
+ useNodesState: (initial: Node[]) => [...useState(initial), vi.fn()],
26
+ useEdgesState: (initial: Edge[]) => [...useState(initial), vi.fn()],
27
+ useReactFlow: () => ({ fitView: vi.fn(), getNodes: () => [], getNodesBounds: vi.fn() }),
28
+ useStore: (selector: (s: { domNode: null }) => unknown) => selector({ domNode: null }),
29
+ }))
30
+
31
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
32
+ let container: HTMLDivElement
33
+ let root: Root
34
+ beforeEach(() => {
35
+ container = document.createElement('div')
36
+ document.body.appendChild(container)
37
+ root = createRoot(container)
38
+ })
39
+ afterEach(() => {
40
+ act(() => root.unmount())
41
+ container.remove()
42
+ })
43
+
44
+ const flow: AggregatedFlow = {
45
+ source: { name: 'web', namespace: 'default', kind: 'Pod' }, destination: { name: 'api', namespace: 'default', kind: 'Service' },
46
+ protocol: 'tcp', port: 80, connections: 3, bytesSent: 10, bytesRecv: 20, bytesByProtocol: { tcp: { bytesSent: 10, bytesRecv: 20 } }, flowCount: 1, lastSeen: '',
47
+ }
48
+
49
+ it('offers image export in the graph controls', async () => {
50
+ await act(async () => root.render(
51
+ <ToastProvider>
52
+ <TrafficGraph flows={[flow]} onLayoutUnavailable={vi.fn()} windowSeconds={300} />
53
+ </ToastProvider>,
54
+ ))
55
+ const controls = container.querySelector('[data-testid="controls"]')!
56
+ expect(controls.querySelector('button[aria-label="Export as image"]')).not.toBeNull()
57
+ })
@@ -19,7 +19,7 @@ import type { ELK } from 'elkjs/lib/elk.bundled.js'
19
19
  import type { AggregatedFlow } from '../../types'
20
20
  import { clsx } from 'clsx'
21
21
  import { X, ArrowRight, Globe, Server, Activity, Puzzle, Crosshair } from 'lucide-react'
22
- import { MiddleEllipsis, PaneLoader } from '@skyhook-io/k8s-ui'
22
+ import { GraphExportButton, MiddleEllipsis, PaneLoader } from '@skyhook-io/k8s-ui'
23
23
  import { isClusterAddon, type AddonMode } from './TrafficView'
24
24
  import { SEVERITY_BADGE, SEVERITY_DOT, SEVERITY_TEXT } from '@skyhook-io/k8s-ui/utils/badge-colors'
25
25
  import { getNamespaceColor } from '../../utils/traffic-colors'
@@ -87,6 +87,8 @@ interface TrafficGraphProps {
87
87
  /** Seconds the byte figures cover, so an edge measured only in bytes can be
88
88
  * labelled with its throughput. */
89
89
  windowSeconds: number
90
+ /** Saves an exported image instead of a browser download (desktop app). */
91
+ onDownloadBlob?: (blob: Blob, filename: string) => void
90
92
  }
91
93
 
92
94
  // Phase 2.1: Calculate edge width based on connection count (log scale)
@@ -372,7 +374,8 @@ export function TrafficNode({ data }: { data: TrafficNodeData }) {
372
374
  // Legend component
373
375
  function TrafficLegend() {
374
376
  return (
375
- <div className="absolute bottom-2 left-2 bg-theme-surface border border-theme-border rounded-lg p-2.5 text-xs z-10 shadow-lg max-w-xs">
377
+ // Clears the graph controls, which sit in the same corner.
378
+ <div className="absolute bottom-2 left-14 bg-theme-surface border border-theme-border rounded-lg p-2.5 text-xs z-10 shadow-lg max-w-xs">
376
379
  <div className="font-medium text-theme-text-primary mb-2">Legend</div>
377
380
  <div className="space-y-1.5">
378
381
  <div className="flex items-center gap-2">
@@ -1165,7 +1168,7 @@ function trafficEdgeId(sourceId: string, destId: string, flow: AggregatedFlow):
1165
1168
  return `${sourceId}->${destId}:${flow.port}${flow.directionUnknown ? ':unoriented' : ''}`
1166
1169
  }
1167
1170
 
1168
- export function TrafficGraph({ flows, hotPathThreshold = 0, showNamespaceGroups = false, serviceCategories, addonMode = 'show', trafficSource = '', selection: viewSelection, onSelectionChange, onFocus, focusedId, onLayoutUnavailable, windowSeconds }: TrafficGraphProps) {
1171
+ export function TrafficGraph({ flows, hotPathThreshold = 0, showNamespaceGroups = false, serviceCategories, addonMode = 'show', trafficSource = '', selection: viewSelection, onSelectionChange, onFocus, focusedId, onLayoutUnavailable, windowSeconds, onDownloadBlob }: TrafficGraphProps) {
1169
1172
  // Beyla is rate-based too: its Connections field carries requests per second,
1170
1173
  // not a connection count, so it needs the same label Istio gets.
1171
1174
  const isRateBased = isRateBasedSource(trafficSource)
@@ -1815,7 +1818,9 @@ export function TrafficGraph({ flows, hotPathThreshold = 0, showNamespaceGroups
1815
1818
  nodesConnectable={false}
1816
1819
  >
1817
1820
  <Background />
1818
- <Controls />
1821
+ <Controls>
1822
+ <GraphExportButton defaultFilename="traffic" title="Export traffic" onDownloadBlob={onDownloadBlob} />
1823
+ </Controls>
1819
1824
  <FitViewOnChange shouldFitViewRef={shouldFitViewRef} layoutedNodes={layoutedNodes} />
1820
1825
  </ReactFlow>
1821
1826
 
@@ -9,6 +9,7 @@ import type { UseTrafficRecordsOptions } from '../../api/traffic'
9
9
 
10
10
  Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
11
11
 
12
+ vi.mock('../../hooks/useDesktopDownload', () => ({ useDesktopBlobDownload: () => undefined }))
12
13
  vi.mock('elkjs/lib/elk.bundled.js', () => {
13
14
  throw new Error('Failed to fetch dynamically imported module')
14
15
  })
@@ -13,11 +13,13 @@ import { TrafficSourcePill } from './TrafficSourcePill'
13
13
  import { TrafficGraphTooLarge } from './TrafficGraphTooLarge'
14
14
  import { TrafficGraphUnavailable } from './TrafficGraphUnavailable'
15
15
  import { useQueryClient } from '@tanstack/react-query'
16
- import { useDock } from '../dock'
16
+ import { useDock, useDockReservedHeight } from '../dock'
17
17
  import { AlertBanner, EmptyState, PaneLoader, FreshnessControl } from '@skyhook-io/k8s-ui'
18
18
  import { useConnection } from '../../context/ConnectionContext'
19
+ import { useDesktopBlobDownload } from '../../hooks/useDesktopDownload'
19
20
  import { Tooltip } from '../ui/Tooltip'
20
21
  import { SEVERITY_TEXT } from '@skyhook-io/k8s-ui/utils/badge-colors'
22
+ import { DURATION_DOCK } from '@skyhook-io/k8s-ui/utils/animation'
21
23
  import { matchesStatusRanges, bucketsFromCounts, bucketsFromStatus, isRateBasedSource, keepAvailable, effectiveThreshold, volumeUnit, type VolumeUnit, isExternalKind, groupAddonFlows, mergeFlowVolume, coverageLabel, type GraphFlow, endpointPair, graphEndpoint, graphEndpointId, mergeRawPairs, mergedEdgePort, selectedEdgeMatcher, selectionRawPairs, selectionMatch, graphSize, GRAPH_DRAW_BUDGET, GRAPH_DRAW_CEILING, parseFocus, focusParam, focusId, focusNeighborhood, touchesFocus, endpointSummaries, namespaceSummaries, verdictChoices, type TrafficFocus, warningRetries, warningBannerTitle, emptyWarningHeadline, rateWindowSeconds } from './trafficFilters'
22
24
 
23
25
  // Where a warning about which cluster the traffic belongs to points: how the map
@@ -390,6 +392,7 @@ interface TrafficViewProps {
390
392
 
391
393
  export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
392
394
  const { connection } = useConnection()
395
+ const desktopBlobDownload = useDesktopBlobDownload()
393
396
  const [wizardState, setWizardState] = useState<TrafficWizardState>('detecting')
394
397
  const [timeRange, setTimeRange] = useState<string>('5m')
395
398
  const [hideSystem, setHideSystem] = useState(true)
@@ -429,6 +432,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
429
432
  const [layoutUnavailable, setLayoutUnavailable] = useState(false)
430
433
  const dock = useDock()
431
434
  const graphPaneRef = useRef<HTMLDivElement>(null)
435
+ const dockInset = useDockReservedHeight()
432
436
 
433
437
  const focusValue = searchParams.get('focus')
434
438
  const focus = useMemo(() => parseFocus(focusValue), [focusValue])
@@ -1330,7 +1334,17 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1330
1334
  />
1331
1335
 
1332
1336
  {/* Main content area */}
1333
- <div ref={graphPaneRef} className="flex-1 relative min-w-0">
1337
+ {/* The dock spans only this pane (see setLeftOffset), so the pane
1338
+ shrinks above it rather than the app-wide DockSpacer shrinking the
1339
+ filter sidebar too. */}
1340
+ <div
1341
+ ref={graphPaneRef}
1342
+ className="flex-1 relative min-w-0"
1343
+ style={{
1344
+ marginBottom: dockInset,
1345
+ transition: dock.isResizing ? 'none' : `margin-bottom ${DURATION_DOCK}ms cubic-bezier(0.4, 0, 0.2, 1)`,
1346
+ }}
1347
+ >
1334
1348
  {/* Floating controls — overlaid on graph like topology view */}
1335
1349
  {(() => {
1336
1350
  const availableSources = sourcesData?.detected.filter(s => s.status === 'available') || []
@@ -1513,6 +1527,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1513
1527
  focusedId={focusKey}
1514
1528
  onLayoutUnavailable={setLayoutUnavailable}
1515
1529
  windowSeconds={rateWindowSeconds(timeRange)}
1530
+ onDownloadBlob={desktopBlobDownload}
1516
1531
  />
1517
1532
  </>
1518
1533
  )}
@@ -117,9 +117,10 @@ describe('formatForGitHub kubeconfig section', () => {
117
117
 
118
118
  expect(md).toContain('Mode: `multi-source` | Files: 3 | Directory Files: 2 | Contexts (after source resolution): 7')
119
119
  expect(md).toContain('KUBECONFIG Captured From Shell: Yes | Ignored: Yes — directories-only configuration')
120
+ expect(md).toContain('Current Context Uses Exec: No')
120
121
  })
121
122
 
122
- it('omits directory counts for environment path lists', () => {
123
+ it('omits directory counts and unobserved current-context auth', () => {
123
124
  const md = formatForGitHub({
124
125
  ...baseSnapshot,
125
126
  kubeconfig: {
@@ -130,11 +131,11 @@ describe('formatForGitHub kubeconfig section', () => {
130
131
  enrichedFromShell: false,
131
132
  kubeconfigEnvIgnored: false,
132
133
  kubeconfigEnvIgnoredReason: '',
133
- currentContextUsesExec: true,
134
134
  },
135
135
  }, undefined, false)
136
136
 
137
137
  expect(md).toContain('Mode: `multi-env` | Files: 2 | Contexts (after source resolution): 4')
138
138
  expect(md).not.toContain('Directory Files:')
139
+ expect(md).not.toContain('Current Context Uses Exec:')
139
140
  })
140
141
  })
@@ -19,7 +19,7 @@ interface DiagnosticsOverlayProps {
19
19
  }
20
20
 
21
21
  export function DiagnosticsOverlay({ onClose, isOpen = true, focus, communityUrl }: DiagnosticsOverlayProps) {
22
- const { data, isLoading, error } = useDiagnostics(true)
22
+ const { data, isLoading, isFetching, error, refetch } = useDiagnostics(true)
23
23
  const [copied, setCopied] = useState<'json' | 'formatted' | null>(null)
24
24
  const [reportOpened, setReportOpened] = useState(false)
25
25
  const timelineRef = useRef<HTMLDivElement>(null)
@@ -124,7 +124,11 @@ export function DiagnosticsOverlay({ onClose, isOpen = true, focus, communityUrl
124
124
  <div className="text-sm text-theme-text-tertiary text-center py-8">Loading diagnostics…</div>
125
125
  )}
126
126
  {error && (
127
- <div className="text-sm text-red-400 text-center py-8">Failed to load diagnostics: {(error as Error).message}</div>
127
+ <div role="alert" className="text-sm text-center py-8 space-y-3">
128
+ <p className="text-theme-text-primary">{error.message}</p>
129
+ {data && <p className="text-theme-text-secondary">Showing the snapshot from {new Date(data.timestamp).toLocaleTimeString()}.</p>}
130
+ <button type="button" className="btn-brand px-3 py-1.5 text-sm font-medium" disabled={isFetching} onClick={() => void refetch()}>{isFetching ? 'Retrying…' : 'Retry diagnostics'}</button>
131
+ </div>
128
132
  )}
129
133
  {data && (
130
134
  <>
@@ -156,8 +160,8 @@ export function DiagnosticsOverlay({ onClose, isOpen = true, focus, communityUrl
156
160
 
157
161
  {/* Footer */}
158
162
  <div className="flex items-center gap-2 px-5 py-3 border-t border-theme-border shrink-0">
159
- <CopyButton label="Copy as Markdown" onClick={() => copyToClipboard('formatted')} copied={copied === 'formatted'} />
160
- <CopyButton label="Copy Raw JSON" onClick={() => copyToClipboard('json')} copied={copied === 'json'} />
163
+ <CopyButton disabled={!data} label="Copy as Markdown" onClick={() => copyToClipboard('formatted')} copied={copied === 'formatted'} />
164
+ <CopyButton disabled={!data} label="Copy Raw JSON" onClick={() => copyToClipboard('json')} copied={copied === 'json'} />
161
165
  <div className="flex-1" />
162
166
  {communityUrl && (
163
167
  <a
@@ -236,6 +240,7 @@ function ConnectionSection({ data }: { data: DiagnosticsSnapshot }) {
236
240
  <Row label="State" value={c.state} warn={warn} />
237
241
  <Row label="Context" value={c.context} />
238
242
  {c.clusterName && <Row label="Cluster" value={c.clusterName} />}
243
+ {c.progressMessage && <Row label="Progress" value={c.progressMessage} />}
239
244
  {c.error && <Row label="Error" value={c.error} warn />}
240
245
  {c.errorType && <Row label="Error Type" value={c.errorType} warn />}
241
246
  </Section>
@@ -266,10 +271,9 @@ function KubeconfigSection({ data }: { data: DiagnosticsSnapshot }) {
266
271
  value={k.kubeconfigEnvIgnored ? `Yes — ${k.kubeconfigEnvIgnoredReason}` : 'No'}
267
272
  warn={k.kubeconfigEnvIgnored}
268
273
  />
269
- <Row
270
- label="Current Context Uses Exec"
271
- value={k.currentContextUsesExec ? 'Yes' : 'No'}
272
- />
274
+ {k.currentContextUsesExec !== undefined && (
275
+ <Row label="Current Context Uses Exec" value={k.currentContextUsesExec ? 'Yes' : 'No'} />
276
+ )}
273
277
  {present.length > 0 && (
274
278
  <Row label="Exec Plugins on PATH" value={present.join(', ')} />
275
279
  )}
@@ -289,6 +293,7 @@ function ClusterSection({ data }: { data: DiagnosticsSnapshot }) {
289
293
  const c = data.cluster
290
294
  return (
291
295
  <Section title="Cluster">
296
+ {c.observedAt && <Row label="Last observed" value={new Date(c.observedAt).toLocaleString()} />}
292
297
  <Row label="Platform" value={c.platform} />
293
298
  <Row label="Kubernetes" value={c.kubernetesVersion} />
294
299
  <Row label="Nodes" value={c.nodeCount} />
@@ -385,7 +390,7 @@ function InformersSection({ data }: { data: DiagnosticsSnapshot }) {
385
390
  return (
386
391
  <Section title="Informers" warn={sectionWarn}>
387
392
  <Row label="Typed" value={inf.typedCount} />
388
- <Row label="Dynamic (CRDs)" value={inf.dynamicCount} />
393
+ <Row label="Dynamic (CRDs)" value={inf.dynamicCount ?? 'Unavailable'} />
389
394
  {sync && (
390
395
  <>
391
396
  <Row
@@ -648,12 +653,13 @@ function ConfigSection({ data }: { data: DiagnosticsSnapshot }) {
648
653
 
649
654
  // --- Copy button ---
650
655
 
651
- function CopyButton({ label, onClick, copied }: { label: string; onClick: () => void; copied: boolean }) {
656
+ function CopyButton({ label, onClick, copied, disabled }: { label: string; onClick: () => void; copied: boolean; disabled: boolean }) {
652
657
  return (
653
658
  <button
659
+ disabled={disabled}
654
660
  onClick={onClick}
655
661
  className={clsx(
656
- 'flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md transition-colors',
662
+ 'flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md transition-colors disabled:opacity-50',
657
663
  copied
658
664
  ? 'bg-green-500/20 text-green-400'
659
665
  : 'bg-theme-elevated text-theme-text-secondary hover:text-theme-text-primary hover:bg-theme-elevated/80'
@@ -679,6 +685,7 @@ export function formatForGitHub(data: DiagnosticsSnapshot, frontendPerf?: K8sUIP
679
685
  lines.push(`### Connection`)
680
686
  lines.push(`- State: \`${c.state}\``)
681
687
  lines.push(`- Context: \`${c.context}\``)
688
+ if (c.progressMessage) lines.push(`- Progress: ${c.progressMessage}`)
682
689
  if (c.clusterName) lines.push(`- Cluster: \`${c.clusterName}\``)
683
690
  if (c.error) lines.push(`- Error: ${c.error}`)
684
691
  if (c.errorType) lines.push(`- Error Type: \`${c.errorType}\``)
@@ -693,7 +700,9 @@ export function formatForGitHub(data: DiagnosticsSnapshot, frontendPerf?: K8sUIP
693
700
  : ''
694
701
  lines.push(`- Mode: \`${k.mode || '(not initialized)'}\` | Files: ${k.fileCount}${directoryFiles} | Contexts (after source resolution): ${k.contextCount}`)
695
702
  lines.push(`- KUBECONFIG Captured From Shell: ${k.enrichedFromShell ? 'Yes' : 'No'} | Ignored: ${k.kubeconfigEnvIgnored ? `Yes — ${k.kubeconfigEnvIgnoredReason}` : 'No'}`)
696
- lines.push(`- Current Context Uses Exec: ${k.currentContextUsesExec ? 'Yes' : 'No'}`)
703
+ if (k.currentContextUsesExec !== undefined) {
704
+ lines.push(`- Current Context Uses Exec: ${k.currentContextUsesExec ? 'Yes' : 'No'}`)
705
+ }
697
706
  if (k.execPluginsPresent && k.execPluginsPresent.length > 0) {
698
707
  lines.push(`- Exec Plugins on PATH: \`${k.execPluginsPresent.join('`, `')}\``)
699
708
  }
@@ -706,6 +715,7 @@ export function formatForGitHub(data: DiagnosticsSnapshot, frontendPerf?: K8sUIP
706
715
  if (data.cluster) {
707
716
  const c = data.cluster
708
717
  lines.push(`### Cluster`)
718
+ if (c.observedAt) lines.push(`- Last observed: ${c.observedAt}`)
709
719
  lines.push(`- Platform: \`${c.platform}\` | K8s: \`${c.kubernetesVersion}\` | Nodes: ${c.nodeCount} | Namespaces: ${c.namespaceCount}${c.inCluster ? ' | In-Cluster' : ''}`)
710
720
  lines.push(``)
711
721
  }
@@ -754,7 +764,7 @@ export function formatForGitHub(data: DiagnosticsSnapshot, frontendPerf?: K8sUIP
754
764
  if (data.informers) {
755
765
  const inf = data.informers
756
766
  lines.push(`### Informers`)
757
- lines.push(`- Typed: ${inf.typedCount} | Dynamic: ${inf.dynamicCount}`)
767
+ lines.push(`- Typed: ${inf.typedCount} | Dynamic: ${inf.dynamicCount ?? 'unavailable'}`)
758
768
  if (inf.syncStatus) {
759
769
  const sync = inf.syncStatus
760
770
  lines.push(`- Sync Phase: \`${sync.phase}\` (${formatElapsed(sync.elapsedSec)})`)