@skyhook-io/radar-app 1.21.6 → 1.21.7

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 (107) hide show
  1. package/README.md +1 -1
  2. package/package.json +7 -7
  3. package/src/App.tsx +19 -1
  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 +572 -111
  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/applications/ApplicationsView.openResource.test.tsx +137 -11
  32. package/src/components/applications/ApplicationsView.tsx +56 -31
  33. package/src/components/cnpg/host.test.tsx +1 -1
  34. package/src/components/cnpg/host.tsx +0 -2
  35. package/src/components/dock/BottomDock.tsx +7 -3
  36. package/src/components/dock/MissingShellDebug.test.tsx +193 -0
  37. package/src/components/dock/MissingShellDebug.tsx +114 -0
  38. package/src/components/dock/PodDebugSession.test.tsx +60 -0
  39. package/src/components/dock/PodDebugSession.tsx +96 -0
  40. package/src/components/dock/TerminalTab.test.tsx +48 -4
  41. package/src/components/dock/TerminalTab.tsx +47 -25
  42. package/src/components/dock/WorkloadLogsTab.test.tsx +24 -1
  43. package/src/components/dock/WorkloadLogsTab.tsx +16 -0
  44. package/src/components/execution/BatchExecutionView.command.test.tsx +69 -0
  45. package/src/components/execution/BatchExecutionView.tsx +88 -5
  46. package/src/components/execution/BatchExecutionView.workflow-stop.test.tsx +69 -0
  47. package/src/components/execution/WorkflowRunStopAction.tsx +8 -0
  48. package/src/components/gitops/GitOpsPermissionRowActions.test.tsx +100 -0
  49. package/src/components/gitops/GitOpsPermissionRowActions.tsx +27 -0
  50. package/src/components/gitops/GitOpsView.identity.test.tsx +1 -0
  51. package/src/components/gitops/GitOpsView.permissions.test.tsx +102 -0
  52. package/src/components/gitops/GitOpsView.syncRequest.test.tsx +95 -7
  53. package/src/components/gitops/GitOpsView.tsx +93 -32
  54. package/src/components/helm/OwnedResources.tsx +1 -0
  55. package/src/components/home/mcpToolCatalog.ts +1 -0
  56. package/src/components/issues/IssuesPane.render.test.tsx +1 -1
  57. package/src/components/issues/IssuesPane.tsx +11 -0
  58. package/src/components/issues/useIssueExpansion.ts +91 -0
  59. package/src/components/resource/MetricsNotConnected.test.tsx +50 -0
  60. package/src/components/resource/MetricsNotConnected.tsx +114 -0
  61. package/src/components/resource/PVCUsageBar.tsx +2 -1
  62. package/src/components/resource/PrometheusCharts.render.test.tsx +47 -0
  63. package/src/components/resource/PrometheusCharts.tsx +14 -2
  64. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +91 -1
  65. package/src/components/resource/PrometheusChartsGrid.tsx +28 -52
  66. package/src/components/resource/RestartChart.tsx +4 -3
  67. package/src/components/resource/RightsizingPanel.source.test.tsx +34 -0
  68. package/src/components/resource/RightsizingStrip.tsx +5 -3
  69. package/src/components/resource/WorkloadMetricsSection.render.test.tsx +6 -0
  70. package/src/components/resource/WorkloadMetricsSection.tsx +14 -11
  71. package/src/components/resource/nameMatchedScope.ts +9 -3
  72. package/src/components/resources/EmptyNamespaceHint.tsx +42 -0
  73. package/src/components/resources/PodDebugAction.test.tsx +157 -0
  74. package/src/components/resources/PodDebugAction.tsx +207 -0
  75. package/src/components/resources/PodDebugPermission.tsx +21 -0
  76. package/src/components/resources/ResourcesView.empty-hint.test.tsx +132 -0
  77. package/src/components/resources/ResourcesView.tsx +39 -5
  78. package/src/components/resources/namespaceHint.test.ts +34 -0
  79. package/src/components/resources/namespaceHint.ts +19 -0
  80. package/src/components/resources/renderers/AdmissionPolicyRenderers.tsx +135 -0
  81. package/src/components/resources/renderers/NodeRenderer.tsx +2 -1
  82. package/src/components/resources/renderers/PodRenderer.tsx +12 -5
  83. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.test.tsx +24 -1
  84. package/src/components/settings/LocalIntegrationStatus.tsx +14 -3
  85. package/src/components/settings/MetricsBackendSwitch.tsx +167 -0
  86. package/src/components/settings/OpenObserveSetup.test.tsx +343 -0
  87. package/src/components/settings/OpenObserveSetup.tsx +358 -0
  88. package/src/components/settings/SettingsDialog.tsx +21 -7
  89. package/src/components/settings/openobserveStatus.test.ts +34 -0
  90. package/src/components/settings/openobserveStatus.ts +55 -0
  91. package/src/components/timeline/TimelineList.selection.test.tsx +40 -0
  92. package/src/components/timeline/TimelineList.test.ts +18 -0
  93. package/src/components/timeline/TimelineList.tsx +19 -5
  94. package/src/components/timeline/TimelineView.tsx +2 -0
  95. package/src/components/workload/WorkloadView.pendingOwnership.test.tsx +34 -0
  96. package/src/components/workload/WorkloadView.tabUrl.test.tsx +44 -0
  97. package/src/components/workload/WorkloadView.tsx +95 -10
  98. package/src/context/TimelineNavigation.test.ts +59 -0
  99. package/src/context/TimelineNavigation.tsx +86 -0
  100. package/src/contexts/CapabilitiesContext.tsx +3 -1
  101. package/src/hooks/useResourceCounts.ts +2 -1
  102. package/src/hooks/useWorkflowStopAction.ts +31 -0
  103. package/src/index.css +1 -0
  104. package/src/integrations/resourceHosts.test.tsx +2 -2
  105. package/src/integrations/resourceHosts.tsx +4 -2
  106. package/src/k8s-ui-exports.test.ts +10 -0
  107. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.tsx +0 -128
@@ -19,7 +19,7 @@ import {
19
19
  import { latestWorkloadValue, workloadPodValues } from "./workloadMetricValues";
20
20
  import { WorkloadMetricsHelpDialog } from './WorkloadMetricsHelpDialog';
21
21
  import { Disclosure } from '@skyhook-io/k8s-ui/components/ui/Disclosure';
22
- import { leastCertainScope, NAME_MATCHED_CLUSTER_NOTE, NAME_MATCHED_SUMMARY } from './nameMatchedScope';
22
+ import { leastCertainScope, NAME_MATCHED_CLUSTER_NOTE, NAME_MATCHED_SUMMARY, OPENOBSERVE_NOTE } from './nameMatchedScope';
23
23
 
24
24
  interface Props {
25
25
  kind: string;
@@ -58,6 +58,7 @@ export function WorkloadMetricsSection(props: Props) {
58
58
  const memoryNameMatched = usePrometheusResourceMetrics(props.kind, props.namespace, props.name, 'memory', props.range, false).data;
59
59
  const nameMatchedScope = leastCertainScope(nameMatchedFallbacks.map((key) => (key === 'cpu' ? cpuNameMatched : memoryNameMatched)?.clusterScope));
60
60
  const nameMatchedNote = NAME_MATCHED_CLUSTER_NOTE[nameMatchedScope];
61
+ const gke = data?.resourceSource === "gke";
61
62
  const resourceNotice = sameResourceScope ? sharedPanelNotice([data?.panels.cpu, data?.panels.memory, data?.panels.throttling]) : undefined;
62
63
  const hasHistoricalTotals = (['cpu', 'memory'] as const).some((key) => data?.history[key]?.mode === 'workload-history');
63
64
  const hasResourceDetails = hasHistoricalTotals || data?.history.throttling?.mode === 'workload-history' || resourceNotice?.state === 'stale';
@@ -65,26 +66,26 @@ export function WorkloadMetricsSection(props: Props) {
65
66
  <div className="metrics-layout min-w-0 px-4 pt-3 space-y-4">
66
67
  <div className="flex items-start justify-between gap-3">
67
68
  <button type="button" aria-haspopup="dialog" onClick={() => setHelpOpen(true)} className="min-w-0 rounded py-1 text-left text-xs text-theme-text-secondary hover:text-accent-text focus-visible:outline-accent">
68
- <Info aria-hidden="true" className="mr-1 inline h-3.5 w-3.5" />About these metrics{data?.attribution?.scope && ' · operator-asserted scope'}
69
+ <Info aria-hidden="true" className="mr-1 inline h-3.5 w-3.5" />About these metrics{data?.attribution?.scope && (data.attribution.scope.startsWith(OPENOBSERVE_NOTE) ? ' · scoped through OpenObserve' : ' · operator-asserted scope')}
69
70
  </button>
70
71
  {props.controls}
71
72
  </div>
72
73
  {helpOpen && <WorkloadMetricsHelpDialog kind={props.kind} namespace={props.namespace} name={props.name} range={props.range} data={data} pending={isLoading || isPlaceholderData} error={error} onClose={() => setHelpOpen(false)} />}
73
74
  {data?.scopeNotice && <p role="status" className={`text-xs ${SEVERITY_TEXT.warning}`}>{data.scopeNotice}</p>}
74
- {data?.state === 'partial' && data.reason && <p role="status" className={`text-xs ${SEVERITY_TEXT.warning}`}>{data.reason}</p>}
75
+ {(data?.state === 'partial' || (gke && (data?.state === 'unavailable' || data?.state === 'error'))) && data.reason && <p role="status" className={`text-xs ${SEVERITY_TEXT.warning}`}>{data.reason}</p>}
75
76
  {isPlaceholderData && <p role="status" className="text-xs text-theme-text-secondary">Loading selected request source… Resources show previous samples.</p>}
76
- <WorkloadRequests data={data} isLoading={isLoading || isPlaceholderData} error={error} setSource={setSource} />
77
+ {!gke && <WorkloadRequests data={data} isLoading={isLoading || isPlaceholderData} error={error} setSource={setSource} />}
77
78
  {props.workloadTotals}
78
79
  <section aria-label="Workload resource pressure">
79
80
  {(data?.panels.cpu || data?.panels.memory || data?.panels.throttling) && <div className="mb-2 flex flex-wrap items-baseline gap-x-3 gap-y-1">
80
- <h3 className="text-sm font-semibold text-theme-text-primary">{props.workloadTotals ? 'Prometheus resources' : 'Resources'}</h3>
81
+ <h3 className="text-sm font-semibold text-theme-text-primary">{gke ? 'GKE system metrics' : props.workloadTotals ? 'Prometheus resources' : 'Resources'}</h3>
81
82
  {sameResourceScope && <HistoryNotice scope={data?.history.cpu} omitReason={data?.panels.cpu?.reason} />}
82
83
  </div>}
83
84
  {props.restartLane}
84
85
  {resourceNotice && <div className="mb-2"><MetricNotice panel={resourceNotice} label="CPU, memory and throttling" /></div>}
85
- <div className="metrics-chart-grid">
86
+ <div className={gke ? "metrics-chart-grid metrics-chart-pair" : "metrics-chart-grid"}>
86
87
  {data?.panels.cpu && <WorkloadChart label="CPU usage" population={data.history.cpu?.mode === 'workload-history' ? 'workload' : 'per Pod'} panel={data.panels.cpu} window={data} scope={sameResourceScope ? undefined : data.history.cpu} referenceLines={data.history.cpu?.mode === 'current-pods' ? props.cpuReferenceLines : undefined} sharedNotice={!!resourceNotice} />}
87
- {data?.panels.memory && <WorkloadChart label="Memory working set" population={data.history.memory?.mode === 'workload-history' ? 'workload' : 'per Pod'} panel={data.panels.memory} window={data} scope={sameResourceScope ? undefined : data.history.memory} referenceLines={data.history.memory?.mode === 'current-pods' ? props.memoryReferenceLines : undefined} sharedNotice={!!resourceNotice} />}
88
+ {data?.panels.memory && <WorkloadChart label={data.panels.memory.source === "gke" ? "Non-evictable memory" : "Memory working set"} population={data.history.memory?.mode === 'workload-history' ? 'workload' : 'per Pod'} panel={data.panels.memory} window={data} scope={sameResourceScope ? undefined : data.history.memory} referenceLines={data.history.memory?.mode === 'current-pods' ? props.memoryReferenceLines : undefined} sharedNotice={!!resourceNotice} />}
88
89
  {data?.panels.throttling && <WorkloadChart
89
90
  className="metrics-chart-wide"
90
91
  label="CPU throttled periods"
@@ -411,6 +412,8 @@ function PodComparison({
411
412
  const value = values[metric].get(pod);
412
413
  return value == null ? "—" : formatMetricValue(value, unit);
413
414
  };
415
+ const memoryLabel = memory?.source === "gke" ? "Non-evictable memory" : "Memory";
416
+ const showThrottle = !!throttle || cpu?.source !== "gke";
414
417
  const comparisonPanels = [{ label: 'CPU', panel: cpu }, { label: 'Memory', panel: memory }, { label: 'Throttling', panel: throttle }];
415
418
  const pending = comparisonPanels.filter(({ panel }) => panel?.state === 'detecting');
416
419
  const notices = new Map<string, { labels: string[]; panel: WorkloadMetricPanel }>();
@@ -440,7 +443,7 @@ function PodComparison({
440
443
  <thead className="text-theme-text-tertiary">
441
444
  <tr>
442
445
  <th className="py-2 font-medium">Pod</th>
443
- {(["cpu", "memory", "throttling"] as const).map((metric) => (
446
+ {(["cpu", "memory", "throttling"] as const).filter((metric) => metric !== "throttling" || showThrottle).map((metric) => (
444
447
  <th
445
448
  key={metric}
446
449
  className="py-2 pl-3 text-right font-medium"
@@ -450,7 +453,7 @@ function PodComparison({
450
453
  {metric === "cpu"
451
454
  ? "CPU"
452
455
  : metric === "memory"
453
- ? "Memory"
456
+ ? memoryLabel
454
457
  : "Throttled"}
455
458
  {sort === metric ? " ↓" : ""}
456
459
  </button>
@@ -472,9 +475,9 @@ function PodComparison({
472
475
  <td className="pl-3 text-right tabular-nums">
473
476
  {show(pod, "memory", "bytes")}
474
477
  </td>
475
- <td className="pl-3 text-right tabular-nums">
478
+ {showThrottle && <td className="pl-3 text-right tabular-nums">
476
479
  {show(pod, "throttling", "percent")}
477
- </td>
480
+ </td>}
478
481
  </tr>
479
482
  ))}
480
483
  </tbody>
@@ -5,15 +5,19 @@ import { isClusterScopeWithheld, type ClusterScope } from "@skyhook-io/k8s-ui/ty
5
5
  * `caveat` keeps the "may include another cluster" wording: an unlabeled
6
6
  * store, older Radar (no clusterScope), or a chart that hasn't answered yet.
7
7
  */
8
- export type NameMatchedScope = "scoped" | "asserted" | "withheld" | "caveat";
8
+ export type NameMatchedScope = "scoped" | "openobserve" | "asserted" | "withheld" | "caveat";
9
9
 
10
10
  // Least certain first. A chart drawn without a cluster check outranks a
11
11
  // withheld one: it shows numbers that may mix clusters, the withheld one none.
12
- const RANK: NameMatchedScope[] = ["caveat", "withheld", "asserted", "scoped"];
12
+ const RANK: NameMatchedScope[] = ["caveat", "withheld", "asserted", "openobserve", "scoped"];
13
+
14
+ // Radar serving metrics from OpenObserve reports the single-cluster state
15
+ // (for older UIs) with this note: the source itself scopes every query.
16
+ export const OPENOBSERVE_NOTE = "Scoped to this cluster through OpenObserve";
13
17
 
14
18
  function classify(scope: ClusterScope | null | undefined): NameMatchedScope {
15
19
  if (scope?.state === "scoped_configured" || scope?.state === "scoped_verified") return "scoped";
16
- if (scope?.state === "single_cluster_asserted") return "asserted";
20
+ if (scope?.state === "single_cluster_asserted") return scope.note?.startsWith(OPENOBSERVE_NOTE) ? "openobserve" : "asserted";
17
21
  return isClusterScopeWithheld(scope) ? "withheld" : "caveat";
18
22
  }
19
23
 
@@ -25,6 +29,7 @@ export function leastCertainScope(scopes: (ClusterScope | null | undefined)[]):
25
29
 
26
30
  export const NAME_MATCHED_SUMMARY: Record<NameMatchedScope, string> = {
27
31
  scoped: "matched by cluster label",
32
+ openobserve: "scoped through OpenObserve",
28
33
  asserted: "operator declared single-cluster",
29
34
  withheld: "identity unverified",
30
35
  caveat: "identity unverified",
@@ -33,6 +38,7 @@ export const NAME_MATCHED_SUMMARY: Record<NameMatchedScope, string> = {
33
38
  /** The sentence that replaces "may include another cluster", or undefined to keep it. */
34
39
  export const NAME_MATCHED_CLUSTER_NOTE: Record<NameMatchedScope, string | undefined> = {
35
40
  scoped: "They're kept to this cluster by its cluster labels.",
41
+ openobserve: "They're kept to this cluster through OpenObserve.",
36
42
  asserted: "An operator declared this metrics store single-cluster, so they don't include another cluster.",
37
43
  withheld: "Charts that couldn't be kept to this cluster say why in place of their data.",
38
44
  caveat: undefined,
@@ -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
+ }