@skyhook-io/radar-app 1.21.6 → 1.21.8

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 (118) hide show
  1. package/README.md +1 -1
  2. package/package.json +7 -7
  3. package/src/App.tsx +31 -4
  4. package/src/RadarApp.tsx +8 -2
  5. package/src/api/client.discoverMetrics.test.tsx +69 -0
  6. package/src/api/client.issueCorrelation.test.tsx +244 -0
  7. package/src/api/client.issueRowChanges.test.tsx +129 -0
  8. package/src/api/client.pendingOwnership.test.tsx +197 -0
  9. package/src/api/client.prometheusStatus.test.ts +4 -0
  10. package/src/api/client.restartError.test.ts +36 -1
  11. package/src/api/client.stopWorkflow.test.tsx +133 -0
  12. package/src/api/client.submitWorkflowTemplate.test.tsx +127 -0
  13. package/src/api/client.ts +582 -114
  14. package/src/api/connectionBinding.test.tsx +3 -1
  15. package/src/api/connectionBinding.ts +14 -2
  16. package/src/api/gitOpsPermissions.render.test.tsx +155 -0
  17. package/src/api/gitOpsPermissions.test.ts +90 -0
  18. package/src/api/gitOpsPermissions.ts +51 -0
  19. package/src/api/httpErrors.test.ts +30 -1
  20. package/src/api/httpErrors.ts +17 -0
  21. package/src/api/openobserveSetup.ts +85 -0
  22. package/src/api/podDebug.test.tsx +137 -0
  23. package/src/api/podDebug.ts +82 -0
  24. package/src/api/prometheusCharts.test.ts +23 -0
  25. package/src/api/prometheusCharts.ts +25 -0
  26. package/src/api/radarFeatures.render.test.tsx +43 -2
  27. package/src/api/radarFeatures.test.ts +18 -1
  28. package/src/api/radarFeatures.ts +17 -4
  29. package/src/api/reviewedActionMutation.ts +9 -2
  30. package/src/api/workloadMetrics.ts +2 -0
  31. package/src/components/NamespaceSwitcher.tsx +6 -2
  32. package/src/components/applications/ApplicationsView.identity.test.ts +35 -7
  33. package/src/components/applications/ApplicationsView.openResource.test.tsx +137 -11
  34. package/src/components/applications/ApplicationsView.tsx +127 -173
  35. package/src/components/cnpg/CNPGOperatorConditions.test.tsx +3 -0
  36. package/src/components/cnpg/CNPGOperatorConditions.tsx +4 -14
  37. package/src/components/cnpg/host.test.tsx +1 -1
  38. package/src/components/cnpg/host.tsx +0 -2
  39. package/src/components/dock/BottomDock.tsx +7 -3
  40. package/src/components/dock/MissingShellDebug.test.tsx +193 -0
  41. package/src/components/dock/MissingShellDebug.tsx +114 -0
  42. package/src/components/dock/PodDebugSession.test.tsx +60 -0
  43. package/src/components/dock/PodDebugSession.tsx +96 -0
  44. package/src/components/dock/TerminalTab.test.tsx +48 -4
  45. package/src/components/dock/TerminalTab.tsx +47 -25
  46. package/src/components/dock/WorkloadLogsTab.test.tsx +24 -1
  47. package/src/components/dock/WorkloadLogsTab.tsx +16 -0
  48. package/src/components/execution/BatchExecutionView.command.test.tsx +69 -0
  49. package/src/components/execution/BatchExecutionView.tsx +88 -5
  50. package/src/components/execution/BatchExecutionView.workflow-stop.test.tsx +69 -0
  51. package/src/components/execution/WorkflowRunStopAction.tsx +8 -0
  52. package/src/components/gitops/GitOpsPermissionRowActions.test.tsx +100 -0
  53. package/src/components/gitops/GitOpsPermissionRowActions.tsx +27 -0
  54. package/src/components/gitops/GitOpsView.identity.test.tsx +1 -0
  55. package/src/components/gitops/GitOpsView.permissions.test.tsx +102 -0
  56. package/src/components/gitops/GitOpsView.syncRequest.test.tsx +95 -7
  57. package/src/components/gitops/GitOpsView.tsx +93 -32
  58. package/src/components/helm/OwnedResources.tsx +1 -0
  59. package/src/components/home/HomeView.tsx +9 -1
  60. package/src/components/home/ProblemsPanel.investigate.test.tsx +12 -2
  61. package/src/components/home/mcpToolCatalog.ts +1 -0
  62. package/src/components/issues/IssuesPane.render.test.tsx +78 -2
  63. package/src/components/issues/IssuesPane.tsx +49 -6
  64. package/src/components/issues/useIssueExpansion.ts +91 -0
  65. package/src/components/resource/MetricsNotConnected.test.tsx +50 -0
  66. package/src/components/resource/MetricsNotConnected.tsx +114 -0
  67. package/src/components/resource/PVCUsageBar.tsx +2 -1
  68. package/src/components/resource/PrometheusCharts.render.test.tsx +47 -0
  69. package/src/components/resource/PrometheusCharts.tsx +14 -2
  70. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +91 -1
  71. package/src/components/resource/PrometheusChartsGrid.tsx +28 -52
  72. package/src/components/resource/RestartChart.tsx +4 -3
  73. package/src/components/resource/RightsizingPanel.source.test.tsx +34 -0
  74. package/src/components/resource/RightsizingStrip.tsx +5 -3
  75. package/src/components/resource/WorkloadMetricsSection.render.test.tsx +6 -0
  76. package/src/components/resource/WorkloadMetricsSection.tsx +14 -11
  77. package/src/components/resource/nameMatchedScope.ts +9 -3
  78. package/src/components/resources/EmptyNamespaceHint.tsx +42 -0
  79. package/src/components/resources/PodDebugAction.test.tsx +157 -0
  80. package/src/components/resources/PodDebugAction.tsx +207 -0
  81. package/src/components/resources/PodDebugPermission.tsx +21 -0
  82. package/src/components/resources/ResourcesView.empty-hint.test.tsx +132 -0
  83. package/src/components/resources/ResourcesView.tsx +39 -5
  84. package/src/components/resources/namespaceHint.test.ts +34 -0
  85. package/src/components/resources/namespaceHint.ts +19 -0
  86. package/src/components/resources/renderers/AdmissionPolicyRenderers.tsx +135 -0
  87. package/src/components/resources/renderers/NodeRenderer.tsx +2 -1
  88. package/src/components/resources/renderers/PodRenderer.tsx +12 -5
  89. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.test.tsx +24 -1
  90. package/src/components/settings/FormSaveActions.tsx +6 -2
  91. package/src/components/settings/LocalIntegrationStatus.tsx +14 -3
  92. package/src/components/settings/MetricsBackendSwitch.tsx +165 -0
  93. package/src/components/settings/OpenObserveSetup.test.tsx +384 -0
  94. package/src/components/settings/OpenObserveSetup.tsx +328 -0
  95. package/src/components/settings/SettingsDialog.tsx +21 -7
  96. package/src/components/settings/openobserveStatus.test.ts +34 -0
  97. package/src/components/settings/openobserveStatus.ts +55 -0
  98. package/src/components/timeline/TimelineList.selection.test.tsx +40 -0
  99. package/src/components/timeline/TimelineList.test.ts +18 -0
  100. package/src/components/timeline/TimelineList.tsx +19 -5
  101. package/src/components/timeline/TimelineView.tsx +2 -0
  102. package/src/components/workload/WorkloadView.pendingOwnership.test.tsx +34 -0
  103. package/src/components/workload/WorkloadView.tabUrl.test.tsx +44 -0
  104. package/src/components/workload/WorkloadView.tsx +103 -16
  105. package/src/components/workspace/WorkspaceConditions.tsx +56 -0
  106. package/src/components/workspace/layout.test.tsx +20 -0
  107. package/src/components/workspace/layout.tsx +1 -1
  108. package/src/context/TimelineNavigation.test.ts +59 -0
  109. package/src/context/TimelineNavigation.tsx +86 -0
  110. package/src/contexts/CapabilitiesContext.tsx +5 -1
  111. package/src/hooks/useResourceCounts.ts +2 -1
  112. package/src/hooks/useWorkflowStopAction.ts +31 -0
  113. package/src/index.css +1 -0
  114. package/src/integrations/resourceHosts.test.tsx +2 -2
  115. package/src/integrations/resourceHosts.tsx +4 -2
  116. package/src/k8s-ui-exports.test.ts +10 -0
  117. package/src/utils/page-links.ts +15 -1
  118. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.tsx +0 -128
@@ -0,0 +1,193 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
5
+ import { usePodDetailAccess } from '../resources/PodDebugAction'
6
+ import { observeConnectionStatus, resetConnectionBindingForTest } from '../../api/connectionBinding'
7
+ import { MissingShellDebug } from './MissingShellDebug'
8
+
9
+ const f = vi.hoisted(() => ({
10
+ pod: {} as any, installation: {} as Record<string, unknown>, checkError: undefined as Error | undefined, namedExec: false, embedded: false, support: 'supported', access: 'denied', image: undefined as string | undefined,
11
+ recheck: vi.fn(), open: vi.fn(), probe: vi.fn(),
12
+ }))
13
+ vi.mock('../../context/ConnectionContext', () => ({ useConnection: () => ({connection:{context:'fixture-cluster'}}) }))
14
+ vi.mock('../../context/NavCustomization', () => ({ useNavCustomization: () => ({ embedded: f.embedded }) }))
15
+ vi.mock('../../contexts/CapabilitiesContext', () => ({ useCapabilitiesContext: () => f.installation, useNamespacedCapabilities: () => ({ podDebugImage: f.image }) }))
16
+ vi.mock('../../api/client', async original => ({ ...await original<typeof import('../../api/client')>(), useResource: () => ({ data: f.pod }) }))
17
+ vi.mock('../../api/podDebug', () => ({ usePodDebugAccess: (...args: unknown[]) => {
18
+ f.probe(...args)
19
+ return {support: f.support, recheckAccess: f.recheck, unverifiedReview: !args[4] && f.access === 'unknown' && f.namedExec && !f.checkError ? {} : undefined, unverifiedImage: !args[4] && f.access === 'unknown' && f.namedExec && !f.checkError ? 'operator-tools' : undefined, query: { error: f.checkError, data: {state: f.access, image: 'toolbox', exec: f.namedExec}, refetch: f.recheck }}
20
+ } }))
21
+ vi.mock('@skyhook-io/k8s-ui', async original => ({ ...await original<typeof import('@skyhook-io/k8s-ui')>(), useOpenTerminal: () => f.open }))
22
+ vi.mock('../resources/PodDebugAction', async original => ({ ...await original<typeof import('../resources/PodDebugAction')>(),
23
+ PodDebugAction: ({ failedContainer, unverifiedReview, hideLauncher }: { failedContainer: string; unverifiedReview?: object; hideLauncher?: boolean }) => hideLauncher ? null : <button>{unverifiedReview ? 'Review attempt for' : 'Start for'} {failedContainer}</button> }))
24
+
25
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
26
+ let host: HTMLDivElement, root: ReturnType<typeof createRoot>
27
+ const render = () => act(() => root.render(<MissingShellDebug namespace="payments" name="checkout" uid="uid-1" target="app" base="/api"/>))
28
+ const button = (label: string) => [...host.querySelectorAll('button')].find(b => b.textContent === label)
29
+ beforeEach(() => {
30
+ vi.clearAllMocks()
31
+ resetConnectionBindingForTest()
32
+ Object.assign(f, { installation: {}, checkError: undefined, embedded: false, namedExec: false, support: 'supported', access: 'denied', image: undefined,
33
+ pod: { apiVersion: 'v1', kind: 'Pod', metadata: {uid:'uid-1', namespace:'payments', name:'checkout'},
34
+ spec: {containers:[{name:'app'}]}, status:{phase:'Running',containerStatuses:[{name:'app', state:{running:{}}}] } } })
35
+ host = document.createElement('div')
36
+ root = createRoot(host)
37
+ })
38
+ afterEach(() => act(() => root.unmount()))
39
+
40
+ it('offers only running debuggers targeting the failed container, with no access probe', () => {
41
+ const names = ['already-running','second','wrong-target','stopped']
42
+ f.pod.spec.ephemeralContainers = names.map(name => ({ name, image:'toolbox', targetContainerName:name === 'wrong-target' ? 'other' : 'app' }))
43
+ f.pod.status.ephemeralContainerStatuses = names.map(name => ({ name, state:name === 'stopped' ? {terminated:{}} : {running:{}} }))
44
+ render()
45
+ const select = host.querySelector('select')!
46
+ expect([...select.options].map(o=>o.value)).toEqual(names.slice(0,2).reverse())
47
+ act(() => { select.value='second'; select.dispatchEvent(new Event('change',{bubbles:true})) })
48
+ act(() => button('Open debug terminal')!.click())
49
+ expect(f.open).toHaveBeenCalledWith(expect.objectContaining({containerName:'second',debugSession:expect.objectContaining({podUID:'uid-1'})}))
50
+ expect(f.probe.mock.lastCall?.[3]).toBe(false)
51
+ expect(button('Start for app')).toBeUndefined()
52
+ })
53
+
54
+ it('shows the exact missing permission and rechecks an updated grant', () => {
55
+ render()
56
+ expect(host.textContent).toContain('Ask your cluster admin for access to update pods/ephemeralcontainers for Pod payments/checkout.')
57
+ expect([...host.querySelectorAll('code.inline-code')].map(code => code.textContent)).toEqual(['update pods/ephemeralcontainers', 'payments/checkout'])
58
+ act(() => button('Recheck access')!.click())
59
+ expect(f.recheck).toHaveBeenCalledOnce()
60
+ f.access='allowed'; render()
61
+ expect(button('Start for app')).toBeDefined()
62
+ })
63
+ it('offers a recheck when Kubernetes returns no decision', () => {
64
+ f.access='unknown'; render()
65
+ expect(host.textContent).toContain('Kubernetes couldn’t confirm permission to update pods/ephemeralcontainers for Pod payments/checkout.')
66
+ expect(host.textContent).not.toContain('Ask your cluster admin for access')
67
+ expect(button('Recheck access')).toBeDefined()
68
+ })
69
+ it('distinguishes a failed request from an inconclusive cluster answer', () => {
70
+ f.access = 'unknown'
71
+ render()
72
+ expect(host.textContent).toContain('Kubernetes couldn’t confirm permission to update pods/ephemeralcontainers for Pod payments/checkout.')
73
+ f.checkError = new Error('request timed out')
74
+ render()
75
+ expect(host.textContent).toContain('Radar couldn’t check permission to update pods/ephemeralcontainers for Pod payments/checkout.')
76
+ expect(host.textContent).not.toContain('Ask your cluster admin for access')
77
+ })
78
+
79
+ it.each(['embedded', 'replaced', 'windows', 'stopped', 'old', 'disabled'])('suppresses the grant request on %s', mode => {
80
+ if(mode==='embedded')f.embedded=true
81
+ if(mode==='replaced')f.pod.metadata.uid='replacement'
82
+ if(mode==='windows')f.pod.spec.os={name:'windows'}
83
+ if(mode==='stopped')f.pod.status.containerStatuses[0].state={terminated:{}}
84
+ if(mode==='old')f.support='unsupported'
85
+ if(mode==='disabled')f.access='unavailable'
86
+ render()
87
+ expect(host.textContent).not.toContain('Ask your cluster admin for access')
88
+ expect(button('Start for app')).toBeUndefined()
89
+ })
90
+
91
+ it('uses a positive namespace grant when named access is unknown, but honors an exact denial', () => {
92
+ f.image = 'operator-debug'; f.access = 'unknown'
93
+ render()
94
+ expect(button('Start for app')).toBeDefined()
95
+ expect(f.probe.mock.lastCall?.[3]).toBe(false)
96
+ f.access = 'denied'; render()
97
+ expect(host.textContent).toContain('Ask your cluster admin for access')
98
+ })
99
+
100
+ it('updates a previously open recovery screen when the connection changes', () => {
101
+ render()
102
+ act(() => observeConnectionStatus({connectionId:'new-cluster'}))
103
+ expect(host.textContent).toContain('Open the Pod on the current cluster')
104
+ expect(host.textContent).not.toContain('Ask your cluster admin for access')
105
+ })
106
+
107
+ it('supplies named-only exec to the Pod header and existing terminals independently of update', () => {
108
+ function Consumer() {
109
+ const access = usePodDetailAccess(f.pod, {canExec:false, canOpenEphemeralTerminal:false})
110
+ return <>{access.canExec && 'Terminal '}{access.canOpenEphemeralTerminal && 'Reopen '}{access.debugImage && 'Debug'}</>
111
+ }
112
+ f.namedExec = true; f.access = 'denied'
113
+ act(() => root.render(<Consumer/>))
114
+ expect(host.textContent).toBe('Terminal Reopen ')
115
+ f.access = 'allowed'
116
+ act(() => root.render(<Consumer/>))
117
+ expect(host.textContent).toBe('Terminal Reopen Debug')
118
+ f.embedded = true
119
+ act(() => root.render(<Consumer/>))
120
+ expect(host.textContent).toBe('Terminal Reopen ')
121
+ expect(f.probe.mock.lastCall?.[4]).toBe(true)
122
+ })
123
+
124
+ it('names Radar’s ServiceAccount for a shared installation without authentication', () => {
125
+ f.installation = { deployment: { mode: 'in-cluster' } }
126
+ render()
127
+ expect(host.textContent).toContain('Ask your cluster admin to grant Radar’s ServiceAccount access to update pods/ephemeralcontainers for Pod payments/checkout.')
128
+ })
129
+
130
+ it('explains how to start a debugger outside a hosted session without issuing a named check', () => {
131
+ f.embedded = true
132
+ render()
133
+ expect(host.textContent).toContain('standalone Radar')
134
+ expect(f.probe.mock.lastCall?.[3]).toBe(false)
135
+ })
136
+
137
+ it.each(['unknown', 'unavailable'])('rechecks hosted exec access to a running debugger when %s', state => {
138
+ f.embedded = true
139
+ f.access = state
140
+ f.pod.spec.ephemeralContainers = [{ name: 'debugger', image: 'tools', targetContainerName: 'app' }]
141
+ f.pod.status.ephemeralContainerStatuses = [{ name: 'debugger', state: { running: {} } }]
142
+ render()
143
+ expect(f.probe.mock.lastCall?.slice(3, 5)).toEqual([true, true])
144
+ expect(host.textContent).not.toContain('Ask your cluster admin for access')
145
+ act(() => button('Recheck access')!.click())
146
+ expect(f.recheck).toHaveBeenCalledOnce()
147
+ f.namedExec = true
148
+ render()
149
+ expect(button('Open debug terminal')).toBeDefined()
150
+ })
151
+
152
+ it('offers confirmation only while the named response verifies exec, on a writable Radar', () => {
153
+ f.namedExec = true
154
+ f.access = 'unknown'
155
+ render()
156
+ expect(button('Review attempt for app')).toBeDefined()
157
+ f.checkError = new Error('transport failure')
158
+ render()
159
+ expect(button('Review attempt for app')).toBeUndefined()
160
+ f.checkError = undefined
161
+ f.access = 'denied'
162
+ render()
163
+ expect(button('Review attempt for app')).toBeUndefined()
164
+ f.access = 'unknown'
165
+ f.embedded = true
166
+ render()
167
+ expect(button('Review attempt for app')).toBeUndefined()
168
+ })
169
+ it('keeps unrelated containers out of the shell recovery actions', () => {
170
+ f.pod.spec.containers.push({ name: 'worker' })
171
+ f.pod.status.containerStatuses.push({ name: 'worker', state: { running: {} } })
172
+ f.pod.spec.ephemeralContainers = [{ name: 'network-tools', image: 'tools' }]
173
+ f.pod.status.ephemeralContainerStatuses = [{ name: 'network-tools', state: { running: {} } }]
174
+ render()
175
+ expect(host.textContent).not.toContain('worker')
176
+ expect(host.textContent).not.toContain('network-tools')
177
+ expect(button('Open debug terminal')).toBeUndefined()
178
+ })
179
+ it('keeps verified named exec when the separate update review failed, with no write preview', async () => {
180
+ f.access = 'check_failed'
181
+ f.namedExec = true
182
+ render()
183
+ expect(host.textContent).toContain('Kubernetes couldn’t complete the check')
184
+ expect(button('Recheck access')).toBeDefined()
185
+ expect(button('Review debug container')).toBeUndefined()
186
+ expect(host.textContent).not.toContain('Ask your cluster admin for access')
187
+ function Details() {
188
+ const access = usePodDetailAccess(f.pod, { canExec: false, canOpenEphemeralTerminal: false })
189
+ return <output>{String(access.canExec)} {access.debugImage ?? 'no preview'}</output>
190
+ }
191
+ act(() => root.render(<Details/>))
192
+ expect(host.textContent).toBe('true no preview')
193
+ })
@@ -0,0 +1,114 @@
1
+ import { type ReactNode, useState } from 'react'
2
+ import { Terminal } from 'lucide-react'
3
+ import { formatAge, getRunningEphemeralContainers, useOpenTerminal } from '@skyhook-io/k8s-ui'
4
+ import { PodDebugPermission } from '../resources/PodDebugPermission'
5
+ import { useResource } from '../../api/client'
6
+ import { connectionHeaderValue, useCurrentConnectionId } from '../../api/connectionBinding'
7
+ import { getApiBase } from '../../api/config'
8
+ import { usePodDebugAccess } from '../../api/podDebug'
9
+ import { useNavCustomization } from '../../context/NavCustomization'
10
+ import { useCapabilitiesContext, useNamespacedCapabilities } from '../../contexts/CapabilitiesContext'
11
+ import { PodDebugAction, debugAccessMessage, runningPodDebugTargets, type PodDebugTarget } from '../resources/PodDebugAction'
12
+
13
+ interface RecoveryTarget {
14
+ namespace: string; name: string; uid: string; target: string; connection?: string; base: string; podDetailsLink?: ReactNode
15
+ }
16
+
17
+ export function MissingShellDebug(props: RecoveryTarget) {
18
+ const { namespace, name, uid, target, connection, base, podDetailsLink } = props
19
+ const currentConnection = useCurrentConnectionId()
20
+ const sameCluster = currentConnection === connection && getApiBase() === base
21
+ const podQuery = useResource<PodDebugTarget>('pods', namespace, name, undefined, { enabled: sameCluster })
22
+ const pod = podQuery.data
23
+ if (!sameCluster) return <p className="text-xs text-theme-text-secondary">The cluster connection changed. Open the Pod on the current cluster to start a terminal.</p>
24
+ if (podQuery.error) return <div className="space-y-2 text-xs text-theme-text-secondary">
25
+ <p>Radar couldn’t read the Pod to check its debug options.</p>
26
+ <button className="btn-secondary px-2 py-1" onClick={() => void podQuery.refetch()}>Check Pod again</button>
27
+ </div>
28
+ if (!pod) return <p className="text-xs text-theme-text-secondary">Checking debug options…</p>
29
+ if (pod.metadata.uid !== uid) return <p className="text-xs text-theme-text-secondary">This Pod was replaced. Open its details to start a new terminal. {podDetailsLink}</p>
30
+ const targets = runningPodDebugTargets(pod)
31
+ if (!targets?.includes(target)) return <p className="max-w-md text-xs text-theme-text-secondary">Debug recovery needs a running Linux container. Check the container state in Pod details.</p>
32
+ return <DebugOptions {...props} pod={pod}/>
33
+ }
34
+
35
+ function DebugOptions({ namespace, name, uid, target, connection, base, pod }: RecoveryTarget & {pod: PodDebugTarget}) {
36
+ const { embedded } = useNavCustomization()
37
+ const { deployment } = useCapabilitiesContext()
38
+ const { podDebugImage, canOpenEphemeralTerminal } = useNamespacedCapabilities(namespace)
39
+ const execOnly = !!embedded || deployment?.mode === 'cloud'
40
+ const current = () => getApiBase() === base && connectionHeaderValue() === connection
41
+ const running = getRunningEphemeralContainers(pod).filter(c => c.targetContainerName === target)
42
+ const { query, support, recheckSupport, unverifiedImage, unverifiedReview, recheckAccess } = usePodDebugAccess(namespace, name, uid,
43
+ execOnly ? !!running.length && !canOpenEphemeralTerminal : !running.length && !podDebugImage,
44
+ execOnly, !execOnly && !running.length ? podDebugImage : undefined)
45
+ const openTerminal = useOpenTerminal()
46
+ const [choice, setChoice] = useState('')
47
+ const access = query.error ? undefined : query.data
48
+ const allowedImage = query.error ? undefined : access?.state === 'allowed' ? access.image :
49
+ access?.state === 'denied' || access?.state === 'unavailable' || access?.state === 'check_failed' ? undefined : podDebugImage
50
+ const accessMessage = debugAccessMessage(execOnly, query.error, access?.state, pod)
51
+ const denied = access?.state === 'denied'
52
+ const canCreate = !execOnly && !running.length
53
+ const image = canCreate ? allowedImage || unverifiedImage : undefined
54
+ const showRecheck = canCreate && (!unverifiedImage || !!unverifiedReview?.refused) && !allowedImage && support === 'supported' && (!query.isPending || !!query.error) && access?.state !== 'unavailable'
55
+ return <div className="flex w-full min-w-0 max-w-md flex-col items-center gap-2 text-xs text-theme-text-secondary">
56
+ {renderOptions()}
57
+ <PodDebugAction pod={pod} defaultImage={image} failedContainer={target} unverifiedReview={image ? unverifiedReview : undefined}
58
+ debugDenial={canCreate && denied ? { refusal: access.refusedAttempt?.message } : undefined}
59
+ hideLauncher={!image || (!!unverifiedReview?.refused && !unverifiedReview.refused.rechecked)}
60
+ reviewStatus={{ message: accessMessage, refusal: query.data?.refusedAttempt?.message,
61
+ recheck: execOnly ? undefined : recheckAccess, checking: query.isFetching }} />
62
+ {showRecheck && <button className="btn-secondary rounded px-2 py-1" disabled={query.isFetching} onClick={() => void recheckAccess()}>{query.isFetching ? 'Checking…' : 'Recheck access'}</button>}
63
+ </div>
64
+
65
+ function renderOptions() {
66
+ if (running.length && support === 'supported' && (!execOnly || canOpenEphemeralTerminal || (!query.error && query.data?.exec))) {
67
+ const selected = running.find(c => c.name === choice) ?? running[0]
68
+ return <div className="flex w-full min-w-0 max-w-md flex-col items-center gap-2">
69
+ <p className="text-xs text-theme-text-secondary [overflow-wrap:anywhere]">{running.length === 1 ? <>A debug container using <code className="inline-code">{selected.image}</code> is running</> : `${running.length} debug containers are running`} for container <code className="inline-code">{target}</code>.</p>
70
+ {running.length > 1 && <select aria-label="Running debug container" className="w-full min-w-0 max-w-full rounded border border-theme-border bg-theme-surface px-2 py-1 text-xs"
71
+ value={selected.name} onChange={event => setChoice(event.target.value)}>
72
+ {running.map(c => <option key={c.name} value={c.name}>{c.startedAt && `${formatAge(c.startedAt)} ago · `}{c.name} · {c.image}</option>)}
73
+ </select>}
74
+ <button className="btn-brand flex items-center gap-2 rounded px-3 py-1.5 text-xs" onClick={() => {
75
+ if (current()) openTerminal({ namespace, podName: name, containerName: selected.name, containers: [selected.name],
76
+ debugSession: { podUID: uid, image: selected.image, connectionId: connection, apiBase: base } })
77
+ }}><Terminal className="h-3.5 w-3.5"/>Open debug terminal</button>
78
+ </div>
79
+ }
80
+ if (execOnly) {
81
+ if (running.length && support === 'unknown') return <div className="flex flex-col items-center gap-2 text-xs text-theme-text-secondary">
82
+ <p>Radar hasn’t confirmed whether this cluster can reopen the running debugger.</p>
83
+ <button className="btn-secondary rounded px-2 py-1" onClick={() => void recheckSupport()}>Recheck support</button>
84
+ </div>
85
+ if (running.length && support === 'supported' && !canOpenEphemeralTerminal) {
86
+ return <div className="flex flex-col items-center gap-2 text-xs text-theme-text-secondary">
87
+ <p>{query.isFetching ? 'Checking whether you can open this debugger…' : query.data?.state === 'unavailable' && !query.error ? 'A debugger is already running. Ask your administrator to check your Pod exec access and whether this Radar allows exec.' : 'Radar couldn’t verify terminal access to this running debugger.'}</p>
88
+ {!query.isFetching && <button className="btn-secondary rounded px-2 py-1" onClick={() => void query.refetch()}>Recheck access</button>}
89
+ </div>
90
+ }
91
+ if (running.length && support === 'unsupported') return <p className="max-w-md text-xs text-theme-text-secondary">A debug container is already running. Upgrade this cluster’s Radar to reopen it here, or open a terminal to that container with kubectl.</p>
92
+ return <p className="max-w-md text-xs text-theme-text-secondary">Run <code className="inline-code">kubectl debug</code> against this cluster with an approved image, or open this Pod in standalone Radar. Your kubectl identity needs permission to patch <code className="inline-code">pods/ephemeralcontainers</code>. <code className="mt-2 block select-all break-all rounded bg-theme-elevated p-2 text-left">kubectl --context CONTEXT -n {namespace} debug {name} --target={target} --image=APPROVED_IMAGE -it</code></p>
93
+ }
94
+ if (allowedImage) return null
95
+ if (support !== 'supported') {
96
+ return support === 'unsupported' ? <p className="max-w-sm text-xs text-theme-text-secondary">Upgrade Radar to check debug access for this Pod, or ask your cluster administrator to help start a debug container.</p> : <div className="flex flex-col items-center gap-2 text-xs text-theme-text-secondary">
97
+ <p>Radar hasn’t confirmed debug support for this cluster.</p>
98
+ <button className="btn-secondary rounded px-2 py-1" onClick={() => void recheckSupport()}>Recheck support</button>
99
+ </div>
100
+ }
101
+ if (query.isPending && !query.error) return <p className="text-xs text-theme-text-secondary">Checking access for this Pod…</p>
102
+ if (access?.state === 'unavailable') return <div className="flex max-w-md flex-col items-center gap-2 text-xs text-theme-text-secondary">
103
+ <p>A debug terminal is unavailable for this Pod. Ask your administrator to check Pod exec access and whether exec is enabled on this Radar.</p>
104
+ <button className="btn-secondary rounded px-2 py-1" disabled={query.isFetching} onClick={() => void query.refetch()}>Recheck access</button>
105
+ </div>
106
+ return <div className="flex max-w-md flex-col items-center gap-2 text-xs text-theme-text-secondary">
107
+ <p>{denied ? <PodDebugPermission namespace={namespace} name={name} /> : accessMessage}</p>
108
+ {query.data?.refusedAttempt && !denied && <div role="status" className="max-w-full break-words text-warning-text">
109
+ <p>The last debug request was refused.</p><p>{query.data.refusedAttempt.message}</p>
110
+ {unverifiedImage && !query.data.refusedAttempt.rechecked && <p className="text-theme-text-secondary">Recheck access to review another attempt.</p>}
111
+ </div>}
112
+ </div>
113
+ }
114
+ }
@@ -0,0 +1,60 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { afterEach, expect, it, vi } from 'vitest'
6
+ import { PodDebugSession } from './PodDebugSession'
7
+
8
+ ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
9
+ const session = { apiBase: '/api', podUID: 'reviewed', image: 'mirror.example/tools' }
10
+ const opts = { namespace: 'demo', podName: 'api', containerName: 'debug-fixture', session }
11
+ const key = ['pod-debug-startup', '/api', undefined, 'reviewed', 'debug-fixture']
12
+ const client = new QueryClient()
13
+ let root: ReturnType<typeof createRoot>
14
+ async function mount() {
15
+ const host = document.createElement('div')
16
+ document.body.append(host)
17
+ root = createRoot(host)
18
+ await act(async () => {
19
+ root.render(<QueryClientProvider client={client}><PodDebugSession {...opts}><b>attached</b></PodDebugSession></QueryClientProvider>)
20
+ })
21
+ }
22
+ afterEach(() => {
23
+ act(() => root.unmount())
24
+ document.body.replaceChildren()
25
+ client.clear()
26
+ vi.unstubAllGlobals()
27
+ })
28
+ function reply(state: object, uid = 'reviewed') {
29
+ return new Response(JSON.stringify({ resource: {
30
+ metadata: { uid }, status: { phase: 'Running', ephemeralContainerStatuses: [{ name: 'debug-fixture', state }] },
31
+ } }))
32
+ }
33
+ async function until(phrase: string) {
34
+ await act(async () => { await vi.waitFor(() => expect(client.getQueryState(key)?.fetchStatus).toBe('idle')) })
35
+ await vi.waitFor(() => expect(document.body.textContent).toContain(phrase))
36
+ }
37
+ it('keeps watching a pull backoff and opens only the accepted container once it runs', async () => {
38
+ const fetch = vi.fn().mockResolvedValueOnce(reply({ waiting: { reason: 'ImagePullBackOff', message: 'registry unavailable' } }))
39
+ .mockResolvedValueOnce(reply({ running: {} }))
40
+ vi.stubGlobal('fetch', fetch)
41
+ await mount()
42
+ await until('ImagePullBackOff')
43
+ expect(document.body.textContent).toContain('registry unavailable')
44
+ expect(document.body.textContent).not.toContain('attached')
45
+ await act(async () => { await client.invalidateQueries({ queryKey: key }) })
46
+ await until('attached')
47
+ expect(fetch.mock.calls.every(([, init]) => !init.method || init.method === 'GET')).toBe(true)
48
+ })
49
+ it.each([
50
+ [() => reply({ waiting: { reason: 'InvalidImageName' } }), 'Start a new debug session with a valid image reference'],
51
+ [() => reply({ waiting: { reason: 'CreateContainerConfigError', message: 'image runs as root' } }), 'Kubernetes could not start the debug container'],
52
+ [() => reply({ terminated: { exitCode: 17, reason: 'Error' } }), 'exited with code 17'],
53
+ [() => reply({ running: {} }, 'replacement'), 'original Pod was replaced'],
54
+ [() => new Response(JSON.stringify({ error: 'pods is forbidden' }), { status: 403 }), 'Access denied'],
55
+ ])('keeps a terminal detached when startup cannot succeed (%#)', async (response, message) => {
56
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(response()))
57
+ await mount()
58
+ await until(message)
59
+ expect(document.body.textContent).not.toContain('attached')
60
+ })
@@ -0,0 +1,96 @@
1
+ import { useState, type ReactNode } from 'react'
2
+ import { useQuery } from '@tanstack/react-query'
3
+ import { LoaderCircle, RefreshCw } from 'lucide-react'
4
+ import type { DockTab } from '@skyhook-io/k8s-ui'
5
+ import { ApiError, fetchResourceWithRelationships } from '../../api/client'
6
+ import { getApiBase } from '../../api/config'
7
+ import { connectionHeaderValue, useCurrentConnectionId } from '../../api/connectionBinding'
8
+ import type { PodDebugTarget } from '../resources/PodDebugAction'
9
+
10
+ type Session = NonNullable<DockTab['debugSession']>
11
+
12
+ interface Startup {
13
+ state: 'finished' | 'running' | 'waiting' | 'blocked'
14
+ title?: string
15
+ hint?: string
16
+ reason?: string
17
+ message?: string
18
+ }
19
+
20
+ function startup(pod: PodDebugTarget, uid: string, container: string): Startup {
21
+ if (pod.metadata.uid !== uid) return { state: 'finished', title: 'The original Pod was replaced' }
22
+ const status = pod.status.ephemeralContainerStatuses?.find(item => item.name === container)?.state
23
+ if (status?.terminated) {
24
+ const { exitCode, reason, message } = status.terminated
25
+ return { state: 'finished', title: `Debug container exited with code ${exitCode}`, reason, message }
26
+ }
27
+ if (pod.metadata.deletionTimestamp || ['Failed', 'Succeeded'].includes(pod.status.phase ?? '')) {
28
+ return { state: 'finished', title: 'The Pod is terminating or has finished' }
29
+ }
30
+ if (status?.running) return { state: 'running' }
31
+ const waiting = status?.waiting
32
+ switch (waiting?.reason) {
33
+ case 'InvalidImageName':
34
+ return { state: 'finished', title: 'The debug image name is invalid', hint: 'Start a new debug session with a valid image reference.', ...waiting }
35
+ case 'ErrImagePull':
36
+ case 'ImagePullBackOff':
37
+ return { state: 'blocked', title: 'Kubernetes could not pull the debug image', hint: 'Check the image and registry access. The terminal opens if Kubernetes succeeds on a retry.', ...waiting }
38
+ case 'ErrImageNeverPull':
39
+ return { state: 'blocked', title: 'The debug image is missing on the node and pulling is disabled', hint: 'Load the image on the node or start a new session with an available image.', ...waiting }
40
+ case 'CreateContainerConfigError':
41
+ case 'CreateContainerError':
42
+ case 'RunContainerError':
43
+ return { state: 'blocked', title: 'Kubernetes could not start the debug container', hint: 'Inspect the kubelet message. Start a new session if the image or its configuration must change.', ...waiting }
44
+ default:
45
+ return { state: 'waiting', title: 'Waiting for the debug container', ...waiting }
46
+ }
47
+ }
48
+
49
+ export function PodDebugSession({ namespace, podName, containerName, session, isActive = true, children, podDetailsLink }: {
50
+ namespace: string; podName: string; containerName: string; session: Session; isActive?: boolean; children: ReactNode; podDetailsLink?: ReactNode
51
+ }) {
52
+ const [connected, setConnected] = useState(false)
53
+ const currentConnection = useCurrentConnectionId()
54
+ const current = () => getApiBase() === session.apiBase && connectionHeaderValue() === session.connectionId
55
+ const query = useQuery({
56
+ queryKey: ['pod-debug-startup', session.apiBase, session.connectionId, session.podUID, containerName],
57
+ queryFn: async () => {
58
+ if (!current()) throw new ApiError('The cluster connection changed.', 409)
59
+ const { resource } = await fetchResourceWithRelationships<PodDebugTarget>('pods', namespace, podName)
60
+ if (!current()) throw new ApiError('The cluster connection changed.', 409)
61
+ return startup(resource, session.podUID, containerName)
62
+ },
63
+ enabled: !connected && isActive,
64
+ retry: false,
65
+ refetchInterval: query => query.state.data?.state === 'finished' || query.state.data?.state === 'running' ||
66
+ (query.state.error instanceof ApiError && [403, 404, 409].includes(query.state.error.status)) ? false : query.state.data?.state === 'blocked' ? 5000 : 2000,
67
+ refetchOnWindowFocus: false,
68
+ })
69
+
70
+ if (!connected && !query.error && query.data?.state === 'running' && current()) setConnected(true)
71
+ if (currentConnection !== session.connectionId || getApiBase() !== session.apiBase) return <div role="status" className="p-5 text-sm text-theme-text-secondary">The cluster connection changed. Reopen the Pod to inspect this debug session.</div>
72
+ if (connected) return <>{children}</>
73
+
74
+ const status = query.data
75
+ const error = query.error
76
+ const code = error instanceof ApiError ? error.status : undefined
77
+ const title = code === 403 ? 'Access denied while reading the debug container'
78
+ : code === 404 ? 'The original Pod is gone'
79
+ : code === 409 ? 'The cluster connection changed'
80
+ : error ? 'Could not read the debug container status' : status?.title ?? 'Waiting for the debug container'
81
+ return <div className="flex h-full min-h-32 flex-col justify-center gap-2 overflow-auto bg-theme-base px-5 py-4">
82
+ <h3 className="flex items-center gap-2 font-medium text-theme-text-primary">
83
+ {!error && (!status || status.state === 'waiting') && <LoaderCircle aria-hidden className="h-4 w-4 animate-spin text-theme-text-tertiary" />}
84
+ {title}
85
+ </h3>
86
+ <p className="break-all font-mono text-xs text-theme-text-secondary">{namespace}/{podName} · {containerName} · {session.image}</p>
87
+ {(error || status?.reason || status?.message) && <p className="break-words text-sm text-theme-text-primary">
88
+ {error?.message || [status?.reason, status?.message].filter(Boolean).join(' · ')}
89
+ </p>}
90
+ {status?.state === 'finished' && podDetailsLink}
91
+ {!error && status?.hint && <p className="text-xs text-theme-text-secondary">{status.hint}</p>}
92
+ {!error && (!status || status.state === 'waiting') && <p className="text-xs text-theme-text-secondary">The terminal opens when Kubernetes reports this container is running.</p>}
93
+ {error && code !== 404 && code !== 409 && <button type="button" className="btn-secondary flex w-fit items-center gap-1.5 px-3 py-1.5 text-xs"
94
+ disabled={query.isFetching} onClick={() => { void query.refetch() }}><RefreshCw className="h-3.5 w-3.5" />Check status</button>}
95
+ </div>
96
+ }
@@ -1,19 +1,26 @@
1
1
  import { renderToString } from 'react-dom/server'
2
- import { expect, it, vi } from 'vitest'
2
+ import { beforeEach, expect, it, vi } from 'vitest'
3
3
  import type { TerminalTabProps } from '@skyhook-io/k8s-ui'
4
4
  import { TerminalTab } from './TerminalTab'
5
- const captured = vi.hoisted(() => ({ props: null as TerminalTabProps | null }))
6
- vi.mock('@skyhook-io/k8s-ui', () => ({ TerminalTab: (props: TerminalTabProps) => { captured.props = props; return null } }))
5
+ vi.mock('./PodDebugSession', () => ({ PodDebugSession: ({ children }: { children: React.ReactNode }) => children }))
6
+ const captured = vi.hoisted(() => ({ props: null as TerminalTabProps | null, read: vi.fn((): { data?: unknown } => ({})) }))
7
+ vi.mock('../../api/client', () => ({ useResource: captured.read }))
8
+ vi.mock('@skyhook-io/k8s-ui', async original => ({ ...await original<typeof import('@skyhook-io/k8s-ui')>(), TerminalTab: (props: TerminalTabProps) => { captured.props = props; return null } }))
7
9
  vi.mock('../../api/config', async (importOriginal) => ({ ...await importOriginal<typeof import('../../api/config')>(), apiUrl: (path: string) => `/api${path}`, getWsUrl: (path: string) => `ws://localhost/api${path}` }))
10
+ beforeEach(() => captured.read.mockReturnValue({}))
11
+
8
12
  it.each([undefined, '/bin/custom+command'])('forwards the executable and context through the shared terminal (%s)', async shell => {
9
13
  renderToString(<TerminalTab namespace="app" podName="worker" containerName="app" containers={['app', 'sidecar']} shell={shell} note="Primary" />)
10
14
  const props = captured.props!
11
15
  expect(props.command).toBe(shell); expect(props.note).toBe('Primary')
12
- expect(Boolean(props.createDebugContainer)).toBe(!shell)
16
+ expect(props.createDebugContainer).toBeUndefined(); expect(Boolean(props.renderDebugAction)).toBe(!shell)
13
17
  const { wsUrl } = await props.createSession('app')
14
18
  const url = new URL(wsUrl)
15
19
  expect(url.pathname).toBe('/api/pods/app/worker/exec'); expect(url.searchParams.get('container')).toBe('app')
16
20
  expect(url.searchParams.get('shell')).toBe(shell ?? null)
21
+ expect(url.searchParams.has('uid')).toBe(false)
22
+ const retry = await props.createSession('app', 'reviewed-pod')
23
+ expect(new URL(retry.wsUrl).searchParams.get('uid')).toBe('reviewed-pod')
17
24
  })
18
25
 
19
26
  it('reconnects on the connection the tab was opened on, not the latest', async () => {
@@ -26,3 +33,40 @@ it('reconnects on the connection the tab was opened on, not the latest', async (
26
33
  expect(new URL(wsUrl).searchParams.get('connection')).toBe('n-1')
27
34
  resetConnectionBindingForTest()
28
35
  })
36
+
37
+ it('reconnects an existing debug session to its reviewed connection without offering another container', async () => {
38
+ const { observeConnectionStatus, resetConnectionBindingForTest } = await import('../../api/connectionBinding')
39
+ observeConnectionStatus({ connectionId: 'next-cluster' })
40
+ renderToString(<TerminalTab namespace="demo" podName="api" containerName="debug-1" containers={['debug-1']} debugSession={{ connectionId: 'reviewed-cluster', apiBase: '/api', podUID: 'reviewed', image: 'mirror.example/debug' }} />)
41
+ const { wsUrl } = await captured.props!.createSession('debug-1')
42
+ expect(new URL(wsUrl).searchParams.get('connection')).toBe('reviewed-cluster')
43
+ expect(new URL(wsUrl).searchParams.get('uid')).toBe('reviewed')
44
+ expect(renderToString(captured.props!.renderDebugAction!('debug-1', 'reviewed'))).toContain('different image')
45
+ resetConnectionBindingForTest()
46
+ })
47
+
48
+ it('opens and retries an ordinary terminal on the UID captured in Pod details', async () => {
49
+ renderToString(<TerminalTab namespace="demo" podName="api" podUID="fresh" containerName="tools" containers={['tools']} />)
50
+ expect(new URL((await captured.props!.createSession('tools')).wsUrl).searchParams.get('uid')).toBe('fresh')
51
+ expect(new URL((await captured.props!.createSession('tools', 'other')).wsUrl).searchParams.get('uid')).toBe('fresh')
52
+ })
53
+
54
+ it('only offers running regular containers and native sidecars of the original Pod', () => {
55
+ captured.read.mockReturnValue({ data: {
56
+ metadata: { uid: 'original' },
57
+ spec: {
58
+ containers: [{ name: 'api' }, { name: 'worker' }],
59
+ initContainers: [{ name: 'mesh', restartPolicy: 'Always' }, { name: 'init' }],
60
+ },
61
+ status: {
62
+ containerStatuses: [{ name: 'api', state: { terminated: {} } }, { name: 'worker', state: { running: {} } }],
63
+ initContainerStatuses: [{ name: 'mesh', state: { running: {} } }, { name: 'init', state: { running: {} } }],
64
+ },
65
+ } })
66
+ const render = (uid: string) => renderToString(<TerminalTab namespace="demo" podName="pod" podUID={uid} containerName="api" containers={['api', 'worker', 'mesh']} />)
67
+ render('original')
68
+ expect(captured.props?.containers).toEqual(['worker', 'mesh'])
69
+ expect(captured.props?.containerName).toBe('api')
70
+ render('replacement')
71
+ expect(captured.props?.containers).toEqual([])
72
+ })