@skyhook-io/radar-app 1.22.0 → 1.22.2

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 (95) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +98 -29
  3. package/src/RadarApp.tsx +5 -0
  4. package/src/api/client.ts +18 -1
  5. package/src/api/cnpg-history.ts +3 -3
  6. package/src/api/cnpg-storage.ts +3 -3
  7. package/src/api/diagnose.test.ts +34 -0
  8. package/src/api/diagnose.ts +17 -4
  9. package/src/api/radarFeatures.test.ts +13 -1
  10. package/src/api/radarFeatures.ts +2 -0
  11. package/src/api/resourceActions.test.ts +829 -0
  12. package/src/api/resourceActions.ts +584 -0
  13. package/src/api/resourceActions.ui.test.tsx +1882 -0
  14. package/src/api/reviewedActionMutation.ts +56 -28
  15. package/src/api/substrateHealth.ts +2 -3
  16. package/src/api/traffic.ts +13 -5
  17. package/src/api/workloadMetrics.test.ts +11 -2
  18. package/src/api/workloadMetrics.ts +2 -2
  19. package/src/api/workloadSource.test.tsx +857 -0
  20. package/src/api/workloadSource.ts +292 -0
  21. package/src/components/APIUnreachableBanner.test.tsx +19 -0
  22. package/src/components/APIUnreachableBanner.tsx +20 -0
  23. package/src/components/ConnectionErrorView.test.tsx +63 -2
  24. package/src/components/ConnectionErrorView.tsx +88 -68
  25. package/src/components/diagnose/ActivityTurn.tsx +6 -4
  26. package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
  27. package/src/components/diagnose/AssessmentCard.tsx +1 -2
  28. package/src/components/diagnose/ContinueInAgentButton.test.tsx +7 -0
  29. package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
  30. package/src/components/diagnose/DiagnoseContext.tsx +28 -3
  31. package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
  32. package/src/components/diagnose/Home.test.tsx +6 -0
  33. package/src/components/diagnose/Home.tsx +13 -3
  34. package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +1 -1
  35. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
  36. package/src/components/diagnose/InvestigationEvidencePane.tsx +19 -2
  37. package/src/components/diagnose/InvestigationFindingsFooter.test.tsx +413 -0
  38. package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
  39. package/src/components/diagnose/InvestigationView.tsx +130 -25
  40. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
  41. package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
  42. package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
  43. package/src/components/diagnose/QuestionComposer.tsx +13 -8
  44. package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
  45. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
  46. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
  47. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
  48. package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
  49. package/src/components/diagnose/investigationEvidence/identity.test.ts +1 -1
  50. package/src/components/diagnose/investigationEvidence/projection.test.ts +1 -1
  51. package/src/components/diagnose/investigationState.ts +9 -0
  52. package/src/components/diagnose/launch.ts +1 -1
  53. package/src/components/diagnose/parts.test.tsx +11 -3
  54. package/src/components/diagnose/toolCallLabel.ts +3 -0
  55. package/src/components/dock/PodDebugSession.test.tsx +66 -0
  56. package/src/components/dock/PodDebugSession.tsx +3 -1
  57. package/src/components/dock/TerminalTab.test.tsx +43 -3
  58. package/src/components/dock/TerminalTab.tsx +10 -1
  59. package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
  60. package/src/components/helm/InstallWizard.tsx +1 -1
  61. package/src/components/home/ActivitySummary.tsx +3 -8
  62. package/src/components/home/ClusterHealthCard.tsx +91 -17
  63. package/src/components/home/ClusterHealthCard.utilization.test.tsx +187 -0
  64. package/src/components/home/HomeView.tsx +6 -26
  65. package/src/components/home/TopologyPreview.test.tsx +31 -30
  66. package/src/components/home/TopologyPreview.tsx +19 -28
  67. package/src/components/home/mcpToolCatalog.ts +4 -4
  68. package/src/components/resources/PodEvictAction.test.tsx +951 -0
  69. package/src/components/resources/PodEvictAction.tsx +167 -0
  70. package/src/components/resources/ResourcesView.tsx +3 -0
  71. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +5 -4
  72. package/src/components/resources/renderers/RolloutRenderer.tsx +4 -1
  73. package/src/components/resources/renderers/WorkloadRenderer.tsx +7 -1
  74. package/src/components/settings/LocalConnectionSettings.tsx +4 -4
  75. package/src/components/settings/SettingsDialog.tsx +23 -18
  76. package/src/components/settings/integrationQueries.test.ts +98 -0
  77. package/src/components/settings/integrationQueries.ts +36 -0
  78. package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
  79. package/src/components/traffic/TrafficView.tsx +91 -35
  80. package/src/components/ui/Markdown.test.tsx +37 -0
  81. package/src/components/ui/Markdown.tsx +15 -2
  82. package/src/components/useContextSwitchFlow.test.tsx +27 -2
  83. package/src/components/useContextSwitchFlow.tsx +20 -22
  84. package/src/components/workload/WorkloadView.tsx +83 -4
  85. package/src/components/workload/WorkloadView.workloadSource.test.tsx +121 -0
  86. package/src/context/ConnectionContext.tsx +24 -5
  87. package/src/context/ConnectionProvider.connectionId.test.tsx +14 -0
  88. package/src/context/ConnectionProvider.handover.test.tsx +94 -0
  89. package/src/context/DiagnoseCustomization.tsx +20 -2
  90. package/src/hooks/useEventSource.test.tsx +275 -4
  91. package/src/hooks/useEventSource.ts +278 -51
  92. package/src/index.ts +1 -0
  93. package/src/utils/navigation.test.ts +1 -6
  94. package/src/utils/navigation.ts +9 -44
  95. package/src/utils/network-policy-navigation.test.ts +21 -36
@@ -0,0 +1,1882 @@
1
+ // @vitest-environment jsdom
2
+ import { act, type ComponentProps } from 'react'
3
+ import { flushSync } from 'react-dom'
4
+ import { createRoot, type Root } from 'react-dom/client'
5
+ import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
7
+ import {
8
+ BulkReviewedActionDialog,
9
+ RESOURCE_ACTION_IDS,
10
+ ResourceActionsBar,
11
+ type ResourceActionClientAdapter,
12
+ type ResourceActionPreviewResponse,
13
+ } from '@skyhook-io/k8s-ui'
14
+ import { WorkloadRenderer } from '@skyhook-io/k8s-ui/components/resources/renderers/WorkloadRenderer'
15
+ import { useResourceActionAdapter } from './resourceActions'
16
+ import { getApiBase } from './config'
17
+ import { observeConnectionStatus, resetConnectionBindingForTest } from './connectionBinding'
18
+
19
+ ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
20
+
21
+ interface RecordedCall {
22
+ url: string
23
+ method: string
24
+ body?: Record<string, unknown>
25
+ connectionId: string | null
26
+ }
27
+
28
+ function makePreview(actionId: string, overrides: Partial<ResourceActionPreviewResponse> = {}): ResourceActionPreviewResponse {
29
+ return {
30
+ actionId,
31
+ actionVersion: 1,
32
+ target: { namespace: 'prod', name: 'web', uid: 'uid-1', apiVersion: 'apps/v1' },
33
+ summary: `Preview for ${actionId}`,
34
+ changes: [{
35
+ object: { apiVersion: 'apps/v1', kind: 'Deployment', namespace: 'prod', name: 'web', uid: 'uid-1' },
36
+ changeType: 'update',
37
+ deltas: [{ path: '/spec/replicas', before: 2, after: 4 }],
38
+ }],
39
+ facts: {},
40
+ warnings: [],
41
+ fromPreview: {
42
+ digest: `v1:sha256:${actionId}:1`,
43
+ actionVersion: 1,
44
+ apiVersion: 'apps/v1',
45
+ preconditions: [{ uid: 'uid-1', resourceVersion: '10' }],
46
+ },
47
+ ...overrides,
48
+ }
49
+ }
50
+
51
+ const DEPLOYMENT_DATA = {
52
+ apiVersion: 'apps/v1',
53
+ kind: 'Deployment',
54
+ metadata: { name: 'web', namespace: 'prod', uid: 'uid-1' },
55
+ spec: { replicas: 2, paused: false },
56
+ status: { readyReplicas: 2 },
57
+ }
58
+
59
+ const CRONJOB_DATA = {
60
+ apiVersion: 'batch/v1',
61
+ kind: 'CronJob',
62
+ metadata: { name: 'nightly', namespace: 'prod', uid: 'cj-1' },
63
+ spec: { suspend: false },
64
+ }
65
+
66
+ function WorkloadHarness(props: Omit<ComponentProps<typeof WorkloadRenderer>, 'resourceActionAdapter'>) {
67
+ const adapter = useResourceActionAdapter()
68
+ return <WorkloadRenderer {...props} resourceActionAdapter={adapter} />
69
+ }
70
+
71
+ function ActionsBarHarness(props: Omit<ComponentProps<typeof ResourceActionsBar>, 'resourceActionAdapter'>) {
72
+ const adapter = useResourceActionAdapter()
73
+ return <ResourceActionsBar {...props} resourceActionAdapter={adapter} />
74
+ }
75
+
76
+ function BulkHarness(props: Omit<ComponentProps<typeof BulkReviewedActionDialog>, 'adapter'>) {
77
+ const adapter = useResourceActionAdapter()
78
+ return <BulkReviewedActionDialog {...props} adapter={adapter} />
79
+ }
80
+
81
+ function QueryBackedWorkloadHarness({ namespace, name }: { namespace: string; name: string }) {
82
+ const { data } = useQuery({
83
+ queryKey: ['resource', 'deployments', namespace, name],
84
+ queryFn: async () => {
85
+ const res = await fetch(`/api/resources/deployments/${namespace}/${name}`)
86
+ return res.json()
87
+ },
88
+ })
89
+ if (!data) return null
90
+ return <WorkloadHarness kind="deployments" data={data} />
91
+ }
92
+
93
+ describe('D4 resource actions UI regression journeys', () => {
94
+ let host: HTMLDivElement
95
+ let root: Root
96
+ let client: QueryClient
97
+ let calls: RecordedCall[]
98
+
99
+ beforeEach(() => {
100
+ calls = []
101
+ if (typeof globalThis.ResizeObserver === 'undefined') {
102
+ vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} })
103
+ }
104
+ resetConnectionBindingForTest()
105
+ observeConnectionStatus({ connectionId: 'conn-1' })
106
+ host = document.createElement('div')
107
+ document.body.appendChild(host)
108
+ root = createRoot(host)
109
+ client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
110
+ client.setQueryData(['connection-status'], { context: 'eks-staging' })
111
+ client.setQueryData(['version-check', getApiBase()], {})
112
+ })
113
+
114
+ afterEach(async () => {
115
+ await act(async () => root.unmount())
116
+ host.remove()
117
+ document.body.innerHTML = ''
118
+ client.clear()
119
+ resetConnectionBindingForTest()
120
+ vi.unstubAllGlobals()
121
+ vi.restoreAllMocks()
122
+ ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
123
+ })
124
+
125
+ function seedD4(actions: string[] = Object.values(RESOURCE_ACTION_IDS)) {
126
+ client.setQueryData(['capabilities'], {
127
+ features: { resourceActions: true, deploymentPause: true, workloadRestartPreconditions: true, cronJobTriggerJobName: true },
128
+ reviewedActions: { contractVersion: 1, actions },
129
+ })
130
+ }
131
+
132
+ function seedLegacy() {
133
+ client.setQueryData(['capabilities'], {
134
+ features: { deploymentPause: true, workloadRestartPreconditions: true, cronJobTriggerJobName: true },
135
+ })
136
+ }
137
+
138
+ function stubFetch(handler: (call: RecordedCall) => Response | Promise<Response>) {
139
+ vi.stubGlobal(
140
+ 'fetch',
141
+ vi.fn<typeof fetch>(async (input, init) => {
142
+ const call: RecordedCall = {
143
+ url: String(input),
144
+ method: init?.method ?? 'GET',
145
+ body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
146
+ connectionId: new Headers(init?.headers).get('X-Radar-Connection'),
147
+ }
148
+ calls.push(call)
149
+ return handler(call)
150
+ }),
151
+ )
152
+ }
153
+
154
+ const render = (node: React.ReactNode) =>
155
+ act(async () => {
156
+ root.render(<QueryClientProvider client={client}>{node}</QueryClientProvider>)
157
+ })
158
+
159
+ const buttonByText = (label: string) =>
160
+ [...document.querySelectorAll('button')].filter((b) => b.textContent?.trim() === label).at(-1)
161
+
162
+ it('Scale uses one ActionConfirmDialog with D4 preview, exact controller facts, warnings, and pinned connection', async () => {
163
+ seedD4()
164
+ const legacyScale = vi.fn(async () => {})
165
+ stubFetch(({ url, body }) => {
166
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
167
+ return Response.json(
168
+ makePreview('apps/Deployment/scale', {
169
+ previewedAs: { user: 'local-kubeconfig' },
170
+ summary: 'Scale Deployment prod/web from 2 to 3 replicas.',
171
+ changes: [{
172
+ object: { apiVersion: 'apps/v1', kind: 'Deployment', namespace: 'prod', name: 'web', uid: 'uid-1' },
173
+ changeType: 'update',
174
+ deltas: [{ path: '/spec/replicas', before: 2, after: 3 }],
175
+ }],
176
+ facts: {
177
+ gitops: {
178
+ state: 'known',
179
+ value: {
180
+ controllers: [{ group: 'argoproj.io', kind: 'Application', namespace: 'argocd', name: 'web-app', selfHeal: true }],
181
+ },
182
+ },
183
+ },
184
+ warnings: [{ code: 'gitops_managed', severity: 'warn', message: 'Argo CD selfHeal may revert manual scaling.' }],
185
+ }),
186
+ )
187
+ }
188
+ if (url.endsWith('/apps/Deployment/scale/execute')) return Response.json({ executionId: body?.executionId, outcome: 'applied' })
189
+ return Response.json({})
190
+ })
191
+
192
+ await render(<WorkloadHarness kind="deployments" data={DEPLOYMENT_DATA} onScale={legacyScale} />)
193
+ await act(async () => buttonByText('Scale')!.click())
194
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
195
+ expect(document.body.textContent).toContain('eks-staging')
196
+
197
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
198
+ await vi.waitFor(() => {
199
+ expect(document.body.textContent).toContain('Scale Deployment prod/web from 2 to 3 replicas.')
200
+ expect(document.body.textContent).toContain('/spec/replicas:')
201
+ expect(document.body.textContent).toContain('Argo CD selfHeal may revert manual scaling.')
202
+ expect(document.body.textContent).toContain('Managed by Argo CD Application argocd/web-app (selfHeal on)')
203
+ })
204
+ expect(document.body.textContent).not.toContain('local-kubeconfig')
205
+ expect(document.body.textContent).not.toContain('Previewed as')
206
+ expect(document.body.textContent).not.toContain('The API write')
207
+
208
+ // Simulate connection switch while dialog is open — execute must still send conn-1
209
+ observeConnectionStatus({ connectionId: 'conn-2' })
210
+ await act(async () => buttonByText('Apply')!.click())
211
+
212
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
213
+ expect(legacyScale).not.toHaveBeenCalled()
214
+ expect(calls.map((c) => c.url)).toEqual([
215
+ '/api/resource-actions/apps/Deployment/scale/preview',
216
+ '/api/resource-actions/apps/Deployment/scale/execute',
217
+ ])
218
+ expect(calls[1].connectionId).toBe('conn-1')
219
+ })
220
+
221
+ it('Preserves HPA-managed scale restriction under D4', async () => {
222
+ seedD4()
223
+ await render(
224
+ <WorkloadHarness
225
+ kind="deployments"
226
+ data={DEPLOYMENT_DATA}
227
+ scaleBlockedBy={[{ kind: 'HorizontalPodAutoscaler', namespace: 'prod', name: 'web-hpa' }]}
228
+ />,
229
+ )
230
+ const scaleBtn = buttonByText('Scale')!
231
+ expect(scaleBtn.disabled).toBe(true)
232
+ expect(scaleBtn.getAttribute('aria-label')).toContain('HorizontalPodAutoscaler prod/web-hpa')
233
+ })
234
+
235
+ it('Scale keeps dialog open on identity_required and locks Confirm across reopen after dispatch_unknown', async () => {
236
+ seedD4()
237
+ const legacyScale = vi.fn(async () => {})
238
+ let mode: 'identity' | 'unknown' = 'identity'
239
+ stubFetch(({ url }) => {
240
+ if (url.endsWith('/preview')) return Response.json(makePreview('apps/Deployment/scale'))
241
+ if (url.endsWith('/execute')) {
242
+ return mode === 'identity'
243
+ ? Response.json({ code: 'identity_required', message: 'Human sign-in required.', retry: 'none', dispatch: 'not_dispatched' }, { status: 401 })
244
+ : Response.json({ code: 'dispatch_unknown', message: 'Connection lost after dispatch.', retry: 'none', dispatch: 'unknown' }, { status: 503 })
245
+ }
246
+ return Response.json({})
247
+ })
248
+
249
+ await render(<WorkloadHarness kind="deployments" data={DEPLOYMENT_DATA} onScale={legacyScale} />)
250
+ await act(async () => buttonByText('Scale')!.click())
251
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
252
+ await vi.waitFor(() => expect(buttonByText('Apply')!.disabled).toBe(false))
253
+
254
+ await act(async () => buttonByText('Apply')!.click())
255
+ await vi.waitFor(() => {
256
+ expect(document.body.textContent).toContain('User identity required')
257
+ expect(document.body.textContent).toContain('Human sign-in required.')
258
+ })
259
+ expect(legacyScale).not.toHaveBeenCalled()
260
+
261
+ mode = 'unknown'
262
+ await act(async () => buttonByText('Apply')!.click())
263
+ await vi.waitFor(() => {
264
+ expect(document.body.textContent).toContain('Radar could not tell whether this took effect')
265
+ expect(document.body.textContent).toContain('Inspect the current state in Kubernetes first, then reload this page and review the action again.')
266
+ expect(buttonByText('Apply')!.disabled).toBe(true)
267
+ })
268
+
269
+ await act(async () => buttonByText('Cancel')!.click())
270
+ await act(async () => buttonByText('Scale')!.click())
271
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
272
+ expect(document.body.textContent).toContain('Radar could not tell whether this took effect')
273
+ expect(document.body.textContent).toContain('Inspect the current state in Kubernetes first, then reload this page and review the action again.')
274
+ expect(buttonByText('Apply')!.disabled).toBe(true)
275
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(2)
276
+ })
277
+
278
+ it('D4 Restart refuses mismatched selected UID and requires one visible confirmation for both clean and warning previews', async () => {
279
+ seedD4()
280
+ const legacyRestart = vi.fn()
281
+ let previewUid = 'uid-replaced'
282
+ let emitWarning = false
283
+ stubFetch(({ url, body }) => {
284
+ if (url.endsWith('/apps/Deployment/restart/preview')) {
285
+ return Response.json(
286
+ makePreview('apps/Deployment/restart', {
287
+ target: { namespace: 'prod', name: 'web', uid: previewUid, apiVersion: 'apps/v1' },
288
+ previewedAs: { user: 'alice@example.com' },
289
+ summary: 'Restart Deployment prod/web.',
290
+ changes: [{
291
+ object: { apiVersion: 'apps/v1', kind: 'Deployment', namespace: 'prod', name: 'web', uid: previewUid },
292
+ changeType: 'update',
293
+ deltas: [{ path: '/spec/template/metadata/annotations/kubectl.kubernetes.io~1restartedAt', after: '<at execute>' }],
294
+ }],
295
+ warnings: emitWarning ? [{ code: 'gitops_self_heal', severity: 'warn', message: 'GitOps controller may reconcile this change.' }] : [],
296
+ }),
297
+ )
298
+ }
299
+ if (url.endsWith('/apps/Deployment/restart/execute')) return Response.json({ executionId: body?.executionId, outcome: 'applied' })
300
+ return Response.json({})
301
+ })
302
+
303
+ await render(
304
+ <ActionsBarHarness
305
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'web' }}
306
+ data={DEPLOYMENT_DATA}
307
+ onRestart={legacyRestart}
308
+ />,
309
+ )
310
+
311
+ // Mismatched UID -> refuses before execute and keeps Confirm disabled
312
+ await act(async () => buttonByText('Restart')!.click())
313
+ await vi.waitFor(() => {
314
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
315
+ expect(document.body.textContent).toContain('Target changed')
316
+ expect(document.body.textContent).toContain('Close and reselect')
317
+ expect(buttonByText('Restart')!.disabled).toBe(true)
318
+ })
319
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(0)
320
+ await act(async () => buttonByText('Cancel')!.click())
321
+
322
+ // Matching UID + clean preview -> opens one confirmation dialog, waits for Restart confirm, and shows real user identity
323
+ calls.length = 0
324
+ previewUid = 'uid-1'
325
+ await act(async () => buttonByText('Restart')!.click())
326
+ await vi.waitFor(() => {
327
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
328
+ expect(document.body.textContent).toContain('Restart Deployment prod/web.')
329
+ expect(document.body.textContent).toContain('Previewed as alice@example.com')
330
+ expect(buttonByText('Restart')!.disabled).toBe(false)
331
+ })
332
+ expect(calls.map((c) => c.url)).toEqual(['/api/resource-actions/apps/Deployment/restart/preview'])
333
+
334
+ await act(async () => buttonByText('Restart')!.click())
335
+ await vi.waitFor(() => {
336
+ expect(calls.map((c) => c.url)).toEqual([
337
+ '/api/resource-actions/apps/Deployment/restart/preview',
338
+ '/api/resource-actions/apps/Deployment/restart/execute',
339
+ ])
340
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0)
341
+ })
342
+ expect(legacyRestart).not.toHaveBeenCalled()
343
+
344
+ // Preview with warning -> opens single ActionConfirmDialog and waits for confirmation
345
+ emitWarning = true
346
+ await act(async () => buttonByText('Restart')!.click())
347
+ await vi.waitFor(() => {
348
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
349
+ expect(document.body.textContent).toContain('GitOps controller may reconcile this change.')
350
+ })
351
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1)
352
+
353
+ await act(async () => buttonByText('Restart')!.click())
354
+ await vi.waitFor(() => {
355
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(2)
356
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0)
357
+ })
358
+ expect(legacyRestart).not.toHaveBeenCalled()
359
+ })
360
+
361
+ it('CronJob Trigger uses D4 dialog without editable Job name and never downgrades on error', async () => {
362
+ seedD4()
363
+ const legacyTrigger = vi.fn()
364
+ stubFetch(({ url }) => {
365
+ if (url.endsWith('/batch/CronJob/trigger/preview')) {
366
+ return Response.json(
367
+ makePreview('batch/CronJob/trigger', {
368
+ target: { namespace: 'prod', name: 'nightly', uid: 'cj-1', apiVersion: 'batch/v1' },
369
+ summary: 'Create a Job from CronJob prod/nightly.',
370
+ changes: [{ object: { apiVersion: 'batch/v1', kind: 'Job', namespace: 'prod', name: '<derived>' }, changeType: 'create' }],
371
+ }),
372
+ )
373
+ }
374
+ if (url.endsWith('/batch/CronJob/trigger/execute')) {
375
+ return Response.json({ code: 'forbidden', message: 'cannot create jobs', retry: 'none', dispatch: 'not_dispatched' }, { status: 403 })
376
+ }
377
+ return Response.json({})
378
+ })
379
+
380
+ await render(
381
+ <ActionsBarHarness
382
+ resource={{ kind: 'cronjobs', group: 'batch', namespace: 'prod', name: 'nightly' }}
383
+ data={CRONJOB_DATA}
384
+ onTriggerCronJob={legacyTrigger}
385
+ cronJobTriggerDialog
386
+ />,
387
+ )
388
+ await act(async () => buttonByText('Trigger')!.click())
389
+ await vi.waitFor(() => {
390
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
391
+ expect(document.body.textContent).toContain('Create a Job from CronJob prod/nightly.')
392
+ })
393
+ expect(document.querySelector('input[aria-label="Job name"]')).toBeNull()
394
+ expect(calls[0].body).toEqual({ target: { namespace: 'prod', name: 'nightly' }, parameters: {} })
395
+
396
+ await act(async () => buttonByText('Trigger')!.click())
397
+ await vi.waitFor(() => {
398
+ expect(document.body.textContent).toContain('Permission denied')
399
+ expect(document.body.textContent).toContain('cannot create jobs')
400
+ })
401
+ expect(legacyTrigger).not.toHaveBeenCalled()
402
+ })
403
+
404
+ it('Deployment Rollback uses one D4 ActionConfirmDialog while StatefulSet Rollback stays on legacy path', async () => {
405
+ seedD4()
406
+ const legacyRollback = vi.fn()
407
+ stubFetch(({ url, body }) => {
408
+ if (url.endsWith('/apps/Deployment/rollback/preview')) {
409
+ return Response.json(
410
+ makePreview('apps/Deployment/rollback', {
411
+ summary: 'Roll back Deployment prod/web to revision #1.',
412
+ changes: [{
413
+ object: { apiVersion: 'apps/v1', kind: 'Deployment', namespace: 'prod', name: 'web', uid: 'uid-1' },
414
+ changeType: 'update',
415
+ deltas: [{ path: '/spec/template/spec/containers/0/image', before: 'app:v2', after: 'app:v1' }],
416
+ }],
417
+ }),
418
+ )
419
+ }
420
+ if (url.endsWith('/apps/Deployment/rollback/execute')) return Response.json({ executionId: body?.executionId, outcome: 'applied' })
421
+ return Response.json({})
422
+ })
423
+
424
+ const revisions = [
425
+ { number: 2, createdAt: '2026-11-29T10:00:00Z', image: 'app:v2', isCurrent: true, replicas: 2 },
426
+ { number: 1, createdAt: '2026-11-28T10:00:00Z', image: 'app:v1', isCurrent: false, replicas: 0 },
427
+ ]
428
+
429
+ await render(
430
+ <ActionsBarHarness
431
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'web' }}
432
+ data={DEPLOYMENT_DATA}
433
+ revisions={revisions}
434
+ onRollback={legacyRollback}
435
+ />,
436
+ )
437
+ await act(async () => buttonByText('Rollback')!.click())
438
+ await act(async () => buttonByText('Rollback')!.click())
439
+ await vi.waitFor(() => {
440
+ expect(document.body.textContent).toContain('Roll back Deployment prod/web to revision #1.')
441
+ expect(document.body.textContent).toContain('app:v2')
442
+ expect(document.body.textContent).toContain('app:v1')
443
+ })
444
+ expect(buttonByText('Confirm')).toBeUndefined()
445
+
446
+ await act(async () => buttonByText('Rollback')!.click())
447
+ await vi.waitFor(() => {
448
+ expect(calls.map((c) => c.url)).toEqual([
449
+ '/api/resource-actions/apps/Deployment/rollback/preview',
450
+ '/api/resource-actions/apps/Deployment/rollback/execute',
451
+ ])
452
+ })
453
+ expect(calls[0].body).toEqual({ target: { namespace: 'prod', name: 'web' }, parameters: { revision: 1 } })
454
+ expect(legacyRollback).not.toHaveBeenCalled()
455
+
456
+ await render(
457
+ <ActionsBarHarness
458
+ resource={{ kind: 'statefulsets', group: 'apps', namespace: 'prod', name: 'db' }}
459
+ data={{ apiVersion: 'apps/v1', kind: 'StatefulSet', metadata: { name: 'db', namespace: 'prod', uid: 'uid-2' } }}
460
+ revisions={revisions}
461
+ onRollback={legacyRollback}
462
+ />,
463
+ )
464
+ await act(async () => buttonByText('Rollback')!.click())
465
+ await act(async () => buttonByText('Rollback')!.click())
466
+ expect(buttonByText('Confirm')).toBeDefined()
467
+ await act(async () => buttonByText('Confirm')!.click())
468
+ expect(legacyRollback).toHaveBeenCalledWith({ kind: 'statefulsets', namespace: 'prod', name: 'db', revision: 1 }, expect.any(Object))
469
+ })
470
+
471
+ it('Older Radar without resourceActions uses legacy paths cleanly (including editable CronJob trigger)', async () => {
472
+ seedLegacy()
473
+ const legacyRestart = vi.fn()
474
+ const legacyPause = vi.fn()
475
+ stubFetch(() => Response.json({}))
476
+
477
+ await render(
478
+ <>
479
+ <ActionsBarHarness
480
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'web' }}
481
+ data={DEPLOYMENT_DATA}
482
+ onRestart={legacyRestart}
483
+ onPauseDeployment={legacyPause}
484
+ onResumeDeployment={vi.fn()}
485
+ />
486
+ <ActionsBarHarness
487
+ resource={{ kind: 'cronjobs', group: 'batch', namespace: 'prod', name: 'nightly' }}
488
+ data={CRONJOB_DATA}
489
+ onTriggerCronJob={vi.fn()}
490
+ cronJobTriggerDialog
491
+ />
492
+ </>,
493
+ )
494
+ await act(async () => buttonByText('Restart')!.click())
495
+ await act(async () => buttonByText('Pause rollout')!.click())
496
+ await act(async () => buttonByText('Trigger')!.click())
497
+ expect(document.querySelector('input[aria-label="Job name"]')).not.toBeNull()
498
+ expect(legacyRestart).toHaveBeenCalledOnce()
499
+ expect(legacyPause).toHaveBeenCalledOnce()
500
+ expect(calls).toHaveLength(0)
501
+ })
502
+
503
+ it('BulkReviewedActionDialog verifies selected UIDs, pins connection, executes in one confirmation, and locks after ambiguity', async () => {
504
+ seedD4()
505
+ const onCompleted = vi.fn()
506
+ let failSecondWithUnknown = false
507
+ stubFetch(({ url, body }) => {
508
+ const name = (body?.target as { name?: string })?.name ?? 'unknown'
509
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
510
+ return Response.json(
511
+ makePreview('apps/Deployment/scale', {
512
+ target: { namespace: 'prod', name, uid: `uid-${name}`, apiVersion: 'apps/v1' },
513
+ summary: `Scale ${name} to 4`,
514
+ changes: [{
515
+ object: { apiVersion: 'apps/v1', kind: 'Deployment', namespace: 'prod', name, uid: `uid-${name}` },
516
+ changeType: 'update',
517
+ deltas: [{ path: '/spec/replicas', before: 2, after: 4 }],
518
+ }],
519
+ }),
520
+ )
521
+ }
522
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
523
+ if (failSecondWithUnknown && name === 'worker') {
524
+ return Response.json({ code: 'dispatch_unknown', message: 'stream dropped', retry: 'none', dispatch: 'unknown' }, { status: 503 })
525
+ }
526
+ return Response.json({ executionId: body?.executionId, outcome: 'applied' })
527
+ }
528
+ return Response.json({})
529
+ })
530
+
531
+ const frozenItems = [
532
+ { kind: 'deployments', group: 'apps', namespace: 'prod', name: 'api', uid: 'uid-api' },
533
+ { kind: 'deployments', group: 'apps', namespace: 'prod', name: 'worker', uid: 'uid-worker' },
534
+ ]
535
+ const bulkProps = {
536
+ open: true,
537
+ mode: 'scale' as const,
538
+ kindLabel: 'Deployment',
539
+ actionId: 'apps/Deployment/scale' as const,
540
+ items: frozenItems,
541
+ connectionId: 'conn-1',
542
+ initialReplicas: 4,
543
+ commonCurrentReplicas: 2,
544
+ onClose: () => {},
545
+ onCompleted,
546
+ }
547
+
548
+ await render(<BulkHarness {...bulkProps} />)
549
+ await vi.waitFor(() => {
550
+ expect(document.body.textContent).toContain('prod/api')
551
+ expect(document.body.textContent).toContain('prod/worker')
552
+ expect(buttonByText('Scale to 4')!.disabled).toBe(false)
553
+ })
554
+
555
+ observeConnectionStatus({ connectionId: 'conn-2' })
556
+ await act(async () => buttonByText('Scale to 4')!.click())
557
+ await vi.waitFor(() => expect(onCompleted).toHaveBeenCalledOnce())
558
+ const execCalls = calls.filter((c) => c.url.endsWith('/apps/Deployment/scale/execute'))
559
+ expect(execCalls).toHaveLength(2)
560
+ expect(execCalls.every((c) => c.connectionId === 'conn-1')).toBe(true)
561
+
562
+ failSecondWithUnknown = true
563
+ await render(<BulkHarness {...bulkProps} />)
564
+ await vi.waitFor(() => expect(buttonByText('Scale to 4')!.disabled).toBe(false))
565
+ await act(async () => buttonByText('Scale to 4')!.click())
566
+ await vi.waitFor(() => {
567
+ expect(document.body.textContent).toContain('Radar could not tell whether every change took effect')
568
+ expect(buttonByText('Scale to 4')!.disabled).toBe(true)
569
+ })
570
+ })
571
+
572
+ it('Scale and low-risk Pause require explicit reapproval on preview_mismatch even when refreshed preview is unchanged', async () => {
573
+ seedD4()
574
+ let previewCount = 0
575
+ let executeCount = 0
576
+
577
+ stubFetch(({ url, body }) => {
578
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
579
+ previewCount += 1
580
+ return Response.json(
581
+ makePreview('apps/Deployment/scale', {
582
+ summary: 'Scale Deployment prod/web from 2 to 3 replicas.',
583
+ fromPreview: {
584
+ digest: 'v1:sha256:stable-digest',
585
+ actionVersion: 1,
586
+ apiVersion: 'apps/v1',
587
+ preconditions: [{ uid: 'uid-1', resourceVersion: String(10 + previewCount) }],
588
+ },
589
+ }),
590
+ )
591
+ }
592
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
593
+ executeCount += 1
594
+ if (executeCount === 1) {
595
+ return Response.json(
596
+ { code: 'preview_mismatch', message: 'Deployment changed before execution.', retry: 'reapprove', dispatch: 'not_dispatched' },
597
+ { status: 409 },
598
+ )
599
+ }
600
+ return Response.json({ executionId: body?.executionId, outcome: 'applied' })
601
+ }
602
+ return Response.json({})
603
+ })
604
+
605
+ await render(<WorkloadHarness kind="deployments" data={DEPLOYMENT_DATA} />)
606
+ await act(async () => buttonByText('Scale')!.click())
607
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
608
+ await vi.waitFor(() => expect(buttonByText('Apply')!.disabled).toBe(false))
609
+
610
+ // First click sends one execute -> preview_mismatch -> refreshes preview -> must stay open for explicit confirmation.
611
+ await act(async () => buttonByText('Apply')!.click())
612
+ await vi.waitFor(() => {
613
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
614
+ expect(document.body.textContent).toContain('Deployment changed before execution.')
615
+ expect(buttonByText('Apply')!.disabled).toBe(false)
616
+ })
617
+ expect(previewCount).toBe(2)
618
+ expect(executeCount).toBe(1)
619
+
620
+ // Second explicit click executes once with the refreshed preview and closes the dialog.
621
+ await act(async () => buttonByText('Apply')!.click())
622
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
623
+ expect(executeCount).toBe(2)
624
+
625
+ // Low-risk auto-execute-if-clean flow also opens for explicit confirmation on preview_mismatch with an unchanged clean preview.
626
+ previewCount = 0
627
+ executeCount = 0
628
+ stubFetch(({ url, body }) => {
629
+ if (url.endsWith('/apps/Deployment/pause/preview')) {
630
+ previewCount += 1
631
+ return Response.json(
632
+ makePreview('apps/Deployment/pause', {
633
+ summary: 'Pause rollout for Deployment prod/web.',
634
+ fromPreview: {
635
+ digest: 'v1:sha256:pause-stable-digest',
636
+ actionVersion: 1,
637
+ apiVersion: 'apps/v1',
638
+ preconditions: [{ uid: 'uid-1', resourceVersion: String(20 + previewCount) }],
639
+ },
640
+ }),
641
+ )
642
+ }
643
+ if (url.endsWith('/apps/Deployment/pause/execute')) {
644
+ executeCount += 1
645
+ if (executeCount === 1) {
646
+ return Response.json(
647
+ { code: 'preview_mismatch', message: 'Deployment changed before pause.', retry: 'reapprove', dispatch: 'not_dispatched' },
648
+ { status: 409 },
649
+ )
650
+ }
651
+ return Response.json({ executionId: body?.executionId, outcome: 'applied' })
652
+ }
653
+ return Response.json({})
654
+ })
655
+
656
+ await render(
657
+ <ActionsBarHarness
658
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'web' }}
659
+ data={DEPLOYMENT_DATA}
660
+ onPauseDeployment={vi.fn()}
661
+ onResumeDeployment={vi.fn()}
662
+ />,
663
+ )
664
+ await act(async () => buttonByText('Pause rollout')!.click())
665
+ await vi.waitFor(() => {
666
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
667
+ expect(document.body.textContent).toContain('Deployment changed before pause.')
668
+ expect(buttonByText('Pause rollout')!.disabled).toBe(false)
669
+ })
670
+ expect(previewCount).toBe(2)
671
+ expect(executeCount).toBe(1)
672
+
673
+ await act(async () => buttonByText('Pause rollout')!.click())
674
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
675
+ expect(executeCount).toBe(2)
676
+ })
677
+
678
+ it('Deployment pause/resume and CronJob suspend/resume run D4 low-risk flow and controls wait cleanly while capabilities load', async () => {
679
+ seedD4()
680
+ const legacyPause = vi.fn()
681
+ const legacySuspend = vi.fn()
682
+ stubFetch(({ url, body }) => {
683
+ if (url.endsWith('/preview')) {
684
+ const actionId = url.split('/resource-actions/')[1].replace('/preview', '')
685
+ return Response.json(
686
+ makePreview(actionId, {
687
+ target: actionId.startsWith('batch/CronJob/')
688
+ ? { namespace: 'prod', name: 'nightly', uid: 'cj-1', apiVersion: 'batch/v1' }
689
+ : { namespace: 'prod', name: 'web', uid: 'uid-1', apiVersion: 'apps/v1' },
690
+ }),
691
+ )
692
+ }
693
+ if (url.endsWith('/execute')) return Response.json({ executionId: body?.executionId, outcome: 'applied' })
694
+ return Response.json({})
695
+ })
696
+
697
+ await render(
698
+ <ActionsBarHarness
699
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'web' }}
700
+ data={DEPLOYMENT_DATA}
701
+ onPauseDeployment={legacyPause}
702
+ onResumeDeployment={vi.fn()}
703
+ />,
704
+ )
705
+ await act(async () => buttonByText('Pause rollout')!.click())
706
+ await vi.waitFor(() => {
707
+ expect(calls.map((c) => c.url)).toEqual([
708
+ '/api/resource-actions/apps/Deployment/pause/preview',
709
+ '/api/resource-actions/apps/Deployment/pause/execute',
710
+ ])
711
+ })
712
+ expect(legacyPause).not.toHaveBeenCalled()
713
+
714
+ calls.length = 0
715
+ await render(
716
+ <ActionsBarHarness
717
+ resource={{ kind: 'cronjobs', group: 'batch', namespace: 'prod', name: 'nightly' }}
718
+ data={CRONJOB_DATA}
719
+ onSuspendCronJob={legacySuspend}
720
+ onResumeCronJob={vi.fn()}
721
+ />,
722
+ )
723
+ await act(async () => buttonByText('Suspend')!.click())
724
+ await vi.waitFor(() => {
725
+ expect(calls.map((c) => c.url)).toEqual([
726
+ '/api/resource-actions/batch/CronJob/suspend/preview',
727
+ '/api/resource-actions/batch/CronJob/suspend/execute',
728
+ ])
729
+ })
730
+ expect(legacySuspend).not.toHaveBeenCalled()
731
+
732
+ // Unknown capabilities (still loading): controls stay disabled with reason, no dead-end dialog, no legacy write
733
+ client.removeQueries({ queryKey: ['capabilities'] })
734
+ let resolveCaps!: (res: Response) => void
735
+ stubFetch(({ url, body }) => {
736
+ if (url.endsWith('/capabilities')) {
737
+ return new Promise<Response>((resolve) => { resolveCaps = resolve })
738
+ }
739
+ if (url.endsWith('/apps/Deployment/restart/preview')) return Response.json(makePreview('apps/Deployment/restart'))
740
+ if (url.endsWith('/apps/Deployment/restart/execute')) return Response.json({ executionId: body?.executionId, outcome: 'applied' })
741
+ return Response.json({})
742
+ })
743
+ const legacyRestart = vi.fn()
744
+ await render(
745
+ <>
746
+ <ActionsBarHarness
747
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'web' }}
748
+ data={DEPLOYMENT_DATA}
749
+ onRestart={legacyRestart}
750
+ />
751
+ <WorkloadHarness kind="deployments" data={DEPLOYMENT_DATA} onScale={vi.fn(async () => {})} />
752
+ </>,
753
+ )
754
+ expect(buttonByText('Restart')!.disabled).toBe(true)
755
+ expect(buttonByText('Scale')!.disabled).toBe(true)
756
+ expect(document.body.textContent).toContain("Checking this cluster's Radar")
757
+ await act(async () => buttonByText('Restart')!.click())
758
+ expect(legacyRestart).not.toHaveBeenCalled()
759
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0)
760
+
761
+ // Resolving to new Radar enables D4 preview dialog without reopening or refreshing
762
+ await act(async () => {
763
+ resolveCaps(
764
+ Response.json({
765
+ features: { resourceActions: true, deploymentPause: true, workloadRestartPreconditions: true, cronJobTriggerJobName: true },
766
+ reviewedActions: { contractVersion: 1, actions: Object.values(RESOURCE_ACTION_IDS) },
767
+ }),
768
+ )
769
+ })
770
+ await vi.waitFor(() => {
771
+ expect(buttonByText('Restart')!.disabled).toBe(false)
772
+ expect(buttonByText('Scale')!.disabled).toBe(false)
773
+ })
774
+ await act(async () => buttonByText('Restart')!.click())
775
+ await vi.waitFor(() => {
776
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
777
+ expect(document.body.textContent).toContain('Preview for apps/Deployment/restart')
778
+ })
779
+ await act(async () => buttonByText('Cancel')!.click())
780
+
781
+ // Loading -> older Radar resolves to legacy immediate route cleanly
782
+ await act(async () => {
783
+ void client.resetQueries({ queryKey: ['capabilities'] })
784
+ })
785
+ await vi.waitFor(() => expect(buttonByText('Restart')!.disabled).toBe(true))
786
+ await act(async () => {
787
+ resolveCaps(
788
+ Response.json({
789
+ features: { deploymentPause: true, workloadRestartPreconditions: true, cronJobTriggerJobName: true },
790
+ }),
791
+ )
792
+ })
793
+ await vi.waitFor(() => expect(buttonByText('Restart')!.disabled).toBe(false))
794
+ await act(async () => buttonByText('Restart')!.click())
795
+ expect(legacyRestart).toHaveBeenCalledOnce()
796
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0)
797
+ })
798
+
799
+ it('D4 Restart opens dialog and surfaces positive controller facts and incomplete-fact notes', async () => {
800
+ seedD4()
801
+ stubFetch(({ url, body }) => {
802
+ if (url.endsWith('/apps/Deployment/restart/preview')) {
803
+ return Response.json(
804
+ makePreview('apps/Deployment/restart', {
805
+ summary: 'Restart Deployment prod/web.',
806
+ warnings: [],
807
+ facts: {
808
+ gitops: {
809
+ state: 'known',
810
+ value: {
811
+ controllers: [{ group: 'argoproj.io', kind: 'Application', namespace: 'argocd', name: 'web-app', auto: true }],
812
+ },
813
+ },
814
+ autoscaler: {
815
+ state: 'incomplete',
816
+ reason: 'user_forbidden',
817
+ },
818
+ },
819
+ }),
820
+ )
821
+ }
822
+ if (url.endsWith('/apps/Deployment/restart/execute')) {
823
+ return Response.json({ executionId: body?.executionId, outcome: 'applied' })
824
+ }
825
+ return Response.json({})
826
+ })
827
+
828
+ await render(
829
+ <ActionsBarHarness
830
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'web' }}
831
+ data={DEPLOYMENT_DATA}
832
+ onRestart={vi.fn()}
833
+ />,
834
+ )
835
+ await act(async () => buttonByText('Restart')!.click())
836
+ await vi.waitFor(() => {
837
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
838
+ expect(document.body.textContent).toContain('Managed by Argo CD Application argocd/web-app (auto-sync on)')
839
+ expect(document.body.textContent).toContain('Could not check autoscaler ownership (you may not list it).')
840
+ })
841
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(0)
842
+ })
843
+
844
+ it('Prevents duplicate rapid confirm clicks from surfacing a conflict error while one execute is pending', async () => {
845
+ seedD4()
846
+ let resolveExecute!: (response: Response) => void
847
+ let sentExecutionId: unknown
848
+ stubFetch(({ url, body }) => {
849
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
850
+ return Response.json(makePreview('apps/Deployment/scale'))
851
+ }
852
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
853
+ sentExecutionId = body?.executionId
854
+ return new Promise<Response>((resolve) => {
855
+ resolveExecute = resolve
856
+ })
857
+ }
858
+ return Response.json({})
859
+ })
860
+
861
+ await render(<WorkloadHarness kind="deployments" data={DEPLOYMENT_DATA} />)
862
+ await act(async () => buttonByText('Scale')!.click())
863
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
864
+ await vi.waitFor(() => expect(buttonByText('Apply')!.disabled).toBe(false))
865
+
866
+ // Dispatch two clicks in the same turn before React renders isExecuting: true.
867
+ const applyBtn = buttonByText('Apply')!
868
+ await act(async () => {
869
+ applyBtn.click()
870
+ applyBtn.click()
871
+ })
872
+
873
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1)
874
+ expect(document.body.textContent).not.toContain('still in progress')
875
+
876
+ await act(async () => {
877
+ resolveExecute(Response.json({ executionId: sentExecutionId, outcome: 'applied' }))
878
+ })
879
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
880
+ })
881
+
882
+ it('Locks Confirm with recovery guidance when execute returns an unparseable 200 or mismatched executionId', async () => {
883
+ seedD4()
884
+ stubFetch(({ url }) => {
885
+ if (url.endsWith('/apps/Deployment/scale/preview')) return Response.json(makePreview('apps/Deployment/scale'))
886
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
887
+ return Response.json({ executionId: 'wrong-exec-id', outcome: 'applied' })
888
+ }
889
+ return Response.json({})
890
+ })
891
+
892
+ await render(<WorkloadHarness kind="deployments" data={DEPLOYMENT_DATA} />)
893
+ await act(async () => buttonByText('Scale')!.click())
894
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
895
+ await vi.waitFor(() => expect(buttonByText('Apply')!.disabled).toBe(false))
896
+
897
+ await act(async () => buttonByText('Apply')!.click())
898
+ await vi.waitFor(() => {
899
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
900
+ expect(document.body.textContent).toContain('Radar could not tell whether this took effect')
901
+ expect(document.body.textContent).toContain('Inspect the current state in Kubernetes first, then reload this page and review the action again.')
902
+ expect(buttonByText('Apply')!.disabled).toBe(true)
903
+ })
904
+
905
+ // Closing and reopening must keep the outcome lock and recovery guidance active, without "Preview failed".
906
+ await act(async () => buttonByText('Cancel')!.click())
907
+ await act(async () => buttonByText('Scale')!.click())
908
+ expect(document.body.textContent).toContain('Radar could not tell whether this took effect')
909
+ expect(document.body.textContent).toContain('Inspect the current state in Kubernetes first, then reload this page and review the action again.')
910
+ expect(document.body.textContent).not.toContain('Preview failed')
911
+ expect(buttonByText('Apply')!.disabled).toBe(true)
912
+ })
913
+
914
+ it('Clears executable preview and disables Confirm when target is replaced during execute (single and bulk)', async () => {
915
+ seedD4()
916
+ let previewCalls = 0
917
+ stubFetch(({ url }) => {
918
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
919
+ previewCalls += 1
920
+ return Response.json(
921
+ makePreview('apps/Deployment/scale', {
922
+ target: { namespace: 'prod', name: 'web', uid: previewCalls === 1 ? 'uid-1' : 'uid-replaced', apiVersion: 'apps/v1' },
923
+ }),
924
+ )
925
+ }
926
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
927
+ return Response.json(
928
+ { code: 'preview_mismatch', message: 'target changed', retry: 'reapprove', dispatch: 'not_dispatched' },
929
+ { status: 409 },
930
+ )
931
+ }
932
+ return Response.json({})
933
+ })
934
+
935
+ await render(<WorkloadHarness kind="deployments" data={DEPLOYMENT_DATA} />)
936
+ await act(async () => buttonByText('Scale')!.click())
937
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
938
+ await vi.waitFor(() => expect(buttonByText('Apply')!.disabled).toBe(false))
939
+
940
+ await act(async () => buttonByText('Apply')!.click())
941
+ await vi.waitFor(() => {
942
+ expect(document.body.textContent).toContain('Target changed')
943
+ expect(document.body.textContent).toContain('Close and reselect')
944
+ expect(buttonByText('Apply')!.disabled).toBe(true)
945
+ })
946
+
947
+ // Bulk: replacement UID during execute clears preview so bulk cannot apply to replacement
948
+ calls.length = 0
949
+ let bulkPreviewCount = 0
950
+ stubFetch(({ url, body }) => {
951
+ const name = (body?.target as { name?: string })?.name ?? 'unknown'
952
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
953
+ bulkPreviewCount += 1
954
+ const uid = name === 'worker' && bulkPreviewCount > 2 ? 'uid-worker-new' : `uid-${name}`
955
+ return Response.json(
956
+ makePreview('apps/Deployment/scale', {
957
+ target: { namespace: 'prod', name, uid, apiVersion: 'apps/v1' },
958
+ }),
959
+ )
960
+ }
961
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
962
+ if (name === 'worker') {
963
+ return Response.json(
964
+ { code: 'preview_mismatch', message: 'target changed', retry: 'reapprove', dispatch: 'not_dispatched' },
965
+ { status: 409 },
966
+ )
967
+ }
968
+ return Response.json({ executionId: body?.executionId, outcome: 'applied' })
969
+ }
970
+ return Response.json({})
971
+ })
972
+
973
+ await render(
974
+ <BulkHarness
975
+ open
976
+ mode="scale"
977
+ kindLabel="Deployment"
978
+ actionId="apps/Deployment/scale"
979
+ items={[
980
+ { kind: 'deployments', group: 'apps', namespace: 'prod', name: 'api', uid: 'uid-api' },
981
+ { kind: 'deployments', group: 'apps', namespace: 'prod', name: 'worker', uid: 'uid-worker' },
982
+ ]}
983
+ connectionId="conn-1"
984
+ initialReplicas={4}
985
+ commonCurrentReplicas={2}
986
+ onClose={() => {}}
987
+ onCompleted={() => {}}
988
+ />,
989
+ )
990
+ await vi.waitFor(() => expect(buttonByText('Scale to 4')!.disabled).toBe(false))
991
+ await act(async () => buttonByText('Scale to 4')!.click())
992
+ await vi.waitFor(() => {
993
+ expect(document.body.textContent).toContain('Close and reselect')
994
+ expect(buttonByText('Scale to 4')!.disabled).toBe(true)
995
+ })
996
+ })
997
+
998
+ it('Debounces rapid replica changes in BulkReviewedActionDialog while disabling Confirm until previews finish', async () => {
999
+ vi.useFakeTimers()
1000
+ try {
1001
+ seedD4()
1002
+ stubFetch(({ url, body }) => {
1003
+ const name = (body?.target as { name?: string })?.name ?? 'unknown'
1004
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
1005
+ return Response.json(
1006
+ makePreview('apps/Deployment/scale', {
1007
+ target: { namespace: 'prod', name, uid: `uid-${name}`, apiVersion: 'apps/v1' },
1008
+ }),
1009
+ )
1010
+ }
1011
+ return Response.json({})
1012
+ })
1013
+
1014
+ await render(
1015
+ <BulkHarness
1016
+ open
1017
+ mode="scale"
1018
+ kindLabel="Deployment"
1019
+ actionId="apps/Deployment/scale"
1020
+ items={[
1021
+ { kind: 'deployments', group: 'apps', namespace: 'prod', name: 'api', uid: 'uid-api' },
1022
+ { kind: 'deployments', group: 'apps', namespace: 'prod', name: 'worker', uid: 'uid-worker' },
1023
+ ]}
1024
+ connectionId="conn-1"
1025
+ initialReplicas={2}
1026
+ commonCurrentReplicas={2}
1027
+ onClose={() => {}}
1028
+ onCompleted={() => {}}
1029
+ />,
1030
+ )
1031
+ await act(async () => { await Promise.resolve() })
1032
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(2)
1033
+
1034
+ // Rapidly step replicas 2 -> 3 -> 4 -> 5 without waiting for debounce
1035
+ const incBtn = document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!
1036
+ await act(async () => { incBtn.click() })
1037
+ await act(async () => { incBtn.click() })
1038
+ await act(async () => { incBtn.click() })
1039
+
1040
+ // Still debouncing: no extra preview calls yet and Confirm stays disabled
1041
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(2)
1042
+ expect(buttonByText('Scale to 5')!.disabled).toBe(true)
1043
+
1044
+ await act(async () => { vi.advanceTimersByTime(260) })
1045
+ await act(async () => { await Promise.resolve() })
1046
+
1047
+ const previews = calls.filter((c) => c.url.endsWith('/preview'))
1048
+ expect(previews).toHaveLength(4)
1049
+ expect(previews.slice(2).every((c) => (c.body?.parameters as { replicas?: number })?.replicas === 5)).toBe(true)
1050
+ expect(buttonByText('Scale to 5')!.disabled).toBe(false)
1051
+ } finally {
1052
+ vi.useRealTimers()
1053
+ }
1054
+ })
1055
+
1056
+ it('Does not auto-execute a pending preview after the selected target changes or unmounts', async () => {
1057
+ let resolveFirstPreview!: (preview: ResourceActionPreviewResponse) => void
1058
+ const execute = vi.fn<ResourceActionClientAdapter['execute']>()
1059
+ const preview = vi.fn<ResourceActionClientAdapter['preview']>(
1060
+ () => new Promise<ResourceActionPreviewResponse>((resolve) => { resolveFirstPreview = resolve }),
1061
+ )
1062
+ const adapter: ResourceActionClientAdapter = {
1063
+ context: 'eks-staging',
1064
+ getConnectionId: () => 'conn-1',
1065
+ support: 'supported',
1066
+ supportsAction: () => true,
1067
+ getOutcomeError: () => null,
1068
+ preview,
1069
+ execute,
1070
+ }
1071
+
1072
+ const otherDeployment = {
1073
+ apiVersion: 'apps/v1',
1074
+ kind: 'Deployment',
1075
+ metadata: { name: 'api', namespace: 'prod', uid: 'uid-2' },
1076
+ spec: { replicas: 2, paused: false },
1077
+ status: { readyReplicas: 2 },
1078
+ }
1079
+
1080
+ await render(
1081
+ <ResourceActionsBar
1082
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'web' }}
1083
+ data={DEPLOYMENT_DATA}
1084
+ onPauseDeployment={vi.fn()}
1085
+ onResumeDeployment={vi.fn()}
1086
+ resourceActionAdapter={adapter}
1087
+ />,
1088
+ )
1089
+
1090
+ await act(async () => buttonByText('Pause rollout')!.click())
1091
+ expect(preview).toHaveBeenCalledTimes(1)
1092
+
1093
+ // Commit the new target synchronously (before passive useEffect invalidates seqRef),
1094
+ // then resolve the previous target's pending preview in the same turn.
1095
+ await act(async () => {
1096
+ flushSync(() => {
1097
+ root.render(
1098
+ <QueryClientProvider client={client}>
1099
+ <ResourceActionsBar
1100
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'api' }}
1101
+ data={otherDeployment}
1102
+ onPauseDeployment={vi.fn()}
1103
+ onResumeDeployment={vi.fn()}
1104
+ resourceActionAdapter={adapter}
1105
+ />
1106
+ </QueryClientProvider>,
1107
+ )
1108
+ })
1109
+ resolveFirstPreview(
1110
+ makePreview('apps/Deployment/pause', {
1111
+ target: { namespace: 'prod', name: 'web', uid: 'uid-1', apiVersion: 'apps/v1' },
1112
+ }),
1113
+ )
1114
+ await Promise.resolve()
1115
+ })
1116
+
1117
+ expect(execute).not.toHaveBeenCalled()
1118
+
1119
+ // Unmounting while a clean auto-execute preview is pending also blocks execution.
1120
+ await act(async () => buttonByText('Pause rollout')!.click())
1121
+ expect(preview).toHaveBeenCalledTimes(2)
1122
+ await act(async () => {
1123
+ flushSync(() => {
1124
+ root.render(<QueryClientProvider client={client}><div /></QueryClientProvider>)
1125
+ })
1126
+ resolveFirstPreview(
1127
+ makePreview('apps/Deployment/pause', {
1128
+ target: { namespace: 'prod', name: 'api', uid: 'uid-2', apiVersion: 'apps/v1' },
1129
+ }),
1130
+ )
1131
+ await Promise.resolve()
1132
+ })
1133
+ expect(execute).not.toHaveBeenCalled()
1134
+ })
1135
+
1136
+ it('Clears bulk loading state when preview dependencies change during execution', async () => {
1137
+ let resolveExecute!: (result: Awaited<ReturnType<ResourceActionClientAdapter['execute']>>) => void
1138
+ const onClose = vi.fn()
1139
+ const makeAdapter = (previewFn: ResourceActionClientAdapter['preview']): ResourceActionClientAdapter => ({
1140
+ context: 'eks-staging',
1141
+ getConnectionId: () => 'conn-1',
1142
+ support: 'supported',
1143
+ supportsAction: () => true,
1144
+ getOutcomeError: () => null,
1145
+ preview: previewFn,
1146
+ execute: () => new Promise((resolve) => { resolveExecute = resolve }),
1147
+ })
1148
+
1149
+ const preview1: ResourceActionClientAdapter['preview'] = async ({ actionId, target }) =>
1150
+ makePreview(actionId, { target: { namespace: target.namespace, name: target.name, uid: 'uid-api', apiVersion: 'apps/v1' } })
1151
+ const preview2: ResourceActionClientAdapter['preview'] = async ({ actionId, target }) =>
1152
+ makePreview(actionId, { target: { namespace: target.namespace, name: target.name, uid: 'uid-api', apiVersion: 'apps/v1' } })
1153
+
1154
+ const items = [{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'api', uid: 'uid-api' }]
1155
+ await render(
1156
+ <BulkReviewedActionDialog
1157
+ open
1158
+ mode="restart"
1159
+ kindLabel="Deployment"
1160
+ actionId="apps/Deployment/restart"
1161
+ items={items}
1162
+ connectionId="conn-1"
1163
+ adapter={makeAdapter(preview1)}
1164
+ onClose={onClose}
1165
+ onCompleted={() => {}}
1166
+ />,
1167
+ )
1168
+ await vi.waitFor(() => expect(buttonByText('Restart 1 workload')!.disabled).toBe(false))
1169
+
1170
+ await act(async () => buttonByText('Restart 1 workload')!.click())
1171
+ expect(buttonByText('Restarting...')!.disabled).toBe(true)
1172
+ expect(buttonByText('Cancel')!.disabled).toBe(true)
1173
+
1174
+ // Trigger a preview-effect re-run mid-execution (bumping seqRef).
1175
+ await render(
1176
+ <BulkReviewedActionDialog
1177
+ open
1178
+ mode="restart"
1179
+ kindLabel="Deployment"
1180
+ actionId="apps/Deployment/restart"
1181
+ items={items}
1182
+ connectionId="conn-1"
1183
+ adapter={makeAdapter(preview2)}
1184
+ onClose={onClose}
1185
+ onCompleted={() => {}}
1186
+ />,
1187
+ )
1188
+
1189
+ await act(async () => {
1190
+ resolveExecute({ status: 'completed', response: { executionId: 'exec-1', outcome: 'applied' } })
1191
+ })
1192
+
1193
+ await vi.waitFor(() => {
1194
+ expect(buttonByText('Cancel')!.disabled).toBe(false)
1195
+ expect(buttonByText('Restart 1 workload')!.disabled).toBe(true)
1196
+ })
1197
+ await act(async () => buttonByText('Cancel')!.click())
1198
+ expect(onClose).toHaveBeenCalledOnce()
1199
+ })
1200
+
1201
+ it('Previews both workloads when the desired count changes after a partial scale failure', async () => {
1202
+ vi.useFakeTimers()
1203
+ try {
1204
+ seedD4()
1205
+ const onCompleted = vi.fn()
1206
+ stubFetch(({ url, body }) => {
1207
+ const name = (body?.target as { name?: string })?.name ?? 'unknown'
1208
+ const replicas = (body?.parameters as { replicas?: number })?.replicas ?? 4
1209
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
1210
+ return Response.json(
1211
+ makePreview('apps/Deployment/scale', {
1212
+ target: { namespace: 'prod', name, uid: `uid-${name}`, apiVersion: 'apps/v1' },
1213
+ summary: `Scale ${name} to ${replicas}`,
1214
+ changes: [{
1215
+ object: { apiVersion: 'apps/v1', kind: 'Deployment', namespace: 'prod', name, uid: `uid-${name}` },
1216
+ changeType: 'update',
1217
+ deltas: [{ path: '/spec/replicas', before: 2, after: replicas }],
1218
+ }],
1219
+ }),
1220
+ )
1221
+ }
1222
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
1223
+ if (name === 'worker' && replicas === 4) {
1224
+ return Response.json(
1225
+ { code: 'action_not_applicable', message: 'quota exceeded at 4 replicas', retry: 'none', dispatch: 'not_dispatched' },
1226
+ { status: 422 },
1227
+ )
1228
+ }
1229
+ return Response.json({ executionId: body?.executionId, outcome: 'applied' })
1230
+ }
1231
+ return Response.json({})
1232
+ })
1233
+
1234
+ await render(
1235
+ <BulkHarness
1236
+ open
1237
+ mode="scale"
1238
+ kindLabel="Deployment"
1239
+ actionId="apps/Deployment/scale"
1240
+ items={[
1241
+ { kind: 'deployments', group: 'apps', namespace: 'prod', name: 'api', uid: 'uid-api' },
1242
+ { kind: 'deployments', group: 'apps', namespace: 'prod', name: 'worker', uid: 'uid-worker' },
1243
+ ]}
1244
+ connectionId="conn-1"
1245
+ initialReplicas={4}
1246
+ commonCurrentReplicas={2}
1247
+ onClose={() => {}}
1248
+ onCompleted={onCompleted}
1249
+ />,
1250
+ )
1251
+ await act(async () => { await Promise.resolve() })
1252
+ expect(buttonByText('Scale to 4')!.disabled).toBe(false)
1253
+
1254
+ await act(async () => { buttonByText('Scale to 4')!.click() })
1255
+ await act(async () => { await Promise.resolve() })
1256
+ expect(document.body.textContent).toContain('Done')
1257
+ expect(document.body.textContent).toContain('quota exceeded at 4 replicas')
1258
+ expect(onCompleted).not.toHaveBeenCalled()
1259
+
1260
+ // Set a new desired count for the whole selection.
1261
+ const decBtn = document.querySelector<HTMLButtonElement>('button[aria-label="Decrease replicas"]')!
1262
+ await act(async () => { decBtn.click() })
1263
+ await act(async () => { vi.advanceTimersByTime(260) })
1264
+ await act(async () => { await Promise.resolve() })
1265
+
1266
+ // Both workloads are eligible for the new count, including the one scaled to 4.
1267
+ const previewsAt3 = calls.filter(
1268
+ (c) => c.url.endsWith('/preview') && (c.body?.parameters as { replicas?: number })?.replicas === 3,
1269
+ )
1270
+ expect(previewsAt3.map((c) => (c.body?.target as { name?: string })?.name)).toEqual(['api', 'worker'])
1271
+ expect(document.body.textContent).not.toContain('Done')
1272
+ expect(buttonByText('Scale to 3')!.disabled).toBe(false)
1273
+
1274
+ await act(async () => { buttonByText('Scale to 3')!.click() })
1275
+ await act(async () => { await Promise.resolve() })
1276
+
1277
+ const execsAt3 = calls.filter(
1278
+ (c) => c.url.endsWith('/execute') && (c.body?.parameters as { replicas?: number })?.replicas === 3,
1279
+ )
1280
+ expect(execsAt3.map((c) => (c.body?.target as { name?: string })?.name)).toEqual(['api', 'worker'])
1281
+ expect(onCompleted).toHaveBeenCalledOnce()
1282
+ } finally {
1283
+ vi.useRealTimers()
1284
+ }
1285
+ })
1286
+
1287
+ it('Surfaces 409 connection_changed reload/reconnect guidance in single and low-risk dialogs without automatic preview or execute', async () => {
1288
+ seedD4()
1289
+ const reloadMessage = 'the active cluster connection changed since this view loaded; reload the page and try again'
1290
+
1291
+ stubFetch(({ url }) => {
1292
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
1293
+ return Response.json(makePreview('apps/Deployment/scale'))
1294
+ }
1295
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
1296
+ return Response.json(
1297
+ { code: 'connection_changed', message: reloadMessage, retry: 'none', dispatch: 'not_dispatched' },
1298
+ { status: 409 },
1299
+ )
1300
+ }
1301
+ if (url.endsWith('/apps/Deployment/pause/preview') || url.endsWith('/apps/Deployment/restart/preview')) {
1302
+ return Response.json(
1303
+ { code: 'connection_changed', message: reloadMessage, retry: 'none', dispatch: 'not_dispatched' },
1304
+ { status: 409 },
1305
+ )
1306
+ }
1307
+ return Response.json({})
1308
+ })
1309
+
1310
+ // 1. Scale execute directly returns 409 connection_changed -> shows reload/reconnect guidance, disables Confirm, zero automatic re-preview.
1311
+ await render(<WorkloadHarness kind="deployments" data={DEPLOYMENT_DATA} />)
1312
+ await act(async () => buttonByText('Scale')!.click())
1313
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
1314
+ await vi.waitFor(() => expect(buttonByText('Apply')!.disabled).toBe(false))
1315
+
1316
+ observeConnectionStatus({ connectionId: 'conn-2' })
1317
+ await act(async () => buttonByText('Apply')!.click())
1318
+
1319
+ await vi.waitFor(() => {
1320
+ expect(document.body.textContent).toContain('Cluster connection changed')
1321
+ expect(document.body.textContent).toContain(reloadMessage)
1322
+ expect(document.body.textContent).toContain('Reload required')
1323
+ expect(buttonByText('Apply')!.disabled).toBe(true)
1324
+ })
1325
+ expect(document.body.textContent).not.toContain('Radar could not tell whether this took effect')
1326
+ expect(calls.map((c) => c.url)).toEqual([
1327
+ '/api/resource-actions/apps/Deployment/scale/preview',
1328
+ '/api/resource-actions/apps/Deployment/scale/execute',
1329
+ ])
1330
+ expect(calls.every((c) => c.connectionId === 'conn-1')).toBe(true)
1331
+
1332
+ // Stepping replicas after connection_changed must not fire any preview requests.
1333
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
1334
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Decrease replicas"]')!.click())
1335
+ expect(calls).toHaveLength(2)
1336
+
1337
+ // 2. Low-risk Pause preview returns 409 connection_changed -> opens dialog with reload/reconnect guidance and zero execute calls.
1338
+ calls.length = 0
1339
+ await render(
1340
+ <ActionsBarHarness
1341
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'web' }}
1342
+ data={DEPLOYMENT_DATA}
1343
+ onPauseDeployment={vi.fn()}
1344
+ onResumeDeployment={vi.fn()}
1345
+ />,
1346
+ )
1347
+ await act(async () => buttonByText('Pause rollout')!.click())
1348
+ await vi.waitFor(() => {
1349
+ expect(document.body.textContent).toContain('Cluster connection changed')
1350
+ expect(document.body.textContent).toContain(reloadMessage)
1351
+ expect(document.body.textContent).toContain('Reload required')
1352
+ expect(buttonByText('Pause rollout')!.disabled).toBe(true)
1353
+ })
1354
+ expect(calls.map((c) => c.url)).toEqual(['/api/resource-actions/apps/Deployment/pause/preview'])
1355
+
1356
+ // 3. 409 invalid_request is NOT treated as connection_changed.
1357
+ calls.length = 0
1358
+ stubFetch(() =>
1359
+ Response.json(
1360
+ { code: 'invalid_request', message: 'Parameter schema conflict.', retry: 'none', dispatch: 'not_dispatched' },
1361
+ { status: 409 },
1362
+ ),
1363
+ )
1364
+ await render(
1365
+ <ActionsBarHarness
1366
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'web' }}
1367
+ data={DEPLOYMENT_DATA}
1368
+ onRestart={vi.fn()}
1369
+ />,
1370
+ )
1371
+ await act(async () => buttonByText('Restart')!.click())
1372
+ await vi.waitFor(() => {
1373
+ expect(document.body.textContent).toContain('Parameter schema conflict.')
1374
+ expect(buttonByText('Restart')!.disabled).toBe(true)
1375
+ })
1376
+ expect(document.body.textContent).not.toContain('Cluster connection changed')
1377
+ expect(document.body.textContent).not.toContain('Reload required')
1378
+ })
1379
+
1380
+ it.each([
1381
+ { stage: 'preview' as const, expectedPreviews: 2, expectedExecutes: 0 },
1382
+ { stage: 'execute' as const, expectedPreviews: 2, expectedExecutes: 2 },
1383
+ ])(
1384
+ 'Issues zero follow-up previews when stepping or editing replicas after bulk $stage connection_changed',
1385
+ async ({ stage, expectedPreviews, expectedExecutes }) => {
1386
+ vi.useFakeTimers()
1387
+ try {
1388
+ seedD4()
1389
+ stubFetch(({ url, body }) => {
1390
+ const name = (body?.target as { name?: string })?.name ?? 'unknown'
1391
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
1392
+ if (stage === 'preview') {
1393
+ return Response.json(
1394
+ { code: 'connection_changed', message: 'The active cluster connection changed.', retry: 'none', dispatch: 'not_dispatched' },
1395
+ { status: 409 },
1396
+ )
1397
+ }
1398
+ return Response.json(
1399
+ makePreview('apps/Deployment/scale', {
1400
+ target: { namespace: 'prod', name, uid: `uid-${name}`, apiVersion: 'apps/v1' },
1401
+ }),
1402
+ )
1403
+ }
1404
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
1405
+ return Response.json(
1406
+ { code: 'connection_changed', message: 'The active cluster connection changed.', retry: 'none', dispatch: 'not_dispatched' },
1407
+ { status: 409 },
1408
+ )
1409
+ }
1410
+ return Response.json({})
1411
+ })
1412
+
1413
+ await render(
1414
+ <BulkHarness
1415
+ open
1416
+ mode="scale"
1417
+ kindLabel="Deployment"
1418
+ actionId="apps/Deployment/scale"
1419
+ items={[
1420
+ { kind: 'deployments', group: 'apps', namespace: 'prod', name: 'api', uid: 'uid-api' },
1421
+ { kind: 'deployments', group: 'apps', namespace: 'prod', name: 'worker', uid: 'uid-worker' },
1422
+ ]}
1423
+ connectionId="conn-1"
1424
+ initialReplicas={4}
1425
+ commonCurrentReplicas={2}
1426
+ onClose={() => {}}
1427
+ onCompleted={() => {}}
1428
+ />,
1429
+ )
1430
+ await act(async () => { await Promise.resolve() })
1431
+
1432
+ if (stage === 'execute') {
1433
+ expect(buttonByText('Scale to 4')!.disabled).toBe(false)
1434
+ await act(async () => { buttonByText('Scale to 4')!.click() })
1435
+ await act(async () => { await Promise.resolve() })
1436
+ }
1437
+
1438
+ expect(document.body.textContent).toContain('Cluster connection changed')
1439
+ expect(document.body.textContent).toContain('Reload or reconnect this view before trying again.')
1440
+ expect(document.body.textContent).toContain('Reload required')
1441
+ expect(buttonByText('Scale to 4')!.disabled).toBe(true)
1442
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(expectedPreviews)
1443
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(expectedExecutes)
1444
+
1445
+ // Stepping replicas past debounce must issue zero follow-up previews and keep Confirm disabled.
1446
+ const incBtn = document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!
1447
+ await act(async () => { incBtn.click() })
1448
+ await act(async () => { vi.advanceTimersByTime(260) })
1449
+ await act(async () => { await Promise.resolve() })
1450
+
1451
+ expect(buttonByText('Scale to 5')!.disabled).toBe(true)
1452
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(expectedPreviews)
1453
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(expectedExecutes)
1454
+
1455
+ // Editing the replica input directly past debounce must also issue zero previews.
1456
+ const input = document.querySelector<HTMLInputElement>('input[aria-label="Replicas"]')!
1457
+ const setInputValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!
1458
+ await act(async () => {
1459
+ setInputValue.call(input, '7')
1460
+ input.dispatchEvent(new Event('input', { bubbles: true }))
1461
+ })
1462
+ await act(async () => { vi.advanceTimersByTime(260) })
1463
+ await act(async () => { await Promise.resolve() })
1464
+
1465
+ expect(input.value).toBe('7')
1466
+ expect(buttonByText('Scale to 7')!.disabled).toBe(true)
1467
+ expect(document.body.textContent).toContain('Cluster connection changed')
1468
+ expect(document.body.textContent).toContain('Reload required')
1469
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(expectedPreviews)
1470
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(expectedExecutes)
1471
+ } finally {
1472
+ vi.useRealTimers()
1473
+ }
1474
+ },
1475
+ )
1476
+
1477
+ it('Handles direct 409 target_replaced/none in single and bulk dialogs without automatically previewing the replacement', async () => {
1478
+ seedD4()
1479
+ stubFetch(({ url }) => {
1480
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
1481
+ return Response.json(makePreview('apps/Deployment/scale'))
1482
+ }
1483
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
1484
+ return Response.json(
1485
+ { code: 'target_replaced', message: 'Deployment prod/web was replaced.', retry: 'none', dispatch: 'not_dispatched' },
1486
+ { status: 409 },
1487
+ )
1488
+ }
1489
+ return Response.json({})
1490
+ })
1491
+
1492
+ await render(<WorkloadHarness kind="deployments" data={DEPLOYMENT_DATA} />)
1493
+ await act(async () => buttonByText('Scale')!.click())
1494
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
1495
+ await vi.waitFor(() => expect(buttonByText('Apply')!.disabled).toBe(false))
1496
+
1497
+ await act(async () => buttonByText('Apply')!.click())
1498
+ await vi.waitFor(() => {
1499
+ expect(document.body.textContent).toContain('Target changed')
1500
+ expect(document.body.textContent).toContain('Deployment prod/web was replaced. Close and reselect it before trying again.')
1501
+ expect(document.body.textContent).toContain('Reselection required')
1502
+ expect(buttonByText('Apply')!.disabled).toBe(true)
1503
+ })
1504
+ expect(document.body.textContent).not.toContain('Close and reselect this object')
1505
+ expect(calls.map((c) => c.url)).toEqual([
1506
+ '/api/resource-actions/apps/Deployment/scale/preview',
1507
+ '/api/resource-actions/apps/Deployment/scale/execute',
1508
+ ])
1509
+
1510
+ // Bulk: direct 409 target_replaced/none on one item never re-previews that replacement, even when replicas change later.
1511
+ vi.useFakeTimers()
1512
+ try {
1513
+ calls.length = 0
1514
+ stubFetch(({ url, body }) => {
1515
+ const name = (body?.target as { name?: string })?.name ?? 'unknown'
1516
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
1517
+ return Response.json(
1518
+ makePreview('apps/Deployment/scale', {
1519
+ target: { namespace: 'prod', name, uid: `uid-${name}`, apiVersion: 'apps/v1' },
1520
+ }),
1521
+ )
1522
+ }
1523
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
1524
+ if (name === 'worker') {
1525
+ return Response.json(
1526
+ { code: 'target_replaced', message: 'Deployment prod/worker was replaced.', retry: 'none', dispatch: 'not_dispatched' },
1527
+ { status: 409 },
1528
+ )
1529
+ }
1530
+ return Response.json({ executionId: body?.executionId, outcome: 'applied' })
1531
+ }
1532
+ return Response.json({})
1533
+ })
1534
+
1535
+ await render(
1536
+ <BulkHarness
1537
+ open
1538
+ mode="scale"
1539
+ kindLabel="Deployment"
1540
+ actionId="apps/Deployment/scale"
1541
+ items={[
1542
+ { kind: 'deployments', group: 'apps', namespace: 'prod', name: 'api', uid: 'uid-api' },
1543
+ { kind: 'deployments', group: 'apps', namespace: 'prod', name: 'worker', uid: 'uid-worker' },
1544
+ ]}
1545
+ connectionId="conn-1"
1546
+ initialReplicas={4}
1547
+ commonCurrentReplicas={2}
1548
+ onClose={() => {}}
1549
+ onCompleted={() => {}}
1550
+ />,
1551
+ )
1552
+ await act(async () => { await Promise.resolve() })
1553
+ expect(buttonByText('Scale to 4')!.disabled).toBe(false)
1554
+
1555
+ await act(async () => { buttonByText('Scale to 4')!.click() })
1556
+ await act(async () => { await Promise.resolve() })
1557
+ // All remaining targets are replaced -> keep close/reselect and disable Confirm.
1558
+ expect(document.body.textContent).toContain('Target changed')
1559
+ expect(document.body.textContent).toContain('Close and reselect it before trying again.')
1560
+ expect(document.body.textContent).toContain('Reselection required')
1561
+ expect(buttonByText('Scale to 4')!.disabled).toBe(true)
1562
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(2)
1563
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(2)
1564
+
1565
+ // Stepping replicas creates a mixed selection: api is executable at 3, worker stays replaced.
1566
+ const decBtn = document.querySelector<HTMLButtonElement>('button[aria-label="Decrease replicas"]')!
1567
+ await act(async () => { decBtn.click() })
1568
+ await act(async () => { vi.advanceTimersByTime(260) })
1569
+ await act(async () => { await Promise.resolve() })
1570
+
1571
+ const previewsAt3 = calls.filter(
1572
+ (c) => c.url.endsWith('/preview') && (c.body?.parameters as { replicas?: number })?.replicas === 3,
1573
+ )
1574
+ expect(previewsAt3.map((c) => (c.body?.target as { name?: string })?.name)).toEqual(['api'])
1575
+ expect(document.body.textContent).toContain('Some targets changed')
1576
+ expect(document.body.textContent).toContain(
1577
+ '1 selected workload was replaced and will be skipped. Only the remaining 1 workload can run.',
1578
+ )
1579
+ expect(document.body.textContent).toContain('Deployment prod/worker was replaced. Close and reselect it before trying again.')
1580
+ expect(buttonByText('Scale to 3')!.disabled).toBe(false)
1581
+
1582
+ // Confirming in the mixed state executes only the remaining executable target, then returns to all-replaced guidance.
1583
+ await act(async () => { buttonByText('Scale to 3')!.click() })
1584
+ await act(async () => { await Promise.resolve() })
1585
+ const execsAt3 = calls.filter(
1586
+ (c) => c.url.endsWith('/execute') && (c.body?.parameters as { replicas?: number })?.replicas === 3,
1587
+ )
1588
+ expect(execsAt3.map((c) => (c.body?.target as { name?: string })?.name)).toEqual(['api'])
1589
+ expect(document.body.textContent).toContain('Target changed')
1590
+ expect(document.body.textContent).toContain('Reselection required')
1591
+ expect(buttonByText('Scale to 3')!.disabled).toBe(true)
1592
+ } finally {
1593
+ vi.useRealTimers()
1594
+ }
1595
+ })
1596
+
1597
+ it('Handles open-enum warning severity, real 422 applicability refusals, and unknown write dispatch values safely in the UI', async () => {
1598
+ seedD4()
1599
+
1600
+ // 1. Low-risk Pause with an unknown warning severity displays the warning, requires explicit review (no auto-execute), and executes on explicit Confirm.
1601
+ stubFetch(({ url, body }) => {
1602
+ if (url.endsWith('/apps/Deployment/pause/preview')) {
1603
+ return Response.json(
1604
+ makePreview('apps/Deployment/pause', {
1605
+ summary: 'Pause rollout for Deployment prod/web.',
1606
+ warnings: [{ code: 'future_guard', severity: 'critical', message: 'Future policy requires operator confirmation.' }],
1607
+ }),
1608
+ )
1609
+ }
1610
+ if (url.endsWith('/apps/Deployment/pause/execute')) {
1611
+ return Response.json({ executionId: body?.executionId, outcome: 'applied' })
1612
+ }
1613
+ return Response.json({})
1614
+ })
1615
+
1616
+ await render(
1617
+ <ActionsBarHarness
1618
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name: 'web' }}
1619
+ data={DEPLOYMENT_DATA}
1620
+ onPauseDeployment={vi.fn()}
1621
+ onResumeDeployment={vi.fn()}
1622
+ />,
1623
+ )
1624
+ await act(async () => buttonByText('Pause rollout')!.click())
1625
+ await vi.waitFor(() => {
1626
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
1627
+ expect(document.body.textContent).toContain('Future policy requires operator confirmation.')
1628
+ expect(buttonByText('Pause rollout')!.disabled).toBe(false)
1629
+ })
1630
+ expect(calls.map((c) => c.url)).toEqual(['/api/resource-actions/apps/Deployment/pause/preview'])
1631
+
1632
+ await act(async () => buttonByText('Pause rollout')!.click())
1633
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
1634
+ expect(calls.map((c) => c.url)).toEqual([
1635
+ '/api/resource-actions/apps/Deployment/pause/preview',
1636
+ '/api/resource-actions/apps/Deployment/pause/execute',
1637
+ ])
1638
+
1639
+ // 2. Real server 422 action_not_applicable on preview still prevents the action and disables Confirm.
1640
+ calls.length = 0
1641
+ stubFetch(({ url }) => {
1642
+ if (url.endsWith('/apps/Deployment/pause/preview')) {
1643
+ return Response.json(
1644
+ { code: 'action_not_applicable', message: 'Deployment is terminating.', retry: 'none', dispatch: 'not_dispatched' },
1645
+ { status: 422 },
1646
+ )
1647
+ }
1648
+ return Response.json({})
1649
+ })
1650
+ await act(async () => buttonByText('Pause rollout')!.click())
1651
+ await vi.waitFor(() => {
1652
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
1653
+ expect(document.body.textContent).toContain('Deployment is terminating.')
1654
+ expect(buttonByText('Pause rollout')!.disabled).toBe(true)
1655
+ })
1656
+ expect(calls.map((c) => c.url)).toEqual(['/api/resource-actions/apps/Deployment/pause/preview'])
1657
+ await act(async () => buttonByText('Cancel')!.click())
1658
+
1659
+ // 3. Unknown write dispatch value on HTTP 409 execute (even with retry: reapprove) locks Confirm as uncertain with zero retries.
1660
+ calls.length = 0
1661
+ stubFetch(({ url }) => {
1662
+ if (url.endsWith('/apps/Deployment/scale/preview')) return Response.json(makePreview('apps/Deployment/scale'))
1663
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
1664
+ return Response.json(
1665
+ { code: 'future_ambiguous', message: 'Write status could not be confirmed.', retry: 'reapprove', dispatch: 'partially_applied' },
1666
+ { status: 409 },
1667
+ )
1668
+ }
1669
+ return Response.json({})
1670
+ })
1671
+ await render(<WorkloadHarness kind="deployments" data={DEPLOYMENT_DATA} />)
1672
+ await act(async () => buttonByText('Scale')!.click())
1673
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
1674
+ await vi.waitFor(() => expect(buttonByText('Apply')!.disabled).toBe(false))
1675
+
1676
+ await act(async () => buttonByText('Apply')!.click())
1677
+ await vi.waitFor(() => {
1678
+ expect(document.body.textContent).toContain('Radar could not tell whether this took effect')
1679
+ expect(document.body.textContent).toContain('Inspect the current state in Kubernetes first, then reload this page and review the action again.')
1680
+ expect(buttonByText('Apply')!.disabled).toBe(true)
1681
+ })
1682
+ expect(calls.map((c) => c.url)).toEqual([
1683
+ '/api/resource-actions/apps/Deployment/scale/preview',
1684
+ '/api/resource-actions/apps/Deployment/scale/execute',
1685
+ ])
1686
+
1687
+ // Reopening keeps Confirm locked.
1688
+ await act(async () => buttonByText('Cancel')!.click())
1689
+ await act(async () => buttonByText('Scale')!.click())
1690
+ expect(document.body.textContent).toContain('Radar could not tell whether this took effect')
1691
+ expect(buttonByText('Apply')!.disabled).toBe(true)
1692
+ })
1693
+
1694
+ const deploymentWith = (overrides: { name?: string; uid?: string; replicas?: number }) => {
1695
+ const replicas = overrides.replicas ?? DEPLOYMENT_DATA.spec.replicas
1696
+ return {
1697
+ ...DEPLOYMENT_DATA,
1698
+ metadata: {
1699
+ ...DEPLOYMENT_DATA.metadata,
1700
+ ...(overrides.name !== undefined ? { name: overrides.name } : {}),
1701
+ ...(overrides.uid !== undefined ? { uid: overrides.uid } : {}),
1702
+ },
1703
+ spec: { ...DEPLOYMENT_DATA.spec, replicas },
1704
+ status: { readyReplicas: replicas },
1705
+ }
1706
+ }
1707
+
1708
+ const targetReplacedResponse = (name = 'web') =>
1709
+ Response.json(
1710
+ { code: 'target_replaced', message: `Deployment prod/${name} was replaced.`, retry: 'none', dispatch: 'not_dispatched' },
1711
+ { status: 409 },
1712
+ )
1713
+
1714
+ it.each(['late', 'early'] as const)(
1715
+ 'Retains target_replaced execute guidance across same-target UID refetch (%s order) with zero follow-up previews/executes and closes on target switch',
1716
+ async (order) => {
1717
+ seedD4()
1718
+ let replaced = false
1719
+ let resolveExecute!: (response: Response) => void
1720
+ const replacedDeployment = deploymentWith({ uid: 'uid-2', replicas: 5 })
1721
+ const otherDeployment = deploymentWith({ name: 'api', uid: 'uid-api', replicas: 1 })
1722
+
1723
+ stubFetch(({ url }) => {
1724
+ if (url === '/api/resources/deployments/prod/web') {
1725
+ return Response.json(replaced ? replacedDeployment : DEPLOYMENT_DATA)
1726
+ }
1727
+ if (url === '/api/resources/deployments/prod/api') {
1728
+ return Response.json(otherDeployment)
1729
+ }
1730
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
1731
+ return Response.json(makePreview('apps/Deployment/scale'))
1732
+ }
1733
+ if (url.endsWith('/apps/Deployment/scale/execute')) {
1734
+ if (order === 'early') {
1735
+ return new Promise<Response>((resolve) => { resolveExecute = resolve })
1736
+ }
1737
+ return targetReplacedResponse()
1738
+ }
1739
+ return Response.json({})
1740
+ })
1741
+
1742
+ await render(<QueryBackedWorkloadHarness namespace="prod" name="web" />)
1743
+ await vi.waitFor(() => expect(buttonByText('Scale')).toBeDefined())
1744
+
1745
+ await act(async () => buttonByText('Scale')!.click())
1746
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
1747
+ await vi.waitFor(() => expect(buttonByText('Apply')!.disabled).toBe(false))
1748
+
1749
+ await act(async () => buttonByText('Apply')!.click())
1750
+
1751
+ if (order === 'late') {
1752
+ await vi.waitFor(() => {
1753
+ expect(document.body.textContent).toContain('Target changed')
1754
+ expect(document.body.textContent).toContain('Deployment prod/web was replaced. Close and reselect it before trying again.')
1755
+ expect(buttonByText('Apply')!.disabled).toBe(true)
1756
+ })
1757
+ replaced = true
1758
+ await act(async () => {
1759
+ await client.invalidateQueries({ queryKey: ['resource', 'deployments', 'prod', 'web'] })
1760
+ })
1761
+ await vi.waitFor(() => expect(document.body.textContent).toContain('Current: 5 replicas'))
1762
+ } else {
1763
+ await vi.waitFor(() => expect(buttonByText('Scaling...')!.disabled).toBe(true))
1764
+ replaced = true
1765
+ await act(async () => {
1766
+ await client.invalidateQueries({ queryKey: ['resource', 'deployments', 'prod', 'web'] })
1767
+ })
1768
+ await vi.waitFor(() => expect(document.body.textContent).toContain('Current: 5 replicas'))
1769
+ await act(async () => {
1770
+ resolveExecute(targetReplacedResponse())
1771
+ })
1772
+ }
1773
+
1774
+ await vi.waitFor(() => {
1775
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
1776
+ expect(document.body.textContent).toContain('Target changed')
1777
+ expect(document.body.textContent).toContain('Deployment prod/web was replaced. Close and reselect it before trying again.')
1778
+ expect(document.body.textContent).toContain('Reselection required')
1779
+ expect(buttonByText('Apply')!.disabled).toBe(true)
1780
+ })
1781
+
1782
+ // Stepping replicas after replacement refusal must send zero previews or executes.
1783
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
1784
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
1785
+ expect(buttonByText('Apply')!.disabled).toBe(true)
1786
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(1)
1787
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1)
1788
+
1789
+ // Switching to a different target must immediately close the terminal dialog without retention.
1790
+ await render(<QueryBackedWorkloadHarness namespace="prod" name="api" />)
1791
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
1792
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(1)
1793
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1)
1794
+ },
1795
+ )
1796
+
1797
+ it('Retains target_replaced across same-locator UID change in ResourceActionsBar without crossing targets, connections, or stale previews', async () => {
1798
+ seedD4()
1799
+ let deferExecute = true
1800
+ let resolveExecute!: (response: Response) => void
1801
+ stubFetch(({ url }) => {
1802
+ if (url.endsWith('/apps/Deployment/pause/preview')) {
1803
+ return Response.json(makePreview('apps/Deployment/pause', { summary: 'Pause rollout for Deployment prod/web.' }))
1804
+ }
1805
+ if (url.endsWith('/apps/Deployment/pause/execute')) {
1806
+ if (deferExecute) {
1807
+ return new Promise<Response>((resolve) => { resolveExecute = resolve })
1808
+ }
1809
+ return targetReplacedResponse()
1810
+ }
1811
+ if (url.endsWith('/apps/Deployment/scale/preview')) {
1812
+ return Response.json(makePreview('apps/Deployment/scale'))
1813
+ }
1814
+ return Response.json({})
1815
+ })
1816
+
1817
+ const onPauseDeployment = vi.fn()
1818
+ const onResumeDeployment = vi.fn()
1819
+ const renderPauseBar = (name: string, data: typeof DEPLOYMENT_DATA) =>
1820
+ render(
1821
+ <ActionsBarHarness
1822
+ resource={{ kind: 'deployments', group: 'apps', namespace: 'prod', name }}
1823
+ data={data}
1824
+ onPauseDeployment={onPauseDeployment}
1825
+ onResumeDeployment={onResumeDeployment}
1826
+ />,
1827
+ )
1828
+
1829
+ const replacedDeployment = deploymentWith({ uid: 'uid-2' })
1830
+ const thirdDeployment = deploymentWith({ uid: 'uid-3' })
1831
+ const otherDeployment = deploymentWith({ name: 'api', uid: 'uid-api' })
1832
+
1833
+ // Clean autoExecuteIfClean Pause enters execute, rerenders new UID before refusal settles, then rerenders again after refusal.
1834
+ await renderPauseBar('web', DEPLOYMENT_DATA)
1835
+ await act(async () => buttonByText('Pause rollout')!.click())
1836
+ await vi.waitFor(() => expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1))
1837
+
1838
+ await renderPauseBar('web', replacedDeployment)
1839
+ await act(async () => { resolveExecute(targetReplacedResponse()) })
1840
+
1841
+ await vi.waitFor(() => {
1842
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
1843
+ expect(document.body.textContent).toContain('Target changed')
1844
+ expect(document.body.textContent).toContain('Deployment prod/web was replaced. Close and reselect it before trying again.')
1845
+ expect(document.body.textContent).toContain('Reselection required')
1846
+ expect(buttonByText('Pause rollout')!.disabled).toBe(true)
1847
+ })
1848
+
1849
+ // Another UID change on the same locator and connection keeps the terminal guidance open.
1850
+ await renderPauseBar('web', thirdDeployment)
1851
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1)
1852
+ expect(document.body.textContent).toContain('Target changed')
1853
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(1)
1854
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1)
1855
+
1856
+ // Navigating to a different resource closes the retained dialog immediately.
1857
+ await renderPauseBar('api', otherDeployment)
1858
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
1859
+ expect(calls.filter((c) => c.url.endsWith('/preview'))).toHaveLength(1)
1860
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(1)
1861
+
1862
+ // Switching cluster connection closes a retained target_replaced dialog even at the same locator.
1863
+ deferExecute = false
1864
+ await renderPauseBar('web', DEPLOYMENT_DATA)
1865
+ await act(async () => buttonByText('Pause rollout')!.click())
1866
+ await vi.waitFor(() => expect(document.body.textContent).toContain('Target changed'))
1867
+ observeConnectionStatus({ connectionId: 'conn-2' })
1868
+ await renderPauseBar('web', replacedDeployment)
1869
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
1870
+
1871
+ // Non-terminal active preview still closes immediately on same-locator UID change (no stale preview carried over).
1872
+ calls.length = 0
1873
+ await render(<WorkloadHarness kind="deployments" data={DEPLOYMENT_DATA} />)
1874
+ await act(async () => buttonByText('Scale')!.click())
1875
+ await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="Increase replicas"]')!.click())
1876
+ await vi.waitFor(() => expect(buttonByText('Apply')!.disabled).toBe(false))
1877
+
1878
+ await render(<WorkloadHarness kind="deployments" data={replacedDeployment} />)
1879
+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(0))
1880
+ expect(calls.filter((c) => c.url.endsWith('/execute'))).toHaveLength(0)
1881
+ })
1882
+ })