@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,42 @@
1
+ import { englishPlural, isEnglishPlural } from '@skyhook-io/k8s-ui/utils/pluralize'
2
+ import type { EmptyNamespaceHint as Hint } from './namespaceHint'
3
+
4
+ interface EmptyNamespaceHintProps {
5
+ hint: Hint
6
+ namespaces: string[]
7
+ /** Real Kind, e.g. "Pod". */
8
+ kind: string
9
+ onShowAll?: () => void
10
+ }
11
+
12
+ export function EmptyNamespaceHint({ hint, namespaces, kind, onShowAll }: EmptyNamespaceHintProps) {
13
+ const scope = namespaces.length === 1 ? namespaces[0] : `${namespaces.length} namespaces`
14
+ if (hint.type === 'none-elsewhere') {
15
+ return (
16
+ <p className="text-sm mt-1 text-theme-text-disabled">
17
+ Filtered to {scope}. None in other namespaces either.
18
+ </p>
19
+ )
20
+ }
21
+ const noun = hint.count === 1 ? kind : isEnglishPlural(kind) ? kind : englishPlural(kind)
22
+ return (
23
+ <div className="mt-3 flex flex-col items-center gap-2 text-sm">
24
+ <p className="text-theme-text-secondary">
25
+ Filtered to {scope}.{' '}
26
+ <span className="font-medium text-theme-text-primary">
27
+ {hint.atLeast ? 'At least ' : ''}{hint.count.toLocaleString()} {noun}
28
+ </span>{' '}
29
+ {hint.count === 1 ? 'is' : 'are'} in other namespaces.
30
+ </p>
31
+ {onShowAll && (
32
+ <button
33
+ type="button"
34
+ onClick={onShowAll}
35
+ className="px-3 py-1.5 rounded-md text-sm font-medium bg-accent-muted text-accent-text hover:bg-theme-hover transition-colors"
36
+ >
37
+ Show all namespaces
38
+ </button>
39
+ )}
40
+ </div>
41
+ )
42
+ }
@@ -0,0 +1,157 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
4
+ import { createRoot, type Root } from 'react-dom/client'
5
+ import { afterEach, expect, it, vi } from 'vitest'
6
+ import { DockProvider, ResourceActionsBar, useDock } from '@skyhook-io/k8s-ui'
7
+ import { observeConnectionStatus, resetConnectionBindingForTest } from '../../api/connectionBinding'
8
+ import { PodDebugAction } from './PodDebugAction'
9
+
10
+ vi.mock('../../context/ConnectionContext', () => ({ useConnection: () => ({connection:{context:'test-context'}}) }))
11
+
12
+ ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
13
+ const running = { running: {} }
14
+ const pod = {
15
+ apiVersion: 'v1', kind: 'Pod',
16
+ metadata: { namespace: 'demo', name: 'api', uid: 'reviewed', annotations: { 'kubectl.kubernetes.io/default-container': 'worker' } },
17
+ spec: { containers: [{ name: 'api' }, { name: 'worker' }], initContainers: [{ name: 'mesh', restartPolicy: 'Always' }] },
18
+ status: {
19
+ phase: 'Running',
20
+ containerStatuses: [{ name: 'api', state: { waiting: {} } }, { name: 'worker', state: running }],
21
+ initContainerStatuses: [{ name: 'mesh', state: running }],
22
+ },
23
+ }
24
+ function Tabs() {
25
+ const { tabs } = useDock()
26
+ return <output>{tabs.map(t => t.containerName).join(',')}</output>
27
+ }
28
+ let root: Root
29
+ let client: QueryClient
30
+ function render(existing = new QueryClient()) {
31
+ client = existing
32
+ const host = document.createElement('div')
33
+ document.body.append(host)
34
+ root = createRoot(host)
35
+ act(() => root.render(<QueryClientProvider client={client}><DockProvider><PodDebugAction pod={pod} defaultImage="mirror.example/debug" /><Tabs /></DockProvider></QueryClientProvider>))
36
+ }
37
+ afterEach(() => {
38
+ act(() => root.unmount())
39
+ document.body.replaceChildren()
40
+ resetConnectionBindingForTest()
41
+ vi.unstubAllGlobals()
42
+ })
43
+ function click(label: string) {
44
+ const button = [...document.querySelectorAll('button')].find(b => b.textContent?.trim() === label)
45
+ expect(button).toBeDefined()
46
+ act(() => button!.click())
47
+ }
48
+
49
+ it.each([false, true])('submits the reviewed running target once, keeping the default image on the server (switch=%s)', async switched => {
50
+ let finish!: (r: Response) => void
51
+ const fetch = vi.fn(() => new Promise<Response>(resolve => { finish = resolve }))
52
+ vi.stubGlobal('fetch', fetch)
53
+ observeConnectionStatus({ connectionId: 'reviewed-connection' })
54
+ render()
55
+ click('Debug')
56
+ const select = document.querySelector('select')!
57
+ expect(Array.from(select.options, o => o.value)).toEqual(['worker', 'mesh'])
58
+ expect(select.value).toBe('worker')
59
+ click('Start debug container')
60
+ click('Start debug container')
61
+ await act(async () => { await Promise.resolve() })
62
+ expect(fetch).toHaveBeenCalledTimes(1)
63
+ const [url, init] = fetch.mock.calls[0] as unknown as [string, RequestInit]
64
+ expect(url).toBe('/api/pods/demo/api/debug')
65
+ expect(new Headers(init.headers).get('X-Radar-Connection')).toBe('reviewed-connection')
66
+ expect(JSON.parse(String(init.body))).toEqual({ uid: 'reviewed', targetContainer: 'worker', returnImmediately: true })
67
+ if (switched) observeConnectionStatus({ connectionId: 'next-cluster' })
68
+ await act(async () => { finish(new Response(JSON.stringify({ containerName: 'debug-1', status: 'pending' }))) })
69
+ expect(document.querySelector('output')!.textContent).toBe(switched ? '' : 'debug-1')
70
+ })
71
+
72
+ it.each([
73
+ [503, { error: 'No serving connection', error_code: 'cluster_unavailable' }, false],
74
+ [502, { error: 'Proxy lost the response' }, true],
75
+ ] as const)('distinguishes a retryable refusal from an uncertain write (%s)', async (status, body, unknown) => {
76
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify(body), { status })))
77
+ render()
78
+ click('Debug')
79
+ await act(async () => { click('Start debug container') })
80
+ const start = [...document.querySelectorAll('button')].find(button => button.textContent === 'Start debug container')!
81
+ expect(start.disabled).toBe(unknown)
82
+ if (unknown) {
83
+ act(() => root.unmount())
84
+ render(client)
85
+ click('Debug')
86
+ const retry = [...document.querySelectorAll('button')].find(button => button.textContent === 'Start debug container')!
87
+ expect(retry.disabled).toBe(true)
88
+ click('I checked the Pod YAML')
89
+ expect(retry.disabled).toBe(false)
90
+ }
91
+ })
92
+
93
+ it('opens an accepted session in the dock if its Pod details closed during the request', async () => {
94
+ let finish!: (response: Response) => void
95
+ vi.stubGlobal('fetch', vi.fn(() => new Promise<Response>(resolve => { finish = resolve })))
96
+ render()
97
+ click('Debug')
98
+ await act(async () => { click('Start debug container') })
99
+ act(() => root.render(<QueryClientProvider client={client}><DockProvider>{null}<Tabs /></DockProvider></QueryClientProvider>))
100
+ await act(async () => { finish(new Response(JSON.stringify({ containerName: 'debug-name', image: 'mirror.example/debug', status: 'pending' }))) })
101
+ expect(document.querySelector('output')!.textContent).toBe('debug-name')
102
+ })
103
+
104
+ it('keeps the header chooser open on a confirmed denial after a refused write', () => {
105
+ const fetch = vi.fn()
106
+ vi.stubGlobal('fetch', fetch)
107
+ render()
108
+ click('Debug')
109
+ act(() => root.render(<QueryClientProvider client={client}><DockProvider>
110
+ <PodDebugAction pod={pod} debugDenial={{ refusal: 'The image policy refused this request' }} /><Tabs />
111
+ </DockProvider></QueryClientProvider>))
112
+ const dialog = document.querySelector('[role="dialog"]')!
113
+ expect(dialog.textContent).toContain('Ask your cluster admin for access to update pods/ephemeralcontainers for Pod demo/api.')
114
+ expect(dialog.textContent).toContain('The image policy refused this request')
115
+ expect(dialog.textContent).not.toContain('Start debug container')
116
+ expect(fetch).not.toHaveBeenCalled()
117
+ click('Close')
118
+ click('Debug')
119
+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Ask your cluster admin for access')
120
+ })
121
+
122
+ it.each([
123
+ ['allowed', 'mirror.example/debug', undefined, '', true],
124
+ ['named denial', undefined, {}, 'Ask your cluster admin for access', false],
125
+ ['completed undecided update with verified exec', 'mirror.example/debug', undefined, '', true],
126
+ ['completed undecided review without verified exec', undefined, undefined, 'Access is unconfirmed', false],
127
+ ['failed update review', undefined, undefined, 'Kubernetes couldn’t complete the check', false],
128
+ ['Radar HTTP failure', undefined, undefined, 'The permission request failed', false],
129
+ ['exec disabled', undefined, undefined, 'Debugging is unavailable', false],
130
+ ['hosted', undefined, undefined, 'This view can’t add a debug container', false],
131
+ ['changed connection', 'mirror.example/debug', undefined, 'The cluster connection changed', false],
132
+ ] as const)('an open header review stays mounted through %s', (state, image, denial, message, canSubmit) => {
133
+ const div = document.createElement('div')
134
+ document.body.append(div)
135
+ root = createRoot(div)
136
+ client = new QueryClient()
137
+ function draw(initial: boolean) {
138
+ const unverified = !initial && state === 'completed undecided update with verified exec'
139
+ const recheck = vi.fn().mockResolvedValue(undefined)
140
+ act(() => root.render(<QueryClientProvider client={client}><DockProvider>
141
+ <ResourceActionsBar resource={{ kind: 'pods', namespace: 'demo', name: 'api' }} data={pod} canExec={initial || canSubmit}
142
+ podDebugAction={<PodDebugAction pod={pod} defaultImage={initial ? 'mirror.example/debug' : image} debugDenial={initial ? undefined : denial}
143
+ unverifiedReview={unverified ? { refused: undefined, recheckAccess: recheck, rememberRefusal: vi.fn(), clearRefusal: vi.fn() } : undefined}
144
+ reviewStatus={{ message, refusal: undefined, checking: false, recheck: state === 'hosted' ? undefined : recheck }} />} />
145
+ </DockProvider></QueryClientProvider>))
146
+ }
147
+ draw(true)
148
+ click('Debug')
149
+ if (state === 'changed connection') observeConnectionStatus({ connectionId: 'replacement' })
150
+ draw(false)
151
+ const dialog = document.querySelector('[role="dialog"]')!
152
+ expect(dialog.textContent).toContain(message)
153
+ const start = [...dialog.querySelectorAll('button')].find(button => button.textContent === 'Start debug container')
154
+ expect(!!start && !start.disabled).toBe(canSubmit)
155
+ expect(dialog.textContent?.includes('Ask your cluster admin for access')).toBe(state === 'named denial')
156
+ expect(dialog.textContent?.includes('Recheck access')).toBe(!canSubmit && state !== 'hosted' && state !== 'changed connection')
157
+ })
@@ -0,0 +1,207 @@
1
+ import { useLayoutEffect, useRef, useState } from 'react'
2
+ import { Bug } from 'lucide-react'
3
+ import { ActionConfirmDialog, getDefaultContainerName, getExecContainerNames, useOpenTerminal, type ActionConfirmResult } from '@skyhook-io/k8s-ui'
4
+ import { PodDebugPermission, PodDebugPermissionScope, usePodDebugContext } from './PodDebugPermission'
5
+ import { Tooltip } from '../ui/Tooltip'
6
+ import { actionDialogResult } from '../../api/actions'
7
+ import { ApiError } from '../../api/client'
8
+ import { connectionHeaderValue } from '../../api/connectionBinding'
9
+ import { getApiBase } from '../../api/config'
10
+ import { useReviewedActionMutation } from '../../api/reviewedActionMutation'
11
+ import { useCapabilitiesContext } from '../../contexts/CapabilitiesContext'
12
+ import { useNavCustomization } from '../../context/NavCustomization'
13
+ import { createPodDebugContainer, usePodDebugAccess } from '../../api/podDebug'
14
+
15
+ export interface PodDebugTarget {
16
+ apiVersion: string
17
+ kind: string
18
+ metadata: { uid: string; name: string; namespace: string; deletionTimestamp?: string }
19
+ spec: {
20
+ containers: { name: string }[]
21
+ ephemeralContainers?: { name: string; image: string; targetContainerName?: string }[]
22
+ initContainers?: { name: string; restartPolicy?: string }[]
23
+ os?: { name?: string }
24
+ nodeSelector?: Record<string, string>
25
+ }
26
+ status: {
27
+ phase?: string
28
+ ephemeralContainerStatuses?: { name: string; state?: {
29
+ running?: { startedAt?: string }
30
+ waiting?: { reason?: string; message?: string }
31
+ terminated?: { exitCode: number; reason?: string; message?: string }
32
+ } }[]
33
+ containerStatuses?: ContainerStatus[]
34
+ initContainerStatuses?: ContainerStatus[]
35
+ }
36
+ }
37
+
38
+ interface ContainerStatus {
39
+ name: string
40
+ state?: Partial<Record<'running' | 'waiting' | 'terminated', object>>
41
+ }
42
+
43
+ export function runningPodDebugTargets(pod: PodDebugTarget): string[] | undefined {
44
+ const os = pod.spec?.os?.name || pod.spec?.nodeSelector?.['kubernetes.io/os'] || pod.spec?.nodeSelector?.['beta.kubernetes.io/os']
45
+ if (!pod.metadata.uid || pod.apiVersion !== 'v1' || pod.kind !== 'Pod' || pod.status.phase !== 'Running' || pod.metadata.deletionTimestamp || os?.toLowerCase() === 'windows') return undefined
46
+ return getExecContainerNames(pod, { runningOnly: true })
47
+ }
48
+
49
+ export function debugAccessMessage(readOnly: boolean, error: unknown, state: string | undefined, pod: PodDebugTarget | undefined) {
50
+ if (readOnly) return 'This view can’t add a debug container.'
51
+ if (state === 'unavailable' && !error) return 'Debugging is unavailable. Check Pod exec access and whether exec is enabled on this Radar.'
52
+ const reason = error ? 'Radar couldn’t check' : state === 'check_failed' ? 'Kubernetes couldn’t complete the check for' : 'Kubernetes couldn’t confirm'
53
+ return <>{reason} permission to <PodDebugPermissionScope pod={pod?.metadata} />.</>
54
+ }
55
+
56
+ export function usePodDetailAccess(pod: PodDebugTarget | undefined, namespace: {
57
+ canExec: boolean; canOpenEphemeralTerminal: boolean; podDebugImage?: string
58
+ }) {
59
+ const { embedded } = useNavCustomization()
60
+ const { deployment } = useCapabilitiesContext()
61
+ const eligible = pod?.apiVersion === 'v1' && pod.kind === 'Pod' && pod.status.phase === 'Running' && !pod.metadata.deletionTimestamp
62
+ const execOnly = !!embedded || deployment?.mode === 'cloud' || !pod || !runningPodDebugTargets(pod)?.length
63
+ const { query, unverifiedImage, unverifiedReview, recheckAccess } = usePodDebugAccess(pod?.metadata.namespace ?? '', pod?.metadata.name ?? '', pod?.metadata.uid ?? '',
64
+ !!eligible && (!namespace.canExec || (!execOnly && !namespace.podDebugImage)), execOnly, eligible && !execOnly ? namespace.podDebugImage : undefined)
65
+ const named = eligible && !query.error ? query.data : undefined
66
+ const debugImage = execOnly || query.error || named?.state === 'denied' || named?.state === 'unavailable' || named?.state === 'check_failed' ? undefined :
67
+ named?.state === 'allowed' ? named.image : namespace.podDebugImage || unverifiedImage
68
+ const readOnly = !!embedded || deployment?.mode === 'cloud'
69
+ return {
70
+ canExec: namespace.canExec || named?.exec === true,
71
+ canOpenEphemeralTerminal: namespace.canOpenEphemeralTerminal || named?.exec === true,
72
+ debugImage,
73
+ reviewStatus: { message: debugAccessMessage(readOnly, query.error, named?.state, pod), refusal: readOnly ? undefined : query.data?.refusedAttempt?.message,
74
+ recheck: readOnly ? undefined : recheckAccess, checking: query.isFetching },
75
+ debugDenial: !execOnly && named?.state === 'denied' ? { refusal: named.refusedAttempt?.message } : undefined,
76
+ unverifiedReview: namespace.podDebugImage ? undefined : unverifiedReview,
77
+ }
78
+ }
79
+
80
+ export function PodDebugAction({ pod, defaultImage, failedContainer, unverifiedReview, debugDenial, reviewStatus, hideLauncher }: {
81
+ pod: PodDebugTarget; defaultImage?: string; hideLauncher?: boolean; failedContainer?: string; debugDenial?: { refusal?: string }; unverifiedReview?: ReturnType<typeof usePodDebugAccess>['unverifiedReview']; reviewStatus?: ReturnType<typeof usePodDetailAccess>['reviewStatus']
82
+ }) {
83
+ const openTerminal = useOpenTerminal()
84
+ const eligibleTargets = runningPodDebugTargets(pod)
85
+ const targets = eligibleTargets ?? []
86
+ const context = usePodDebugContext()
87
+ const [draft, setDraft] = useState<{ target: string; image: string; base: string; connection?: string; context?: string }>()
88
+ const [result, setResult] = useState<ActionConfirmResult>()
89
+ const submitting = useRef(false)
90
+ const mounted = useRef(false)
91
+ useLayoutEffect(() => {
92
+ mounted.current = true
93
+ return () => { mounted.current = false }
94
+ }, [])
95
+
96
+ const { namespace, name, uid } = pod.metadata
97
+ const connection = connectionHeaderValue()
98
+ const mutation = useReviewedActionMutation(
99
+ JSON.stringify([getApiBase(), 'pod-debug', uid]), connection ?? '', {
100
+ mutationFn: ({ request }: { request: { reviewedContext: string; base: string; targetContainer: string; image?: string } }) => {
101
+ if (getApiBase() !== request.base || (connectionHeaderValue() ?? '') !== request.reviewedContext) {
102
+ throw new ApiError('The cluster connection changed. Reopen the Pod to debug it.', 409)
103
+ }
104
+ return createPodDebugContainer(namespace, name, request.reviewedContext || undefined, {
105
+ uid, targetContainer: request.targetContainer, image: request.image,
106
+ })
107
+ },
108
+ }, '',
109
+ )
110
+ const changedConnection = !!draft && (draft.base !== getApiBase() || draft.connection !== connection)
111
+ const blockedMessage = changedConnection ? 'The cluster connection changed. Reopen the Pod to debug it.' :
112
+ !eligibleTargets?.length ? 'This Pod no longer has a running container eligible for debugging.' :
113
+ !debugDenial && !defaultImage ? reviewStatus?.message : undefined
114
+ const canReview = !blockedMessage && !debugDenial
115
+ const previousRefusal = !changedConnection && (debugDenial?.refusal || (blockedMessage && reviewStatus?.refusal))
116
+ const busy = mutation.isPending
117
+ const refused = unverifiedReview?.refused
118
+ const refusedNow = result?.state === 'error' && mutation.error instanceof ApiError && mutation.error.status === 403 && !!unverifiedReview
119
+ const recheckRequired = !!refused && !refused.rechecked
120
+ const outcome = result ?? actionDialogResult(mutation.outcomeError, {
121
+ unknown: 'Radar could not confirm whether the debug container was added',
122
+ })
123
+ function show() {
124
+ if (!defaultImage && !debugDenial) return
125
+ const preferred = failedContainer || getDefaultContainerName(pod)
126
+ const connection = connectionHeaderValue()
127
+ setDraft({ target: preferred && targets.includes(preferred) ? preferred : targets[0], image: defaultImage ?? '', base: getApiBase(), connection, context })
128
+ }
129
+
130
+ async function start() {
131
+ if (!draft || !defaultImage || debugDenial || blockedMessage || submitting.current || refusedNow || recheckRequired || !targets.includes(draft.target)) return
132
+ const sameConnection = () => getApiBase() === draft.base && connectionHeaderValue() === draft.connection
133
+ submitting.current = true
134
+ setResult(undefined)
135
+ try {
136
+ const { containerName, image } = await mutation.mutateAsync({ request: {
137
+ base: draft.base, reviewedContext: draft.connection ?? '', targetContainer: draft.target, image: draft.image.trim() === defaultImage ? undefined : draft.image.trim() || undefined,
138
+ } })
139
+ unverifiedReview?.clearRefusal()
140
+ if (!sameConnection()) return
141
+ openTerminal({
142
+ namespace, podName: name, containerName, containers: [containerName],
143
+ debugSession: { connectionId: draft.connection, apiBase: draft.base, podUID: uid, image },
144
+ })
145
+ if (mounted.current) setDraft(undefined)
146
+ } catch (error) {
147
+ if (mounted.current && sameConnection()) setResult(actionDialogResult(error instanceof Error ? error : new Error(String(error)), {
148
+ unknown: 'Radar could not confirm whether the debug container was added',
149
+ }))
150
+ } finally {
151
+ submitting.current = false
152
+ if (mounted.current && !sameConnection()) setDraft(undefined)
153
+ }
154
+ }
155
+
156
+ if (!draft && (!targets.length || (!defaultImage && !debugDenial))) return null
157
+ return <>
158
+ {!hideLauncher && targets.length > 0 && (debugDenial ? <Tooltip content="View the permission needed to debug this Pod">
159
+ <button type="button" className="btn-secondary flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium" onClick={show}><Bug className="h-3.5 w-3.5" />Debug</button>
160
+ </Tooltip> : defaultImage && <button type="button" className={`${failedContainer ? 'btn-brand' : 'btn-secondary'} flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium`} onClick={show}>
161
+ <Bug className="h-3.5 w-3.5" />{unverifiedReview ? recheckRequired ? 'Review debug refusal' : refused ? 'Review another debug attempt' : 'Review debug container' : failedContainer ? 'Start a debug container' : 'Debug'}
162
+ </button>)}
163
+ <ActionConfirmDialog open={!!draft} title="Debug Pod" context={draft?.context} writes={canReview ? [{ summary: `Update pods/ephemeralcontainers on ${namespace}/${name}` }] : []} subject={{ kind: 'Pod', namespace, name }}
164
+ effect={blockedMessage || (debugDenial ? <PodDebugPermission namespace={namespace} name={name} /> : 'Start an ephemeral container and open a terminal in it. Its entry stays on the Pod until the Pod is deleted.')}
165
+ onClose={() => {
166
+ if (submitting.current) return
167
+ setDraft(undefined)
168
+ if (refusedNow && mutation.error) unverifiedReview?.rememberRefusal(mutation.error.message)
169
+ if (result?.state === 'error') setResult(undefined)
170
+ }}
171
+ onConfirm={canReview ? start : undefined} confirmLabel="Start debug container" isLoading={busy} result={outcome}
172
+ guard={outcome?.state === 'unknown' && <div className="space-y-2">
173
+ <p>Inspect the Pod YAML for an added ephemeral container before you retry.</p>
174
+ <button type="button" className="btn-secondary px-3 py-1.5 text-sm"
175
+ onClick={() => {
176
+ mutation.acknowledgeOutcome()
177
+ setResult(undefined)
178
+ }}>I checked the Pod YAML</button></div>}
179
+ incompleteReason={!canReview ? undefined : refusedNow ? 'Close to recheck access after the refusal.' : recheckRequired ? 'Recheck access before reviewing another attempt.' : draft && !targets.includes(draft.target) ? 'Select a running container.' : undefined}>
180
+ {previousRefusal &&
181
+ <div className="text-warning-text"><p>The last debug request was refused.</p><p className="break-words">{previousRefusal}</p></div>}
182
+ {!canReview && !changedConnection && reviewStatus?.recheck &&
183
+ <button type="button" className="btn-secondary px-2 py-1" disabled={reviewStatus.checking} onClick={() => void reviewStatus.recheck?.()}>{reviewStatus.checking ? 'Checking…' : 'Recheck access'}</button>}
184
+ {draft && canReview && <div className="grid gap-3">
185
+ {refused && <div className="space-y-1 text-sm text-warning-text"><p>The last debug request was refused.</p><p className="break-words">{refused.message}</p>
186
+ {recheckRequired && <button type="button" className="btn-secondary px-2 py-1" onClick={() => void unverifiedReview?.recheckAccess()}>Recheck access</button>}</div>}
187
+ {unverifiedReview && <p className="text-sm text-theme-text-secondary">Radar verified terminal access to this Pod. Kubernetes will decide whether to allow <code className="inline-code">update pods/ephemeralcontainers</code> when you confirm.</p>}
188
+ <label className="grid gap-1">Target container
189
+ <select className="rounded border border-theme-border bg-theme-surface px-2 py-1.5" value={draft.target} disabled={busy}
190
+ onChange={event => setDraft({ ...draft, target: event.target.value })}>
191
+ {!targets.includes(draft.target) && <option value={draft.target} disabled>{draft.target} (stopped)</option>}
192
+ {targets.map(name => <option key={name} value={name}>{name}</option>)}
193
+ </select>
194
+ </label>
195
+ <label className="grid gap-1">Debug image
196
+ <input className="rounded border border-theme-border bg-theme-surface px-2 py-1.5" placeholder={defaultImage} value={draft.image} disabled={busy}
197
+ onChange={event => setDraft({ ...draft, image: event.target.value })} />
198
+ <span className="text-xs text-theme-text-tertiary">
199
+ {draft.image.trim() && draft.image.trim() !== defaultImage
200
+ ? <>Server default: <code className="inline-code">{defaultImage}</code></>
201
+ : 'Using the server default. Edit to override it for this container.'}
202
+ </span>
203
+ </label>
204
+ </div>}
205
+ </ActionConfirmDialog>
206
+ </>
207
+ }
@@ -0,0 +1,21 @@
1
+ import { connectionHeaderValue } from '../../api/connectionBinding'
2
+ import { useConnection } from '../../context/ConnectionContext'
3
+ import { useCapabilitiesContext } from '../../contexts/CapabilitiesContext'
4
+
5
+ export function usePodDebugContext() {
6
+ const { connection } = useConnection()
7
+ if (connection.connectionId !== connectionHeaderValue()) return undefined
8
+ return connection.context === 'in-cluster' ? connection.clusterName || connection.context : connection.context
9
+ }
10
+
11
+ export function PodDebugPermissionScope({ pod }: { pod?: { namespace: string; name: string } }) {
12
+ return <><code className="inline-code">update pods/ephemeralcontainers</code> for {pod
13
+ ? <>Pod <code className="inline-code break-all">{pod.namespace}/{pod.name}</code></>
14
+ : 'this Pod'}</>
15
+ }
16
+
17
+ export function PodDebugPermission({ namespace, name }: { namespace: string; name: string }) {
18
+ const { username, authEnabled, deployment } = useCapabilitiesContext()
19
+ const sharedServiceAccount = !username && !authEnabled && deployment?.mode === 'in-cluster'
20
+ return <>Ask your cluster admin {sharedServiceAccount ? 'to grant Radar’s ServiceAccount access' : 'for access'} to <PodDebugPermissionScope pod={{ namespace, name }} />.</>
21
+ }
@@ -0,0 +1,132 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { MemoryRouter } from 'react-router-dom'
5
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
6
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
7
+ import { ResourcesView } from './ResourcesView'
8
+
9
+ vi.mock('../../context/ConnectionContext', () => ({ useConnection: () => ({ connection: { state: 'connected', context: 'test' } }) }))
10
+ vi.mock('../dock', () => ({ useOpenLogs: () => () => {}, useOpenWorkloadLogs: () => () => {} }))
11
+ vi.mock('../../context/RadarUpgradeHost', () => ({ useRadarUpgradeHost: () => ({}) }))
12
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
13
+
14
+ const completeAll = { status: 'complete', scope: { type: 'all_namespaces' }, gaps: [] }
15
+ const narrowedAll = { status: 'complete', scope: { type: 'all_namespaces' }, narrowedBy: ['user_access'], gaps: [] }
16
+ const completeScoped = (ns: string) => ({ status: 'complete', scope: { type: 'namespaces', namespaces: { names: [ns], count: 1 } }, gaps: [] })
17
+
18
+ const apiResourcesFixture = [
19
+ { name: 'pods', kind: 'Pod', group: '', version: 'v1', namespaced: true, verbs: ['get', 'list'], isCrd: false },
20
+ { name: 'certificates', kind: 'Certificate', group: 'cert-manager.io', version: 'v1', namespaced: true, verbs: ['get', 'list'], isCrd: true },
21
+ ]
22
+
23
+ function jsonResponse(body: unknown) {
24
+ return Promise.resolve(new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } }))
25
+ }
26
+
27
+ let host: HTMLDivElement
28
+ let root: ReturnType<typeof createRoot>
29
+ let client: QueryClient
30
+
31
+ beforeEach(() => {
32
+ vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener: () => {}, removeEventListener: () => {} }))
33
+ Element.prototype.scrollIntoView = vi.fn()
34
+ host = document.createElement('div')
35
+ document.body.append(host)
36
+ root = createRoot(host)
37
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
38
+ })
39
+
40
+ afterEach(async () => {
41
+ await act(async () => root.unmount())
42
+ host.remove()
43
+ client.clear()
44
+ vi.unstubAllGlobals()
45
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
46
+ })
47
+
48
+ async function flush() {
49
+ for (let i = 0; i < 6; i++) {
50
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 10)) })
51
+ }
52
+ }
53
+
54
+ function setupFetch(options: {
55
+ scope?: 'pending' | Record<string, unknown>
56
+ listCoverage?: Record<string, unknown>
57
+ allCounts?: Record<string, unknown>
58
+ }) {
59
+ const requested: URL[] = []
60
+ vi.stubGlobal('fetch', vi.fn((input: RequestInfo | URL) => {
61
+ const url = new URL(String(input), 'http://radar.invalid')
62
+ requested.push(url)
63
+ if (url.pathname.endsWith('/api-resources')) return jsonResponse(apiResourcesFixture)
64
+ if (url.pathname.endsWith('/capabilities')) return jsonResponse({ workloadWrites: {} })
65
+ if (url.pathname.endsWith('/cluster/namespace-scope')) {
66
+ if (options.scope === 'pending') return new Promise<Response>(() => {})
67
+ return jsonResponse(options.scope)
68
+ }
69
+ if (url.pathname.endsWith('/resource-counts')) {
70
+ const ns = url.searchParams.get('namespaces')
71
+ if (!ns) return jsonResponse(options.allCounts ?? { counts: { Pod: 15, 'cert-manager.io/Certificate': 12 }, coverage: { Pod: completeAll, 'cert-manager.io/Certificate': completeAll } })
72
+ return jsonResponse({ counts: { Pod: 0, 'cert-manager.io/Certificate': 0 }, coverage: { Pod: completeScoped(ns), 'cert-manager.io/Certificate': completeScoped(ns) } })
73
+ }
74
+ if (url.pathname.includes('/metrics/')) return jsonResponse([])
75
+ if (url.pathname.includes('/resources/')) {
76
+ return jsonResponse({ items: [], coverage: options.listCoverage ?? completeScoped('staging') })
77
+ }
78
+ return jsonResponse({})
79
+ }))
80
+ return requested
81
+ }
82
+
83
+ async function renderView(initialEntry: string, namespaces: string[]) {
84
+ await act(async () => {
85
+ root.render(
86
+ <QueryClientProvider client={client}>
87
+ <MemoryRouter initialEntries={[initialEntry]}>
88
+ <ResourcesView namespaces={namespaces} selectedResource={null} onResourceClick={() => {}} onClearNamespaces={() => {}} />
89
+ </MemoryRouter>
90
+ </QueryClientProvider>,
91
+ )
92
+ })
93
+ await flush()
94
+ }
95
+
96
+ it('resolves canonical CRD count keys on direct URL load', async () => {
97
+ setupFetch({
98
+ scope: { actives: ['staging'], context: 'test', accessChecked: true, kubeconfigNamespace: '', mode: 'namespace', accessibleNamespaces: ['default', 'staging'], deniedNamespaces: [], authoritative: true, canClearNamespace: true, cacheScoped: false, namespaceRescope: false },
99
+ })
100
+ await renderView('/resources/certificates?apiGroup=cert-manager.io', ['staging'])
101
+ expect(host.textContent).toContain('Filtered to staging. 12 Certificates are in other namespaces.')
102
+ expect(host.textContent).toContain('Show all namespaces')
103
+ })
104
+
105
+ it('waits for namespaceScope before requesting unfiltered counts (prevents --namespace-scope load race)', async () => {
106
+ const requested = setupFetch({ scope: 'pending' })
107
+ await renderView('/resources/pods', ['other-ns'])
108
+ const unfilteredCounts = requested.filter(u => u.pathname.endsWith('/resource-counts') && !u.searchParams.get('namespaces'))
109
+ expect(unfilteredCounts).toHaveLength(0)
110
+ expect(host.textContent).not.toContain('are in other namespaces')
111
+ })
112
+
113
+ it('hides Show all namespaces when canClearNamespace is false', async () => {
114
+ setupFetch({
115
+ scope: { actives: ['team-a'], context: 'test', accessChecked: true, kubeconfigNamespace: '', mode: 'namespace', accessibleNamespaces: ['team-a'], deniedNamespaces: [], authoritative: false, canClearNamespace: false, cacheScoped: false, namespaceRescope: false },
116
+ allCounts: { counts: { Pod: 8 }, coverage: { Pod: narrowedAll } },
117
+ })
118
+ await renderView('/resources/pods', ['team-a'])
119
+ expect(host.textContent).toContain('Filtered to team-a. At least 8 Pods are in other namespaces.')
120
+ expect(host.textContent).not.toContain('Show all namespaces')
121
+ })
122
+
123
+ it('skips unfiltered counts while a selected namespace is still syncing', async () => {
124
+ const requested = setupFetch({
125
+ scope: { actives: ['staging', 'syncing'], context: 'test', accessChecked: true, kubeconfigNamespace: '', mode: 'namespace', accessibleNamespaces: ['staging', 'syncing', 'prod'], deniedNamespaces: [], authoritative: true, canClearNamespace: true, cacheScoped: false, namespaceRescope: false },
126
+ listCoverage: { status: 'partial', scope: { type: 'namespaces', namespaces: { names: ['staging', 'syncing'], count: 2 } }, gaps: [{ code: 'kind_sync_pending', namespaces: { names: ['syncing'], count: 1 } }] },
127
+ })
128
+ await renderView('/resources/pods', ['staging', 'syncing'])
129
+ const unfilteredCounts = requested.filter(u => u.pathname.endsWith('/resource-counts') && !u.searchParams.get('namespaces'))
130
+ expect(unfilteredCounts).toHaveLength(0)
131
+ expect(host.textContent).not.toContain('are in other namespaces')
132
+ })