@skyhook-io/radar-app 1.21.8 → 1.22.1

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 (83) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +16 -1
  3. package/src/api/client.ts +18 -0
  4. package/src/api/cnpg-history.ts +3 -3
  5. package/src/api/cnpg-storage.ts +3 -3
  6. package/src/api/diagnose.test.ts +34 -0
  7. package/src/api/diagnose.ts +17 -4
  8. package/src/api/radarFeatures.test.ts +13 -1
  9. package/src/api/radarFeatures.ts +6 -0
  10. package/src/api/resourceActions.test.ts +829 -0
  11. package/src/api/resourceActions.ts +584 -0
  12. package/src/api/resourceActions.ui.test.tsx +1882 -0
  13. package/src/api/reviewedActionMutation.ts +56 -28
  14. package/src/api/substrateHealth.ts +2 -3
  15. package/src/api/traefik.ts +33 -0
  16. package/src/api/traffic.ts +14 -5
  17. package/src/api/workloadMetrics.test.ts +11 -2
  18. package/src/api/workloadMetrics.ts +2 -2
  19. package/src/components/CloudFunnelButton.test.tsx +39 -1
  20. package/src/components/CloudFunnelButton.tsx +10 -3
  21. package/src/components/cnpg/CNPGOverview.test.tsx +75 -3
  22. package/src/components/cnpg/CNPGOverview.tsx +62 -4
  23. package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
  24. package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
  25. package/src/components/diagnose/DiagnoseContext.tsx +28 -3
  26. package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
  27. package/src/components/diagnose/Home.tsx +3 -0
  28. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
  29. package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
  30. package/src/components/diagnose/InvestigationView.tsx +10 -2
  31. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
  32. package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
  33. package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
  34. package/src/components/diagnose/QuestionComposer.tsx +13 -8
  35. package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
  36. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
  37. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
  38. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
  39. package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
  40. package/src/components/diagnose/launch.ts +1 -1
  41. package/src/components/dock/PodDebugSession.test.tsx +66 -0
  42. package/src/components/dock/PodDebugSession.tsx +3 -1
  43. package/src/components/dock/TerminalTab.test.tsx +43 -3
  44. package/src/components/dock/TerminalTab.tsx +10 -1
  45. package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
  46. package/src/components/helm/InstallWizard.tsx +1 -1
  47. package/src/components/home/NetworkPolicyCoverageCard.test.tsx +37 -0
  48. package/src/components/home/NetworkPolicyCoverageCard.tsx +26 -2
  49. package/src/components/home/mcpToolCatalog.ts +1 -1
  50. package/src/components/resources/PodEvictAction.test.tsx +951 -0
  51. package/src/components/resources/PodEvictAction.tsx +167 -0
  52. package/src/components/resources/ResourcesView.tsx +3 -0
  53. package/src/components/resources/renderers/TraefikIngressRouteRenderer.test.tsx +23 -0
  54. package/src/components/resources/renderers/TraefikIngressRouteRenderer.tsx +23 -0
  55. package/src/components/resources/renderers/TraefikMiddlewareRenderer.test.tsx +23 -0
  56. package/src/components/resources/renderers/TraefikMiddlewareRenderer.tsx +29 -0
  57. package/src/components/resources/renderers/WorkloadRenderer.tsx +3 -0
  58. package/src/components/settings/LocalConnectionSettings.tsx +4 -4
  59. package/src/components/settings/SettingsDialog.tsx +23 -18
  60. package/src/components/settings/integrationQueries.test.ts +98 -0
  61. package/src/components/settings/integrationQueries.ts +36 -0
  62. package/src/components/traffic/TrafficConnectionsTable.test.tsx +23 -0
  63. package/src/components/traffic/TrafficConnectionsTable.tsx +5 -4
  64. package/src/components/traffic/TrafficFilterSidebar.test.tsx +14 -0
  65. package/src/components/traffic/TrafficFilterSidebar.tsx +17 -0
  66. package/src/components/traffic/TrafficFlowList.tsx +5 -5
  67. package/src/components/traffic/TrafficGraph.test.tsx +11 -0
  68. package/src/components/traffic/TrafficGraph.tsx +31 -19
  69. package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
  70. package/src/components/traffic/TrafficView.tsx +108 -41
  71. package/src/components/traffic/traffic-export.test.ts +8 -0
  72. package/src/components/traffic/traffic-export.ts +7 -4
  73. package/src/components/traffic/trafficFilters.test.ts +51 -1
  74. package/src/components/traffic/trafficFilters.ts +39 -11
  75. package/src/components/ui/Markdown.test.tsx +37 -0
  76. package/src/components/ui/Markdown.tsx +15 -2
  77. package/src/components/ui/command-items-crd.test.tsx +23 -8
  78. package/src/components/useContextSwitchFlow.test.tsx +27 -2
  79. package/src/components/useContextSwitchFlow.tsx +20 -22
  80. package/src/components/whats-new/releaseNotes.ts +75 -1
  81. package/src/components/workload/WorkloadView.tsx +16 -3
  82. package/src/integrations/resourceHosts.test.tsx +1 -1
  83. package/src/integrations/resourceHosts.tsx +3 -0
@@ -0,0 +1,951 @@
1
+ // @vitest-environment jsdom
2
+ import { act, type ReactNode } from 'react'
3
+ import { MemoryRouter } from 'react-router-dom'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { createRoot, type Root } from 'react-dom/client'
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
7
+ import {
8
+ DockProvider,
9
+ RESOURCE_ACTION_IDS,
10
+ ResourceActionsBar,
11
+ ToastProvider,
12
+ readResourceActionError,
13
+ resourceActionLockKey,
14
+ type ResourceActionPreviewResponse,
15
+ } from '@skyhook-io/k8s-ui'
16
+ import { getApiBase, setApiBase } from '../../api/config'
17
+ import { observeConnectionStatus, resetConnectionBindingForTest } from '../../api/connectionBinding'
18
+ import { ResourceActionError, useResourceActionAdapter } from '../../api/resourceActions'
19
+ import { getReviewedActionOutcomeStore } from '../../api/reviewedActionMutation'
20
+ import { ConnectionProvider } from '../../context/ConnectionContext'
21
+ import { showApiSuccess } from '../ui/Toast'
22
+ import { WorkloadView } from '../workload/WorkloadView'
23
+ import { isPodEvictEligible, PodEvictAction, type PodEvictTarget } from './PodEvictAction'
24
+
25
+ vi.mock('../ui/Toast', async (importOriginal) => {
26
+ const actual = await importOriginal<typeof import('../ui/Toast')>()
27
+ return { ...actual, showApiSuccess: vi.fn(), showApiError: vi.fn(), showApiNotice: vi.fn() }
28
+ })
29
+
30
+ ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
31
+
32
+ const POD_EVICT_ID = RESOURCE_ACTION_IDS.podEvict
33
+ const DIGEST_1 = `v1:sha256:${'a'.repeat(64)}`
34
+ const DIGEST_2 = `v1:sha256:${'b'.repeat(64)}`
35
+
36
+ interface RecordedCall {
37
+ url: string
38
+ method: string
39
+ body?: Record<string, unknown>
40
+ connectionId: string | null
41
+ }
42
+
43
+ const basePod: PodEvictTarget = {
44
+ apiVersion: 'v1',
45
+ kind: 'Pod',
46
+ metadata: {
47
+ namespace: 'shop',
48
+ name: 'checkout-0',
49
+ uid: 'pod-uid-3',
50
+ ownerReferences: [{ kind: 'ReplicaSet', name: 'checkout-6f8b9c7d5', controller: true }],
51
+ },
52
+ spec: { nodeName: 'node-a', volumes: [] },
53
+ status: { phase: 'Running' },
54
+ }
55
+
56
+ function makePreview(overrides?: Partial<ResourceActionPreviewResponse>): ResourceActionPreviewResponse {
57
+ return {
58
+ actionId: POD_EVICT_ID,
59
+ actionVersion: 1,
60
+ target: { namespace: 'shop', name: 'checkout-0', uid: 'pod-uid-3', apiVersion: 'v1' },
61
+ previewedAs: { user: 'alice@example.com' },
62
+ summary: 'Evict Pod shop/checkout-0 managed by ReplicaSet checkout-6f8b9c7d5.',
63
+ changes: [{ object: { apiVersion: 'v1', kind: 'Pod', namespace: 'shop', name: 'checkout-0', uid: 'pod-uid-3' }, changeType: 'evict' }],
64
+ warnings: [{ code: 'pod_disruption_budget', severity: 'warn', message: 'PodDisruptionBudget checkout-pdb applies to this Pod.' }],
65
+ fromPreview: { digest: DIGEST_1, actionVersion: 1, apiVersion: 'v1', preconditions: [{ strategy: 'uid_only', uid: 'pod-uid-3' }] },
66
+ ...overrides,
67
+ }
68
+ }
69
+
70
+ const EXECUTED_AS = { user: 'alice@example.com', groups: ['devs'] }
71
+
72
+ function makeAcceptedExecuteResponse(executionId: unknown) {
73
+ return Response.json(
74
+ { executionId, outcome: 'accepted', executedAs: EXECUTED_AS },
75
+ { status: 202 },
76
+ )
77
+ }
78
+
79
+ function PodEvictHarness({ pod, inActionsBar = false, enabled = true }: { pod: PodEvictTarget; inActionsBar?: boolean; enabled?: boolean }) {
80
+ const adapter = useResourceActionAdapter()
81
+ const evict = <PodEvictAction pod={pod} adapter={adapter} enabled={enabled} />
82
+ if (!inActionsBar) return evict
83
+ return (
84
+ <ResourceActionsBar
85
+ resource={{ kind: 'pods', namespace: pod.metadata?.namespace ?? 'shop', name: pod.metadata?.name ?? 'checkout-0' }}
86
+ data={{ ...pod, spec: { ...pod.spec, containers: [{ name: 'app' }] } }}
87
+ canExec
88
+ canViewLogs
89
+ onOpenTerminal={vi.fn()}
90
+ onOpenLogs={vi.fn()}
91
+ resourceActionAdapter={adapter}
92
+ podEvictAction={evict}
93
+ />
94
+ )
95
+ }
96
+
97
+ describe('PodEvictAction integration on shared D4 dialog and adapter', () => {
98
+ let host: HTMLDivElement
99
+ let root: Root
100
+ let client: QueryClient
101
+ let calls: RecordedCall[]
102
+ let originalApiBase: string
103
+
104
+ beforeEach(() => {
105
+ originalApiBase = getApiBase()
106
+ setApiBase('/api')
107
+ calls = []
108
+ if (typeof globalThis.ResizeObserver === 'undefined') {
109
+ vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} })
110
+ }
111
+ resetConnectionBindingForTest()
112
+ observeConnectionStatus({ connectionId: 'conn-1' })
113
+ host = document.createElement('div')
114
+ document.body.appendChild(host)
115
+ root = createRoot(host)
116
+ client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
117
+ client.setQueryData(['connection-status'], { context: 'prod-cluster' })
118
+ client.setQueryData(['version-check', getApiBase()], {})
119
+ })
120
+
121
+ afterEach(async () => {
122
+ await act(async () => root.unmount())
123
+ host.remove()
124
+ document.body.replaceChildren()
125
+ client.clear()
126
+ setApiBase(originalApiBase)
127
+ resetConnectionBindingForTest()
128
+ vi.unstubAllGlobals()
129
+ vi.clearAllMocks()
130
+ vi.restoreAllMocks()
131
+ ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
132
+ })
133
+
134
+ function seedCapabilities(options?: { resourceActions?: boolean; actions?: string[] }) {
135
+ const enabled = options?.resourceActions ?? true
136
+ client.setQueryData(['capabilities'], {
137
+ features: { resourceActions: enabled },
138
+ ...(enabled ? { reviewedActions: { contractVersion: 1, actions: options?.actions ?? [POD_EVICT_ID] } } : {}),
139
+ })
140
+ }
141
+
142
+ function stubFetch(handler: (call: RecordedCall, signal?: AbortSignal | null) => Response | Promise<Response>) {
143
+ vi.stubGlobal(
144
+ 'fetch',
145
+ vi.fn<typeof fetch>(async (input, init) => {
146
+ const call: RecordedCall = {
147
+ url: String(input),
148
+ method: init?.method ?? 'GET',
149
+ body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
150
+ connectionId: new Headers(init?.headers).get('X-Radar-Connection'),
151
+ }
152
+ calls.push(call)
153
+ return handler(call, init?.signal)
154
+ }),
155
+ )
156
+ }
157
+
158
+ const renderNode = (node: ReactNode) =>
159
+ act(async () => {
160
+ root.render(<QueryClientProvider client={client}>{node}</QueryClientProvider>)
161
+ })
162
+
163
+ const buttonsByText = (label: string) =>
164
+ [...document.querySelectorAll('button')].filter((b): b is HTMLButtonElement => b.textContent?.trim() === label)
165
+
166
+ it('checks exact /access with target-only request and {access} response, enforces eligibility, and fails closed without legacy fallback', async () => {
167
+ expect(isPodEvictEligible(basePod)).toBe(true)
168
+ expect(isPodEvictEligible(undefined)).toBe(false)
169
+ expect(isPodEvictEligible({ ...basePod, metadata: { ...basePod.metadata, uid: '' } })).toBe(false)
170
+ expect(isPodEvictEligible({ ...basePod, metadata: { ...basePod.metadata, ownerReferences: [] } })).toBe(false)
171
+ expect(isPodEvictEligible({ ...basePod, metadata: { ...basePod.metadata, deletionTimestamp: '2026-11-29T00:00:00Z' } })).toBe(false)
172
+ expect(isPodEvictEligible({ ...basePod, status: { phase: 'Succeeded' } })).toBe(false)
173
+ expect(isPodEvictEligible({ ...basePod, metadata: { ...basePod.metadata, annotations: { 'kubernetes.io/config.mirror': 'abc' } } })).toBe(false)
174
+ expect(isPodEvictEligible({ ...basePod, spec: { volumes: [{ emptyDir: {} }] } })).toBe(false)
175
+
176
+ // Unknown capabilities (loading) never calls /access or renders button.
177
+ stubFetch(({ url }) => (url.includes('/capabilities') ? new Promise<Response>(() => {}) : Response.json({ access: 'allowed' })))
178
+ await renderNode(<PodEvictHarness pod={basePod} />)
179
+ expect(buttonsByText('Evict Pod')).toHaveLength(0)
180
+ expect(calls.filter((c) => c.url.includes('/resource-actions/'))).toHaveLength(0)
181
+
182
+ calls.length = 0
183
+ stubFetch(() => Response.json({ access: 'allowed' }))
184
+ seedCapabilities({ resourceActions: false })
185
+ await renderNode(<PodEvictHarness pod={basePod} />)
186
+ expect(buttonsByText('Evict Pod')).toHaveLength(0)
187
+ expect(calls.filter((c) => c.url.includes('/resource-actions/'))).toHaveLength(0)
188
+
189
+ seedCapabilities({ resourceActions: true, actions: ['apps/Deployment/restart'] })
190
+ await renderNode(<PodEvictHarness pod={basePod} />)
191
+ expect(buttonsByText('Evict Pod')).toHaveLength(0)
192
+ expect(calls.filter((c) => c.url.includes('/resource-actions/'))).toHaveLength(0)
193
+
194
+ // Ineligible pod skips /access even when supported.
195
+ seedCapabilities()
196
+ await renderNode(<PodEvictHarness pod={{ ...basePod, spec: { volumes: [{ emptyDir: {} }] } }} />)
197
+ expect(buttonsByText('Evict Pod')).toHaveLength(0)
198
+ expect(calls.filter((c) => c.url.includes('/resource-actions/'))).toHaveLength(0)
199
+
200
+ // Pending /access hides button until exact { access: 'allowed' } resolves.
201
+ calls.length = 0
202
+ let resolveAccess!: (res: Response) => void
203
+ stubFetch(() => new Promise<Response>((resolve) => { resolveAccess = resolve }))
204
+ await renderNode(<PodEvictHarness pod={basePod} />)
205
+ expect(buttonsByText('Evict Pod')).toHaveLength(0)
206
+ expect(calls).toEqual([{
207
+ url: '/api/resource-actions/core/Pod/evict/access',
208
+ method: 'POST',
209
+ body: { target: { namespace: 'shop', name: 'checkout-0' } },
210
+ connectionId: 'conn-1',
211
+ }])
212
+
213
+ await act(async () => { resolveAccess(Response.json({ access: 'allowed' })) })
214
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod')).toHaveLength(1))
215
+ // No duplicate namespace can-I or second /access query.
216
+ expect(calls).toHaveLength(1)
217
+ expect(calls.some((c) => c.url.includes('namespace='))).toBe(false)
218
+
219
+ // Denied, unknown, and 403/404 inaccessible pod all fail closed.
220
+ for (const [uid, res] of [
221
+ ['pod-denied', Response.json({ access: 'denied' })],
222
+ ['pod-unknown', Response.json({ access: 'unknown' })],
223
+ ['pod-inaccessible', Response.json({ code: 'forbidden', message: 'denied', retry: 'none', dispatch: 'not_dispatched' }, { status: 403 })],
224
+ ['pod-gone', Response.json({ code: 'target_not_found', message: 'not found', retry: 'none', dispatch: 'not_dispatched' }, { status: 404 })],
225
+ ] as const) {
226
+ stubFetch(() => res)
227
+ await renderNode(<PodEvictHarness pod={{ ...basePod, metadata: { ...basePod.metadata, uid } }} />)
228
+ await vi.waitFor(() => expect(calls.some((c) => c.url.endsWith('/access'))).toBe(true))
229
+ expect(buttonsByText('Evict Pod')).toHaveLength(0)
230
+ }
231
+ })
232
+
233
+ it('wires into ResourceActionsBar, previews once, never executes on reopen, accepts only 202 accepted, and shows Eviction accepted', async () => {
234
+ seedCapabilities()
235
+ const invalidateSpy = vi.spyOn(client, 'invalidateQueries')
236
+ let resolveExecute!: (res: Response) => void
237
+
238
+ stubFetch(({ url }) => {
239
+ if (url.endsWith('/core/Pod/evict/access')) return Response.json({ access: 'allowed' })
240
+ if (url.endsWith('/core/Pod/evict/preview')) return Response.json(makePreview())
241
+ if (url.endsWith('/core/Pod/evict/execute')) {
242
+ return new Promise<Response>((resolve) => { resolveExecute = resolve })
243
+ }
244
+ return Response.json({})
245
+ })
246
+
247
+ await renderNode(<PodEvictHarness pod={basePod} inActionsBar />)
248
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod')).toHaveLength(1))
249
+ // Existing Pod controls layout preserved alongside Evict Pod.
250
+ expect(buttonsByText('Terminal')).toHaveLength(1)
251
+ expect(buttonsByText('Logs')).toHaveLength(1)
252
+
253
+ // Open -> previews once and waits for explicit confirm.
254
+ await act(async () => buttonsByText('Evict Pod')[0].click())
255
+ await vi.waitFor(() => {
256
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
257
+ expect(document.body.textContent).toContain('PodDisruptionBudget checkout-pdb applies to this Pod.')
258
+ expect(document.body.textContent).toContain('Previewed as alice@example.com')
259
+ expect(document.body.textContent).toContain('API acceptance only confirms Kubernetes accepted the eviction request')
260
+ expect(document.body.textContent).toContain('prod-cluster')
261
+ })
262
+ expect(document.body.innerHTML).not.toContain(DIGEST_1)
263
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(1)
264
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(0)
265
+
266
+ // Cancel + reopen must NOT execute automatically.
267
+ await act(async () => buttonsByText('Cancel')[0].click())
268
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0)
269
+ await act(async () => buttonsByText('Evict Pod')[0].click())
270
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false))
271
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(2)
272
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(0)
273
+
274
+ // Synchronous double-click on Confirm executes exactly once with pinned UID + connection.
275
+ const confirmBtn = buttonsByText('Evict Pod').at(-1)!
276
+ act(() => {
277
+ confirmBtn.click()
278
+ confirmBtn.click()
279
+ })
280
+ await vi.waitFor(() => expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1))
281
+ const execCall = calls.find((c) => c.url.endsWith('/execute'))!
282
+ expect(execCall.connectionId).toBe('conn-1')
283
+ expect(execCall.body).toMatchObject({
284
+ target: { namespace: 'shop', name: 'checkout-0' },
285
+ parameters: {},
286
+ fromPreview: makePreview().fromPreview,
287
+ })
288
+
289
+ // Resolve with expected 202 accepted receipt echoing exact outgoing executionId and executedAs.
290
+ await act(async () => {
291
+ resolveExecute(makeAcceptedExecuteResponse(execCall.body?.executionId))
292
+ })
293
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
294
+ expect(showApiSuccess).toHaveBeenCalledWith(
295
+ 'Eviction accepted',
296
+ expect.stringContaining('Termination and controller follow-up happen separately'),
297
+ )
298
+ expect(String(vi.mocked(showApiSuccess).mock.calls[0]?.[1] ?? '')).not.toMatch(/terminated|replaced|completed/i)
299
+ expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['resources', 'pods'] })
300
+ expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['resource', 'pods', 'shop', 'checkout-0'] })
301
+ })
302
+
303
+ it('locks ambiguous/non-202/non-accepted/mismatched-ID/malformed-2xx/post-dispatch outcomes against the same Pod across reopen and remount without retry', async () => {
304
+ const ambiguousCases: Array<{
305
+ label: string
306
+ uid: string
307
+ respond: (body?: Record<string, unknown>) => Response | Promise<Response>
308
+ expectRetainedExecutionId?: boolean
309
+ }> = [
310
+ { label: '200 accepted', uid: 'pod-200', respond: (body) => Response.json({ executionId: body?.executionId, outcome: 'accepted' }, { status: 200 }) },
311
+ { label: '200 applied', uid: 'pod-200-applied', respond: (body) => Response.json({ executionId: body?.executionId, outcome: 'applied' }, { status: 200 }), expectRetainedExecutionId: true },
312
+ { label: '200 noop', uid: 'pod-200-noop', respond: (body) => Response.json({ executionId: body?.executionId, outcome: 'noop' }, { status: 200 }), expectRetainedExecutionId: true },
313
+ { label: '202 applied', uid: 'pod-applied', respond: (body) => Response.json({ executionId: body?.executionId, outcome: 'applied' }, { status: 202 }) },
314
+ { label: '202 wrong executionId', uid: 'pod-wrong-id', respond: () => Response.json({ executionId: 'wrong-exec-id', outcome: 'accepted' }, { status: 202 }) },
315
+ { label: '202 malformed body', uid: 'pod-badjson', respond: () => new Response('<html>gateway</html>', { status: 202, headers: { 'Content-Type': 'text/html' } }) },
316
+ { label: '202 empty object', uid: 'pod-emptyobj', respond: () => Response.json({}, { status: 202 }) },
317
+ {
318
+ label: '503 post-dispatch unknown',
319
+ uid: 'pod-dispatch-unknown',
320
+ respond: (body) =>
321
+ Response.json(
322
+ {
323
+ code: 'dispatch_unknown',
324
+ message: 'eviction request for Pod shop/checkout-0 did not return an accepted confirmation; inspect the Pod and PDB before retrying',
325
+ retry: 'none',
326
+ dispatch: 'unknown',
327
+ executionId: body?.executionId,
328
+ },
329
+ { status: 503 },
330
+ ),
331
+ expectRetainedExecutionId: true,
332
+ },
333
+ { label: 'network drop after dispatch', uid: 'pod-net', respond: () => Promise.reject(new TypeError('Failed to fetch')) },
334
+ ]
335
+
336
+ seedCapabilities()
337
+
338
+ for (const tc of ambiguousCases) {
339
+ calls.length = 0
340
+ vi.mocked(showApiSuccess).mockClear()
341
+ const pod: PodEvictTarget = { ...basePod, metadata: { ...basePod.metadata, uid: tc.uid } }
342
+
343
+ stubFetch(({ url, body }) => {
344
+ if (url.endsWith('/access')) return Response.json({ access: 'allowed' })
345
+ if (url.endsWith('/preview')) return Response.json(makePreview({ target: { namespace: 'shop', name: 'checkout-0', uid: tc.uid, apiVersion: 'v1' } }))
346
+ if (url.endsWith('/execute')) return tc.respond(body)
347
+ return Response.json({})
348
+ })
349
+
350
+ await renderNode(<PodEvictHarness pod={pod} />)
351
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod')).toHaveLength(1))
352
+ await act(async () => buttonsByText('Evict Pod')[0].click())
353
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false))
354
+
355
+ await act(async () => buttonsByText('Evict Pod').at(-1)!.click())
356
+ await vi.waitFor(() => {
357
+ expect(document.body.textContent, tc.label).toContain('Radar could not tell whether this took effect')
358
+ expect(document.body.textContent, tc.label).toContain('Inspect the current state in Kubernetes first, then reload this page and review the action again.')
359
+ expect(buttonsByText('Evict Pod').at(-1)!.disabled, tc.label).toBe(true)
360
+ })
361
+ expect(showApiSuccess, tc.label).not.toHaveBeenCalled()
362
+ const executeCalls = calls.filter((c) => c.url.endsWith('/execute'))
363
+ expect(executeCalls, tc.label).toHaveLength(1)
364
+ if (tc.expectRetainedExecutionId) {
365
+ const sentExecutionId = executeCalls[0]?.body?.executionId
366
+ expect(typeof sentExecutionId, tc.label).toBe('string')
367
+ const lockKey = resourceActionLockKey({
368
+ actionId: POD_EVICT_ID,
369
+ namespace: 'shop',
370
+ name: 'checkout-0',
371
+ uid: tc.uid,
372
+ connectionId: 'conn-1',
373
+ })
374
+ const retainedError = getReviewedActionOutcomeStore(client).get(lockKey).error
375
+ expect(retainedError, tc.label).toBeInstanceOf(ResourceActionError)
376
+ expect((retainedError as ResourceActionError).executionId, tc.label).toBe(sentExecutionId)
377
+ expect(readResourceActionError(retainedError)?.executionId, tc.label).toBe(sentExecutionId)
378
+ }
379
+
380
+ // Close and reopen -> still locked, zero new preview or execute.
381
+ await act(async () => buttonsByText('Cancel')[0].click())
382
+ await act(async () => buttonsByText('Evict Pod')[0].click())
383
+ expect(document.body.textContent, tc.label).toContain('Radar could not tell whether this took effect')
384
+ expect(buttonsByText('Evict Pod').at(-1)!.disabled, tc.label).toBe(true)
385
+ expect(calls.filter((c) => c.url.endsWith('/preview')), tc.label).toHaveLength(1)
386
+ expect(calls.filter((c) => c.url.endsWith('/execute')), tc.label).toHaveLength(1)
387
+
388
+ // Unmount and remount on same QueryClient -> still locked against same Pod UID.
389
+ await act(async () => root.unmount())
390
+ root = createRoot(host)
391
+ await renderNode(<PodEvictHarness pod={pod} />)
392
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod')).toHaveLength(1))
393
+ await act(async () => buttonsByText('Evict Pod')[0].click())
394
+ expect(document.body.textContent, tc.label).toContain('Radar could not tell whether this took effect')
395
+ expect(buttonsByText('Evict Pod').at(-1)!.disabled, tc.label).toBe(true)
396
+ expect(calls.filter((c) => c.url.endsWith('/preview')), tc.label).toHaveLength(1)
397
+ expect(calls.filter((c) => c.url.endsWith('/execute')), tc.label).toHaveLength(1)
398
+ }
399
+ })
400
+
401
+ it('keeps PDB-marked 429 refusal unlocked and sends no new execute until a second explicit user click', async () => {
402
+ seedCapabilities()
403
+ let execAttempt = 0
404
+
405
+ stubFetch(({ url, body }) => {
406
+ if (url.endsWith('/access')) return Response.json({ access: 'allowed' })
407
+ if (url.endsWith('/preview')) return Response.json(makePreview())
408
+ if (url.endsWith('/execute')) {
409
+ execAttempt += 1
410
+ if (execAttempt === 1) {
411
+ return Response.json(
412
+ {
413
+ code: 'temporarily_unavailable',
414
+ message: 'Kubernetes reported a PodDisruptionBudget refusal for Pod shop/checkout-0; try again later.',
415
+ retry: 'later',
416
+ dispatch: 'not_dispatched',
417
+ executionId: body?.executionId,
418
+ },
419
+ { status: 429 },
420
+ )
421
+ }
422
+ return makeAcceptedExecuteResponse(body?.executionId)
423
+ }
424
+ return Response.json({})
425
+ })
426
+
427
+ await renderNode(<PodEvictHarness pod={basePod} />)
428
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod')).toHaveLength(1))
429
+ await act(async () => buttonsByText('Evict Pod')[0].click())
430
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false))
431
+
432
+ await act(async () => buttonsByText('Evict Pod').at(-1)!.click())
433
+ await vi.waitFor(() => {
434
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
435
+ expect(document.body.textContent).toContain('Kubernetes reported a PodDisruptionBudget refusal for Pod shop/checkout-0; try again later.')
436
+ expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false)
437
+ })
438
+ expect(document.body.textContent).not.toContain('Radar could not tell whether this took effect')
439
+ expect(showApiSuccess).not.toHaveBeenCalled()
440
+
441
+ const lockKey = resourceActionLockKey({
442
+ actionId: POD_EVICT_ID,
443
+ namespace: 'shop',
444
+ name: 'checkout-0',
445
+ uid: 'pod-uid-3',
446
+ connectionId: 'conn-1',
447
+ })
448
+ expect(getReviewedActionOutcomeStore(client).get(lockKey).error).toBeNull()
449
+
450
+ // Flush microtasks to verify no automatic retry is issued before a second explicit user click.
451
+ await act(async () => {})
452
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1)
453
+
454
+ await act(async () => buttonsByText('Evict Pod').at(-1)!.click())
455
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
456
+
457
+ const execCalls = calls.filter((c) => c.url.endsWith('/execute'))
458
+ expect(execCalls).toHaveLength(2)
459
+ expect(execCalls[1].connectionId).toBe('conn-1')
460
+ expect(execCalls[1].body?.executionId).not.toBe(execCalls[0].body?.executionId)
461
+ expect(execCalls[1].body?.fromPreview).toEqual(makePreview().fromPreview)
462
+ expect(showApiSuccess).toHaveBeenCalledTimes(1)
463
+ expect(showApiSuccess).toHaveBeenCalledWith(
464
+ 'Eviction accepted',
465
+ expect.stringContaining('Termination and controller follow-up happen separately'),
466
+ )
467
+ })
468
+
469
+ it('re-queries /access and closes open dialog without executing when connection rebounds or Pod UID/target changes', async () => {
470
+ seedCapabilities()
471
+ let accessOnConn2: 'pending' | 'denied' | 'allowed' = 'denied'
472
+ let resolveConn2Access: ((res: Response) => void) | undefined
473
+
474
+ stubFetch(({ url, body, connectionId }) => {
475
+ if (url.endsWith('/access')) {
476
+ if (connectionId === 'conn-2') {
477
+ if (accessOnConn2 === 'pending') {
478
+ return new Promise<Response>((resolve) => { resolveConn2Access = resolve })
479
+ }
480
+ return Response.json({ access: accessOnConn2 })
481
+ }
482
+ return Response.json({ access: 'allowed' })
483
+ }
484
+ if (url.endsWith('/preview')) return Response.json(makePreview())
485
+ if (url.endsWith('/execute')) return makeAcceptedExecuteResponse(body?.executionId)
486
+ return Response.json({})
487
+ })
488
+
489
+ await renderNode(<PodEvictHarness pod={basePod} />)
490
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod')).toHaveLength(1))
491
+ await act(async () => buttonsByText('Evict Pod')[0].click())
492
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false))
493
+
494
+ // Connection rebounds from conn-1 -> conn-2 while dialog is open: dialog closes, no execute, /access re-runs on conn-2.
495
+ accessOnConn2 = 'pending'
496
+ await act(async () => { observeConnectionStatus({ connectionId: 'conn-2' }) })
497
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0)
498
+ expect(buttonsByText('Evict Pod')).toHaveLength(0)
499
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(0)
500
+ await vi.waitFor(() => expect(calls.some((c) => c.url.endsWith('/access') && c.connectionId === 'conn-2')).toBe(true))
501
+
502
+ await act(async () => { resolveConn2Access?.(Response.json({ access: 'denied' })) })
503
+ expect(buttonsByText('Evict Pod')).toHaveLength(0)
504
+
505
+ // Switch to conn-3 where allowed, open dialog, then replace Pod UID -> dialog closes without executing and new UID checks /access.
506
+ accessOnConn2 = 'allowed'
507
+ await act(async () => { observeConnectionStatus({ connectionId: 'conn-3' }) })
508
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod')).toHaveLength(1))
509
+ await act(async () => buttonsByText('Evict Pod')[0].click())
510
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1))
511
+
512
+ const replacedPod: PodEvictTarget = { ...basePod, metadata: { ...basePod.metadata, uid: 'pod-uid-4' } }
513
+ await renderNode(<PodEvictHarness pod={replacedPod} />)
514
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0)
515
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(0)
516
+ await vi.waitFor(() => expect(calls.filter((c) => c.url.endsWith('/access') && c.connectionId === 'conn-3')).toHaveLength(2))
517
+ })
518
+
519
+ it('refuses replaced UID in live preview or reapprove, enforces 422 action_not_applicable, confirms unknown warning severities explicitly, and keeps pre-dispatch errors unlocked', async () => {
520
+ seedCapabilities()
521
+
522
+ // 1. Live preview returns replaced UID -> blocks confirm, zero execute.
523
+ stubFetch(({ url }) => {
524
+ if (url.endsWith('/access')) return Response.json({ access: 'allowed' })
525
+ if (url.endsWith('/preview')) return Response.json(makePreview({ target: { namespace: 'shop', name: 'checkout-0', uid: 'pod-uid-999', apiVersion: 'v1' } }))
526
+ return Response.json({})
527
+ })
528
+ await renderNode(<PodEvictHarness pod={basePod} />)
529
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod')).toHaveLength(1))
530
+ await act(async () => buttonsByText('Evict Pod')[0].click())
531
+ await vi.waitFor(() => {
532
+ expect(document.body.textContent).toContain('Target changed')
533
+ expect(document.body.textContent).toContain('Close and reselect')
534
+ })
535
+ expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(true)
536
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(0)
537
+ await act(async () => buttonsByText('Cancel')[0].click())
538
+
539
+ // 2a. Server-ineligible 422 action_not_applicable on /preview disables confirm and never executes.
540
+ calls.length = 0
541
+ stubFetch(({ url }) => {
542
+ if (url.endsWith('/access')) return Response.json({ access: 'allowed' })
543
+ if (url.endsWith('/preview')) {
544
+ return Response.json(
545
+ {
546
+ code: 'action_not_applicable',
547
+ message: 'Pod uses emptyDir storage and cannot be evicted.',
548
+ retry: 'none',
549
+ dispatch: 'not_dispatched',
550
+ },
551
+ { status: 422 },
552
+ )
553
+ }
554
+ return Response.json({})
555
+ })
556
+ await act(async () => buttonsByText('Evict Pod')[0].click())
557
+ await vi.waitFor(() => {
558
+ expect(document.body.textContent).toContain('Pod uses emptyDir storage and cannot be evicted.')
559
+ expect(document.body.textContent).toContain('Preview failed')
560
+ })
561
+ expect(document.body.textContent).not.toContain('Radar could not tell whether this took effect')
562
+ expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(true)
563
+ expect(calls.map((c) => c.url)).toEqual(['/api/resource-actions/core/Pod/evict/preview'])
564
+ await act(async () => buttonsByText('Cancel')[0].click())
565
+
566
+ // 2b. Unknown warning severity on /preview is displayed without auto-executing, and remains explicitly confirmable.
567
+ calls.length = 0
568
+ vi.mocked(showApiSuccess).mockClear()
569
+ stubFetch(({ url, body }) => {
570
+ if (url.endsWith('/access')) return Response.json({ access: 'allowed' })
571
+ if (url.endsWith('/preview')) {
572
+ return Response.json(
573
+ makePreview({
574
+ warnings: [{ code: 'future_pod_policy', severity: 'critical', message: 'Future policy requires operator review.' }],
575
+ }),
576
+ )
577
+ }
578
+ if (url.endsWith('/execute')) return makeAcceptedExecuteResponse(body?.executionId)
579
+ return Response.json({})
580
+ })
581
+ await act(async () => buttonsByText('Evict Pod')[0].click())
582
+ await vi.waitFor(() => {
583
+ expect(document.body.textContent).toContain('Future policy requires operator review.')
584
+ expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false)
585
+ })
586
+ expect(calls.map((c) => c.url)).toEqual(['/api/resource-actions/core/Pod/evict/preview'])
587
+ await act(async () => buttonsByText('Evict Pod').at(-1)!.click())
588
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
589
+ expect(calls.map((c) => c.url)).toEqual([
590
+ '/api/resource-actions/core/Pod/evict/preview',
591
+ '/api/resource-actions/core/Pod/evict/execute',
592
+ ])
593
+ expect(showApiSuccess).toHaveBeenCalledWith('Eviction accepted', expect.any(String))
594
+
595
+ // 3. Transient preview error does NOT falsely claim uncertain dispatch or lock reopen.
596
+ let previewCalls = 0
597
+ stubFetch(({ url }) => {
598
+ if (url.endsWith('/access')) return Response.json({ access: 'allowed' })
599
+ if (url.endsWith('/preview')) {
600
+ previewCalls += 1
601
+ if (previewCalls === 1) return Promise.reject(new TypeError('Failed to fetch'))
602
+ return Response.json(makePreview())
603
+ }
604
+ if (url.endsWith('/execute')) {
605
+ return Response.json({ code: 'identity_required', message: 'Human identity required.', retry: 'none', dispatch: 'not_dispatched' }, { status: 401 })
606
+ }
607
+ return Response.json({})
608
+ })
609
+ await act(async () => buttonsByText('Evict Pod')[0].click())
610
+ await vi.waitFor(() => expect(document.body.textContent).toContain('Failed to fetch'))
611
+ expect(document.body.textContent).not.toContain('Radar could not tell whether this took effect')
612
+ await act(async () => buttonsByText('Cancel')[0].click())
613
+
614
+ // Reopen after transient preview failure succeeds; pre-dispatch identity_required does NOT lock.
615
+ await act(async () => buttonsByText('Evict Pod')[0].click())
616
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false))
617
+ await act(async () => buttonsByText('Evict Pod').at(-1)!.click())
618
+ await vi.waitFor(() => expect(document.body.textContent).toContain('User identity required'))
619
+ expect(document.body.textContent).not.toContain('Radar could not tell whether this took effect')
620
+
621
+ // 4. Pre-dispatch reapprove with same UID requires one fresh confirm; replaced UID on reapprove blocks confirm.
622
+ let execCalls = 0
623
+ let reapproveUid = 'pod-uid-3'
624
+ stubFetch(({ url, body }) => {
625
+ if (url.endsWith('/access')) return Response.json({ access: 'allowed' })
626
+ if (url.endsWith('/preview')) {
627
+ return Response.json(makePreview({
628
+ target: { namespace: 'shop', name: 'checkout-0', uid: reapproveUid, apiVersion: 'v1' },
629
+ summary: 'Refreshed eviction preview for shop/checkout-0.',
630
+ fromPreview: { digest: DIGEST_2, actionVersion: 1, apiVersion: 'v1', preconditions: [{ strategy: 'uid_only', uid: reapproveUid }] },
631
+ }))
632
+ }
633
+ if (url.endsWith('/execute')) {
634
+ execCalls += 1
635
+ if (execCalls === 1) {
636
+ return Response.json({ code: 'preview_mismatch', message: 'Pod changed before send.', retry: 'reapprove', dispatch: 'not_dispatched' }, { status: 409 })
637
+ }
638
+ return makeAcceptedExecuteResponse(body?.executionId)
639
+ }
640
+ return Response.json({})
641
+ })
642
+ await act(async () => buttonsByText('Cancel')[0].click())
643
+ await act(async () => buttonsByText('Evict Pod')[0].click())
644
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false))
645
+ await act(async () => buttonsByText('Evict Pod').at(-1)!.click())
646
+ await vi.waitFor(() => expect(document.body.textContent).toContain('Pod changed before send.'))
647
+ expect(execCalls).toBe(1)
648
+
649
+ await act(async () => buttonsByText('Evict Pod').at(-1)!.click())
650
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
651
+ expect(execCalls).toBe(2)
652
+
653
+ // Replaced UID returned during reapprove refresh refuses instead of letting user confirm replacement pod.
654
+ execCalls = 0
655
+ let previewNum = 0
656
+ reapproveUid = 'pod-uid-replaced'
657
+ stubFetch(({ url }) => {
658
+ if (url.endsWith('/access')) return Response.json({ access: 'allowed' })
659
+ if (url.endsWith('/preview')) {
660
+ previewNum += 1
661
+ const uid = previewNum === 1 ? 'pod-uid-3' : reapproveUid
662
+ return Response.json(makePreview({ target: { namespace: 'shop', name: 'checkout-0', uid, apiVersion: 'v1' } }))
663
+ }
664
+ if (url.endsWith('/execute')) {
665
+ return Response.json({ code: 'preview_mismatch', message: 'Pod replaced.', retry: 'reapprove', dispatch: 'not_dispatched' }, { status: 409 })
666
+ }
667
+ return Response.json({})
668
+ })
669
+ await act(async () => buttonsByText('Evict Pod')[0].click())
670
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false))
671
+ await act(async () => buttonsByText('Evict Pod').at(-1)!.click())
672
+ await vi.waitFor(() => {
673
+ expect(document.body.textContent).toContain('Target changed')
674
+ expect(document.body.textContent).toContain('Close and reselect')
675
+ })
676
+ expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(true)
677
+ })
678
+
679
+ it('handles typed connection_changed and target_replaced/none without automatic repeats or replacement preview', async () => {
680
+ seedCapabilities()
681
+ const connChangedResponse = () =>
682
+ Response.json(
683
+ {
684
+ code: 'connection_changed',
685
+ message: 'The active cluster connection changed.',
686
+ retry: 'none',
687
+ dispatch: 'not_dispatched',
688
+ },
689
+ { status: 409 },
690
+ )
691
+
692
+ // 1. /access 409 connection_changed fails closed with zero automatic repeat.
693
+ stubFetch(() => connChangedResponse())
694
+ await renderNode(<PodEvictHarness pod={{ ...basePod, metadata: { ...basePod.metadata, uid: 'pod-uid-conn-access' } }} />)
695
+ await vi.waitFor(() => expect(calls).toHaveLength(1))
696
+ await act(async () => {})
697
+ expect(buttonsByText('Evict Pod')).toHaveLength(0)
698
+ expect(calls.map((c) => c.url)).toEqual(['/api/resource-actions/core/Pod/evict/access'])
699
+
700
+ // 2. /preview 409 connection_changed shows reload/reconnect guidance with zero automatic repeat.
701
+ calls.length = 0
702
+ stubFetch(({ url }) => {
703
+ if (url.endsWith('/access')) return Response.json({ access: 'allowed' })
704
+ if (url.endsWith('/preview')) return connChangedResponse()
705
+ return Response.json({})
706
+ })
707
+ await renderNode(<PodEvictHarness pod={basePod} />)
708
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod')).toHaveLength(1))
709
+ calls.length = 0
710
+ await act(async () => buttonsByText('Evict Pod')[0].click())
711
+ await vi.waitFor(() => {
712
+ expect(document.body.textContent).toContain('Cluster connection changed')
713
+ expect(document.body.textContent).toContain('Reload or reconnect this view before trying again.')
714
+ expect(document.body.textContent).toContain('Reload required')
715
+ expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(true)
716
+ })
717
+ expect(document.body.textContent).not.toContain('Radar could not tell whether this took effect')
718
+ await act(async () => {})
719
+ expect(calls.map((c) => c.url)).toEqual(['/api/resource-actions/core/Pod/evict/preview'])
720
+ await act(async () => buttonsByText('Cancel')[0].click())
721
+
722
+ // 3. /execute 409 connection_changed shows reload/reconnect guidance with zero automatic re-preview or execute repeat.
723
+ calls.length = 0
724
+ vi.mocked(showApiSuccess).mockClear()
725
+ stubFetch(({ url }) => {
726
+ if (url.endsWith('/access')) return Response.json({ access: 'allowed' })
727
+ if (url.endsWith('/preview')) return Response.json(makePreview())
728
+ if (url.endsWith('/execute')) return connChangedResponse()
729
+ return Response.json({})
730
+ })
731
+ await act(async () => buttonsByText('Evict Pod')[0].click())
732
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false))
733
+ await act(async () => buttonsByText('Evict Pod').at(-1)!.click())
734
+ await vi.waitFor(() => {
735
+ expect(document.body.textContent).toContain('Cluster connection changed')
736
+ expect(document.body.textContent).toContain('Reload or reconnect this view before trying again.')
737
+ expect(document.body.textContent).toContain('Reload required')
738
+ expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(true)
739
+ })
740
+ expect(document.body.textContent).not.toContain('Radar could not tell whether this took effect')
741
+ expect(showApiSuccess).not.toHaveBeenCalled()
742
+ await act(async () => {})
743
+ expect(calls.map((c) => c.url)).toEqual([
744
+ '/api/resource-actions/core/Pod/evict/preview',
745
+ '/api/resource-actions/core/Pod/evict/execute',
746
+ ])
747
+ await act(async () => buttonsByText('Cancel')[0].click())
748
+
749
+ // 4. Direct /execute 409 target_replaced/none shows reselect guidance with zero automatic replacement preview.
750
+ const invalidateSpy = vi.spyOn(client, 'invalidateQueries')
751
+ calls.length = 0
752
+ vi.mocked(showApiSuccess).mockClear()
753
+ stubFetch(({ url }) => {
754
+ if (url.endsWith('/access')) return Response.json({ access: 'allowed' })
755
+ if (url.endsWith('/preview')) return Response.json(makePreview())
756
+ if (url.endsWith('/execute')) {
757
+ return Response.json(
758
+ {
759
+ code: 'target_replaced',
760
+ message: 'Pod shop/checkout-0 was replaced.',
761
+ retry: 'none',
762
+ dispatch: 'not_dispatched',
763
+ },
764
+ { status: 409 },
765
+ )
766
+ }
767
+ return Response.json({})
768
+ })
769
+ await act(async () => buttonsByText('Evict Pod')[0].click())
770
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false))
771
+ await act(async () => buttonsByText('Evict Pod').at(-1)!.click())
772
+ await vi.waitFor(() => {
773
+ expect(document.body.textContent).toContain('Target changed')
774
+ expect(document.body.textContent).toContain('Pod shop/checkout-0 was replaced. Close and reselect it before trying again.')
775
+ expect(document.body.textContent).toContain('Reselection required')
776
+ expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(true)
777
+ })
778
+ expect(document.body.textContent).not.toContain('Radar could not tell whether this took effect')
779
+ expect(showApiSuccess).not.toHaveBeenCalled()
780
+ await act(async () => {})
781
+ expect(calls.map((c) => c.url)).toEqual([
782
+ '/api/resource-actions/core/Pod/evict/preview',
783
+ '/api/resource-actions/core/Pod/evict/execute',
784
+ ])
785
+ expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['resources', 'pods'] })
786
+ expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['resource', 'pods', 'shop', 'checkout-0'] })
787
+ })
788
+
789
+ it('retains target_replaced notice across early and late same-locator Pod UID changes without extra preview/execute, and dismisses on target/connection switch or other errors', async () => {
790
+ seedCapabilities()
791
+ let resolveExecute!: (res: Response) => void
792
+ const targetReplacedResponse = () =>
793
+ Response.json(
794
+ {
795
+ code: 'target_replaced',
796
+ message: 'Pod shop/checkout-0 was replaced.',
797
+ retry: 'none',
798
+ dispatch: 'not_dispatched',
799
+ },
800
+ { status: 409 },
801
+ )
802
+
803
+ stubFetch(({ url }) => {
804
+ if (url.endsWith('/access')) return Response.json({ access: 'allowed' })
805
+ if (url.endsWith('/preview')) return Response.json(makePreview())
806
+ if (url.endsWith('/execute')) return new Promise<Response>((resolve) => { resolveExecute = resolve })
807
+ return Response.json({})
808
+ })
809
+
810
+ const podWith = (overrides: { name?: string; uid: string }): PodEvictTarget => ({
811
+ ...basePod,
812
+ metadata: { ...basePod.metadata, ...overrides },
813
+ })
814
+
815
+ const startDeferredExecute = async () => {
816
+ calls.length = 0
817
+ await renderNode(<PodEvictHarness pod={basePod} />)
818
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod')).toHaveLength(1))
819
+ await act(async () => buttonsByText('Evict Pod')[0].click())
820
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false))
821
+ await act(async () => buttonsByText('Evict Pod').at(-1)!.click())
822
+ await vi.waitFor(() => expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1))
823
+ }
824
+
825
+ const expectRetainedNotice = async () => {
826
+ await vi.waitFor(() => {
827
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
828
+ expect(document.body.textContent).toContain('Target changed')
829
+ expect(document.body.textContent).toContain('Pod shop/checkout-0 was replaced. Close and reselect it before trying again.')
830
+ expect(document.body.textContent).toContain('Reselection required')
831
+ expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(true)
832
+ })
833
+ expect(showApiSuccess).not.toHaveBeenCalled()
834
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(1)
835
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1)
836
+ }
837
+
838
+ // Early order: replacement UID renders before deferred 409 target_replaced settles.
839
+ await startDeferredExecute()
840
+ await renderNode(<PodEvictHarness pod={podWith({ uid: 'pod-uid-4' })} />)
841
+ await act(async () => { resolveExecute(targetReplacedResponse()) })
842
+ await expectRetainedNotice()
843
+
844
+ // Another same-locator UID refetch keeps the retained notice visible with zero extra preview/execute.
845
+ await renderNode(<PodEvictHarness pod={podWith({ uid: 'pod-uid-5' })} />)
846
+ await expectRetainedNotice()
847
+
848
+ // Different Pod locator closes the retained notice immediately without extra preview/execute.
849
+ await renderNode(<PodEvictHarness pod={podWith({ name: 'checkout-1', uid: 'pod-uid-other' })} />)
850
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
851
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(1)
852
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1)
853
+
854
+ // Late order through shared #2999 retention: 409 target_replaced settles first, then replacement UID renders.
855
+ await startDeferredExecute()
856
+ await act(async () => { resolveExecute(targetReplacedResponse()) })
857
+ await expectRetainedNotice()
858
+ await renderNode(<PodEvictHarness pod={podWith({ uid: 'pod-uid-4' })} />)
859
+ await expectRetainedNotice()
860
+
861
+ // Switching cluster connection closes the retained notice even at the same locator.
862
+ await act(async () => { observeConnectionStatus({ connectionId: 'conn-2' }) })
863
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
864
+
865
+ // Connection switch while deferred target_replaced is in flight dismisses it instead of retaining.
866
+ await act(async () => { observeConnectionStatus({ connectionId: 'conn-1' }) })
867
+ await startDeferredExecute()
868
+ await act(async () => { observeConnectionStatus({ connectionId: 'conn-2' }) })
869
+ await act(async () => { resolveExecute(targetReplacedResponse()) })
870
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
871
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(1)
872
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1)
873
+
874
+ // Non-target_replaced deferred error after UID change is still dismissed.
875
+ await act(async () => { observeConnectionStatus({ connectionId: 'conn-1' }) })
876
+ await startDeferredExecute()
877
+ await renderNode(<PodEvictHarness pod={podWith({ uid: 'pod-uid-6' })} />)
878
+ await act(async () => {
879
+ resolveExecute(
880
+ Response.json(
881
+ { code: 'temporarily_unavailable', message: 'PDB refusal', retry: 'later', dispatch: 'not_dispatched' },
882
+ { status: 429 },
883
+ ),
884
+ )
885
+ })
886
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
887
+ })
888
+
889
+ it('wires WorkloadView Pod detail to exact /access, skips inactive drawer layers, and runs confirmed eviction', async () => {
890
+ seedCapabilities()
891
+ const fullPod = {
892
+ ...basePod,
893
+ spec: { ...basePod.spec, containers: [{ name: 'app', image: 'nginx:1.27' }] },
894
+ status: { phase: 'Running', containerStatuses: [{ name: 'app', ready: true, state: { running: {} } }] },
895
+ }
896
+ client.setQueryData(['api-resources'], [])
897
+
898
+ stubFetch(({ url, body }) => {
899
+ if (url.endsWith('/resources/pods/shop/checkout-0')) return Response.json({ resource: fullPod, relationships: {} })
900
+ if (url.endsWith('/capabilities')) {
901
+ return Response.json({
902
+ features: { resourceActions: true },
903
+ reviewedActions: { contractVersion: 1, actions: [POD_EVICT_ID] },
904
+ })
905
+ }
906
+ if (url.endsWith('/connection-status')) return Response.json({ state: 'connected', context: 'prod-cluster', connectionId: 'conn-1' })
907
+ if (url.endsWith('/core/Pod/evict/access')) return Response.json({ access: 'allowed' })
908
+ if (url.endsWith('/core/Pod/evict/preview')) return Response.json(makePreview())
909
+ if (url.endsWith('/core/Pod/evict/execute')) return makeAcceptedExecuteResponse(body?.executionId)
910
+ if (url.includes('/audit/') || url.includes('/api-resources') || url.includes('/events') || url.includes('/changes') || url.includes('/issues')) return Response.json([])
911
+ return Response.json({ error: 'not mocked' }, { status: 404 })
912
+ })
913
+
914
+ const renderWorkload = (active: boolean) =>
915
+ renderNode(
916
+ <ConnectionProvider>
917
+ <ToastProvider>
918
+ <DockProvider>
919
+ <MemoryRouter initialEntries={['/workload/pods/shop/checkout-0']}>
920
+ <WorkloadView kind="pods" namespace="shop" name="checkout-0" group="" onBack={() => {}} expanded={false} active={active} />
921
+ </MemoryRouter>
922
+ </DockProvider>
923
+ </ToastProvider>
924
+ </ConnectionProvider>,
925
+ )
926
+
927
+ // Inactive drawer layer must not query /access or render Evict Pod.
928
+ await renderWorkload(false)
929
+ expect(calls.filter((c) => c.url.endsWith('/core/Pod/evict/access'))).toHaveLength(0)
930
+ expect(buttonsByText('Evict Pod')).toHaveLength(0)
931
+
932
+ // Active Pod detail queries exact /access once, previews once, and accepts only after confirm.
933
+ await renderWorkload(true)
934
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod')).toHaveLength(1))
935
+ expect(calls.filter((c) => c.url.endsWith('/core/Pod/evict/access'))).toEqual([{
936
+ url: '/api/resource-actions/core/Pod/evict/access',
937
+ method: 'POST',
938
+ body: { target: { namespace: 'shop', name: 'checkout-0' } },
939
+ connectionId: 'conn-1',
940
+ }])
941
+
942
+ await act(async () => buttonsByText('Evict Pod')[0].click())
943
+ await vi.waitFor(() => expect(buttonsByText('Evict Pod').at(-1)!.disabled).toBe(false))
944
+ expect(calls.filter((c) => c.url.endsWith('/core/Pod/evict/preview'))).toHaveLength(1)
945
+ expect(calls.filter((c) => c.url.endsWith('/core/Pod/evict/execute'))).toHaveLength(0)
946
+
947
+ await act(async () => buttonsByText('Evict Pod').at(-1)!.click())
948
+ await vi.waitFor(() => expect(showApiSuccess).toHaveBeenCalledWith('Eviction accepted', expect.any(String)))
949
+ expect(calls.filter((c) => c.url.endsWith('/core/Pod/evict/execute'))).toHaveLength(1)
950
+ })
951
+ })