@skyhook-io/radar-app 1.22.0 → 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 (57) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +2 -1
  3. package/src/api/client.ts +12 -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 +2 -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/traffic.ts +13 -5
  16. package/src/api/workloadMetrics.test.ts +11 -2
  17. package/src/api/workloadMetrics.ts +2 -2
  18. package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
  19. package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
  20. package/src/components/diagnose/DiagnoseContext.tsx +28 -3
  21. package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
  22. package/src/components/diagnose/Home.tsx +3 -0
  23. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
  24. package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
  25. package/src/components/diagnose/InvestigationView.tsx +10 -2
  26. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
  27. package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
  28. package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
  29. package/src/components/diagnose/QuestionComposer.tsx +13 -8
  30. package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
  31. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
  32. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
  33. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
  34. package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
  35. package/src/components/diagnose/launch.ts +1 -1
  36. package/src/components/dock/PodDebugSession.test.tsx +66 -0
  37. package/src/components/dock/PodDebugSession.tsx +3 -1
  38. package/src/components/dock/TerminalTab.test.tsx +43 -3
  39. package/src/components/dock/TerminalTab.tsx +10 -1
  40. package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
  41. package/src/components/helm/InstallWizard.tsx +1 -1
  42. package/src/components/home/mcpToolCatalog.ts +1 -1
  43. package/src/components/resources/PodEvictAction.test.tsx +951 -0
  44. package/src/components/resources/PodEvictAction.tsx +167 -0
  45. package/src/components/resources/ResourcesView.tsx +3 -0
  46. package/src/components/resources/renderers/WorkloadRenderer.tsx +3 -0
  47. package/src/components/settings/LocalConnectionSettings.tsx +4 -4
  48. package/src/components/settings/SettingsDialog.tsx +23 -18
  49. package/src/components/settings/integrationQueries.test.ts +98 -0
  50. package/src/components/settings/integrationQueries.ts +36 -0
  51. package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
  52. package/src/components/traffic/TrafficView.tsx +91 -35
  53. package/src/components/ui/Markdown.test.tsx +37 -0
  54. package/src/components/ui/Markdown.tsx +15 -2
  55. package/src/components/useContextSwitchFlow.test.tsx +27 -2
  56. package/src/components/useContextSwitchFlow.tsx +20 -22
  57. package/src/components/workload/WorkloadView.tsx +16 -3
@@ -0,0 +1,829 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import {
3
+ ResourceActionError,
4
+ checkResourceActionAccess,
5
+ executeResourceAction,
6
+ executeReviewedActionWithRecovery,
7
+ previewResourceAction,
8
+ resourceActionPath,
9
+ } from './resourceActions'
10
+ import { observeConnectionStatus, resetConnectionBindingForTest } from './connectionBinding'
11
+ import { getApiBase, setApiBase } from './config'
12
+ import type { ResourceActionPreviewResponse } from '@skyhook-io/k8s-ui'
13
+ import { isConnectionChangedError, isResourceActionDispatchUncertain, previewHasWarnings, readResourceActionError } from '@skyhook-io/k8s-ui'
14
+
15
+ function makePreview(overrides: Partial<ResourceActionPreviewResponse> = {}): ResourceActionPreviewResponse {
16
+ return {
17
+ actionId: 'apps/Deployment/scale',
18
+ actionVersion: 1,
19
+ target: { namespace: 'prod', name: 'web', uid: 'uid-1', apiVersion: 'apps/v1' },
20
+ previewedAs: { user: 'alice', groups: ['devs'] },
21
+ summary: 'Scale Deployment prod/web from 2 to 4 replicas.',
22
+ changes: [
23
+ {
24
+ object: { apiVersion: 'apps/v1', kind: 'Deployment', namespace: 'prod', name: 'web', uid: 'uid-1' },
25
+ changeType: 'update',
26
+ deltas: [{ path: '/spec/replicas', before: 2, after: 4 }],
27
+ },
28
+ ],
29
+ facts: {},
30
+ warnings: [],
31
+ fromPreview: {
32
+ digest: 'v1:sha256:digest-1',
33
+ actionVersion: 1,
34
+ apiVersion: 'apps/v1',
35
+ preconditions: [{ resourceVersion: '10', uid: 'uid-1' }],
36
+ },
37
+ ...overrides,
38
+ }
39
+ }
40
+
41
+ describe('D4 resource actions HTTP client', () => {
42
+ let originalApiBase: string
43
+
44
+ beforeEach(() => {
45
+ originalApiBase = getApiBase()
46
+ setApiBase('/api')
47
+ resetConnectionBindingForTest()
48
+ })
49
+
50
+ afterEach(() => {
51
+ setApiBase(originalApiBase)
52
+ resetConnectionBindingForTest()
53
+ vi.unstubAllGlobals()
54
+ vi.restoreAllMocks()
55
+ })
56
+
57
+ it('builds exact D4 URLs for access, preview, and execute stages', () => {
58
+ expect(resourceActionPath('apps/Deployment/scale', 'preview')).toBe(
59
+ '/resource-actions/apps/Deployment/scale/preview',
60
+ )
61
+ expect(resourceActionPath('argoproj.io/Rollout/restart', 'execute')).toBe(
62
+ '/resource-actions/argoproj.io/Rollout/restart/execute',
63
+ )
64
+ expect(resourceActionPath('core/Pod/evict', 'access')).toBe(
65
+ '/resource-actions/core/Pod/evict/access',
66
+ )
67
+ expect(() => resourceActionPath('bad-id', 'preview')).toThrow()
68
+ })
69
+
70
+ it('sends closed request bodies, exact /access contract, verbatim fromPreview, and pins X-Radar-Connection', async () => {
71
+ observeConnectionStatus({ connectionId: 'conn-1' })
72
+ const calls: Array<{ url: string; body: Record<string, unknown>; conn: string | null }> = []
73
+ const preview = makePreview()
74
+
75
+ vi.stubGlobal(
76
+ 'fetch',
77
+ vi.fn<typeof fetch>(async (input, init) => {
78
+ const url = String(input)
79
+ calls.push({
80
+ url,
81
+ body: JSON.parse(String(init?.body)),
82
+ conn: new Headers(init?.headers).get('X-Radar-Connection'),
83
+ })
84
+ if (url.endsWith('/access')) {
85
+ return Response.json({ access: 'allowed' })
86
+ }
87
+ if (url.endsWith('/preview')) return Response.json(preview)
88
+ return Response.json({ executionId: 'exec-1', outcome: 'applied', effects: [] })
89
+ }),
90
+ )
91
+
92
+ const access = await checkResourceActionAccess(
93
+ 'core/Pod/evict',
94
+ { namespace: 'prod', name: 'web-0' },
95
+ { connectionId: 'conn-1' },
96
+ )
97
+ const p = await previewResourceAction(
98
+ 'apps/Deployment/scale',
99
+ { target: { namespace: 'prod', name: 'web' }, parameters: { replicas: 4 } },
100
+ { connectionId: 'conn-1' },
101
+ )
102
+ // Simulate cluster connection switch before execute; pinned connectionId must still be sent.
103
+ observeConnectionStatus({ connectionId: 'conn-2' })
104
+
105
+ const exec = await executeResourceAction(
106
+ 'apps/Deployment/scale',
107
+ {
108
+ target: { namespace: 'prod', name: 'web' },
109
+ parameters: { replicas: 4 },
110
+ executionId: 'exec-1',
111
+ fromPreview: p.fromPreview,
112
+ },
113
+ { connectionId: 'conn-1' },
114
+ )
115
+
116
+ expect(access).toEqual({ access: 'allowed' })
117
+ expect(exec.outcome).toBe('applied')
118
+ expect(calls[0]).toEqual({
119
+ url: '/api/resource-actions/core/Pod/evict/access',
120
+ body: { target: { namespace: 'prod', name: 'web-0' } },
121
+ conn: 'conn-1',
122
+ })
123
+ expect(calls[1]).toEqual({
124
+ url: '/api/resource-actions/apps/Deployment/scale/preview',
125
+ body: { target: { namespace: 'prod', name: 'web' }, parameters: { replicas: 4 } },
126
+ conn: 'conn-1',
127
+ })
128
+ expect(calls[2]).toEqual({
129
+ url: '/api/resource-actions/apps/Deployment/scale/execute',
130
+ body: {
131
+ target: { namespace: 'prod', name: 'web' },
132
+ parameters: { replicas: 4 },
133
+ executionId: 'exec-1',
134
+ fromPreview: preview.fromPreview,
135
+ },
136
+ conn: 'conn-1',
137
+ })
138
+ })
139
+
140
+ it('refuses before dispatch when selected UID does not match preview target UID', async () => {
141
+ const fetchMock = vi.fn<typeof fetch>()
142
+ vi.stubGlobal('fetch', fetchMock)
143
+
144
+ await expect(
145
+ executeReviewedActionWithRecovery({
146
+ actionId: 'apps/Deployment/scale',
147
+ target: { namespace: 'prod', name: 'web' },
148
+ uid: 'uid-selected',
149
+ parameters: { replicas: 4 },
150
+ preview: makePreview({ target: { namespace: 'prod', name: 'web', uid: 'uid-replaced', apiVersion: 'apps/v1' } }),
151
+ }),
152
+ ).rejects.toSatisfy((err: unknown) => {
153
+ return (
154
+ err instanceof ResourceActionError &&
155
+ err.code === 'target_replaced' &&
156
+ err.dispatch === 'not_dispatched'
157
+ )
158
+ })
159
+ expect(fetchMock).not.toHaveBeenCalled()
160
+ })
161
+
162
+ it('requires explicit reapproval on preview_mismatch even when the refreshed preview is unchanged', async () => {
163
+ const firstPreview = makePreview()
164
+ const unchangedRefreshedPreview = makePreview({
165
+ fromPreview: {
166
+ digest: firstPreview.fromPreview.digest,
167
+ actionVersion: 1,
168
+ apiVersion: 'apps/v1',
169
+ preconditions: [{ resourceVersion: '11', uid: 'uid-1' }],
170
+ },
171
+ })
172
+ const seen: Array<{ url: string; body: Record<string, unknown> }> = []
173
+
174
+ vi.stubGlobal(
175
+ 'fetch',
176
+ vi.fn<typeof fetch>(async (input, init) => {
177
+ const url = String(input)
178
+ const body = JSON.parse(String(init?.body))
179
+ seen.push({ url, body })
180
+ if (url.endsWith('/execute')) {
181
+ return Response.json(
182
+ {
183
+ code: 'preview_mismatch',
184
+ message: 'target state changed before execution',
185
+ retry: 'reapprove',
186
+ dispatch: 'not_dispatched',
187
+ },
188
+ { status: 409 },
189
+ )
190
+ }
191
+ return Response.json(unchangedRefreshedPreview)
192
+ }),
193
+ )
194
+
195
+ let idSeq = 0
196
+ const result = await executeReviewedActionWithRecovery({
197
+ actionId: 'apps/Deployment/scale',
198
+ target: { namespace: 'prod', name: 'web' },
199
+ uid: 'uid-1',
200
+ parameters: { replicas: 4 },
201
+ preview: firstPreview,
202
+ createId: () => `exec-${++idSeq}`,
203
+ })
204
+
205
+ expect(result.status).toBe('reapprove')
206
+ expect(result.preview).toEqual(unchangedRefreshedPreview)
207
+ expect(result.reason).toBe('target state changed before execution')
208
+ expect(seen.map((s) => s.url)).toEqual([
209
+ '/api/resource-actions/apps/Deployment/scale/execute',
210
+ '/api/resource-actions/apps/Deployment/scale/preview',
211
+ ])
212
+ expect(idSeq).toBe(1)
213
+ })
214
+
215
+ it('never auto-refreshes or retries removed preview_stale envelopes', async () => {
216
+ const fetchMock = vi.fn<typeof fetch>(async () =>
217
+ Response.json(
218
+ {
219
+ code: 'preview_stale',
220
+ message: 'resourceVersion changed',
221
+ retry: 'refresh_preview_if_unchanged',
222
+ dispatch: 'not_dispatched',
223
+ },
224
+ { status: 409 },
225
+ ),
226
+ )
227
+ vi.stubGlobal('fetch', fetchMock)
228
+
229
+ await expect(
230
+ executeReviewedActionWithRecovery({
231
+ actionId: 'apps/Deployment/scale',
232
+ target: { namespace: 'prod', name: 'web' },
233
+ uid: 'uid-1',
234
+ parameters: { replicas: 4 },
235
+ preview: makePreview(),
236
+ }),
237
+ ).rejects.toSatisfy((err: unknown) =>
238
+ err instanceof ResourceActionError &&
239
+ err.status === 409 &&
240
+ err.retry === 'none' &&
241
+ err.dispatch === 'not_dispatched',
242
+ )
243
+ expect(fetchMock).toHaveBeenCalledTimes(1)
244
+ })
245
+
246
+ it('never resends after dispatch_unknown or network failure during execute', async () => {
247
+ const firstPreview = makePreview()
248
+ const fetchMock = vi.fn<typeof fetch>(async () =>
249
+ Response.json(
250
+ {
251
+ code: 'dispatch_unknown',
252
+ message: 'apiserver connection dropped after write',
253
+ retry: 'none',
254
+ dispatch: 'unknown',
255
+ executionId: 'exec-1',
256
+ },
257
+ { status: 503 },
258
+ ),
259
+ )
260
+ vi.stubGlobal('fetch', fetchMock)
261
+
262
+ await expect(
263
+ executeReviewedActionWithRecovery({
264
+ actionId: 'apps/Deployment/scale',
265
+ target: { namespace: 'prod', name: 'web' },
266
+ parameters: { replicas: 4 },
267
+ preview: firstPreview,
268
+ }),
269
+ ).rejects.toSatisfy((err: unknown) => {
270
+ return (
271
+ err instanceof ResourceActionError &&
272
+ err.code === 'dispatch_unknown' &&
273
+ err.dispatch === 'unknown' &&
274
+ isResourceActionDispatchUncertain(err)
275
+ )
276
+ })
277
+ expect(fetchMock).toHaveBeenCalledTimes(1)
278
+
279
+ const netMock = vi.fn<typeof fetch>(async () => {
280
+ throw new TypeError('Failed to fetch')
281
+ })
282
+ vi.stubGlobal('fetch', netMock)
283
+
284
+ await expect(
285
+ executeReviewedActionWithRecovery({
286
+ actionId: 'apps/Deployment/scale',
287
+ target: { namespace: 'prod', name: 'web' },
288
+ parameters: { replicas: 4 },
289
+ preview: firstPreview,
290
+ }),
291
+ ).rejects.toSatisfy((err: unknown) => {
292
+ return err instanceof ResourceActionError && err.dispatch === 'unknown' && isResourceActionDispatchUncertain(err)
293
+ })
294
+ expect(netMock).toHaveBeenCalledTimes(1)
295
+ })
296
+
297
+ it('surfaces 401 identity_required without triggering window reload', async () => {
298
+ const reload = vi.fn()
299
+ vi.stubGlobal('window', { location: { pathname: '/resources', search: '', reload } })
300
+ vi.stubGlobal(
301
+ 'fetch',
302
+ vi.fn<typeof fetch>(async () =>
303
+ Response.json(
304
+ {
305
+ code: 'identity_required',
306
+ message: 'A signed-in user identity is required to execute this action.',
307
+ retry: 'none',
308
+ dispatch: 'not_dispatched',
309
+ },
310
+ { status: 401 },
311
+ ),
312
+ ),
313
+ )
314
+
315
+ await expect(
316
+ executeReviewedActionWithRecovery({
317
+ actionId: 'apps/Deployment/scale',
318
+ target: { namespace: 'prod', name: 'web' },
319
+ parameters: { replicas: 4 },
320
+ preview: makePreview(),
321
+ }),
322
+ ).rejects.toSatisfy((err: unknown) => {
323
+ return (
324
+ err instanceof ResourceActionError &&
325
+ err.status === 401 &&
326
+ err.code === 'identity_required' &&
327
+ err.dispatch === 'not_dispatched'
328
+ )
329
+ })
330
+ expect(reload).not.toHaveBeenCalled()
331
+ })
332
+
333
+ it('parses executedAs on fresh 202 accepted (without effects), allows recovered 202 without executedAs, and rejects malformed 2xx execute responses as dispatch_unknown', async () => {
334
+ const preview = makePreview({ actionId: 'core/Pod/evict', target: { namespace: 'prod', name: 'web-0', uid: 'pod-1', apiVersion: 'v1' } })
335
+
336
+ vi.stubGlobal(
337
+ 'fetch',
338
+ vi.fn<typeof fetch>(async () =>
339
+ Response.json(
340
+ {
341
+ executionId: 'exec-202',
342
+ outcome: 'accepted',
343
+ executedAs: { user: 'alice@example.com', groups: ['devs'] },
344
+ },
345
+ { status: 202 },
346
+ ),
347
+ ),
348
+ )
349
+ const freshAccepted = await executeReviewedActionWithRecovery({
350
+ actionId: 'core/Pod/evict',
351
+ target: { namespace: 'prod', name: 'web-0' },
352
+ uid: 'pod-1',
353
+ preview,
354
+ createId: () => 'exec-202',
355
+ })
356
+ expect(freshAccepted.status).toBe('completed')
357
+ expect(freshAccepted.response).toEqual({
358
+ executionId: 'exec-202',
359
+ outcome: 'accepted',
360
+ executedAs: { user: 'alice@example.com', groups: ['devs'] },
361
+ })
362
+
363
+ vi.stubGlobal(
364
+ 'fetch',
365
+ vi.fn<typeof fetch>(async () =>
366
+ Response.json({ executionId: 'exec-202-recovered', outcome: 'accepted' }, { status: 202 }),
367
+ ),
368
+ )
369
+ const recoveredAccepted = await executeReviewedActionWithRecovery({
370
+ actionId: 'core/Pod/evict',
371
+ target: { namespace: 'prod', name: 'web-0' },
372
+ uid: 'pod-1',
373
+ preview,
374
+ createId: () => 'exec-202-recovered',
375
+ })
376
+ expect(recoveredAccepted.status).toBe('completed')
377
+ expect(recoveredAccepted.response).toEqual({ executionId: 'exec-202-recovered', outcome: 'accepted' })
378
+
379
+ vi.stubGlobal(
380
+ 'fetch',
381
+ vi.fn<typeof fetch>(async () =>
382
+ Response.json(
383
+ { executionId: 'exec-200', outcome: 'applied', executedAs: { user: 'alice', groups: [] }, effects: [] },
384
+ { status: 200 },
385
+ ),
386
+ ),
387
+ )
388
+ const applied = await executeReviewedActionWithRecovery({
389
+ actionId: 'apps/Deployment/scale',
390
+ target: { namespace: 'prod', name: 'web' },
391
+ uid: 'uid-1',
392
+ parameters: { replicas: 4 },
393
+ preview: makePreview(),
394
+ createId: () => 'exec-200',
395
+ })
396
+ expect(applied.response).toEqual({
397
+ executionId: 'exec-200',
398
+ outcome: 'applied',
399
+ executedAs: { user: 'alice', groups: [] },
400
+ })
401
+
402
+ for (const badResponse of [
403
+ () => new Response('<html>gateway ok</html>', { status: 200, headers: { 'Content-Type': 'text/html' } }),
404
+ () => Response.json({}),
405
+ () => Response.json({ executionId: 'exec-sent', outcome: 'bogus' }),
406
+ () => Response.json({ executionId: 'exec-sent', outcome: 'applied' }, { status: 202 }),
407
+ () => Response.json({ executionId: 'exec-sent', outcome: 'accepted' }, { status: 200 }),
408
+ () => Response.json({ executionId: 'exec-sent', outcome: 'accepted', effects: [] }, { status: 202 }),
409
+ () => Response.json({ executionId: 'exec-sent', outcome: 'accepted', executedAs: { user: '' } }, { status: 202 }),
410
+ () =>
411
+ Response.json(
412
+ { executionId: 'exec-sent', outcome: 'accepted', executedAs: { user: 'alice', groups: [123] } },
413
+ { status: 202 },
414
+ ),
415
+ () => Response.json({ executionId: 'exec-sent', outcome: 'applied' }, { status: 201 }),
416
+ () => Response.json({ executionId: 'exec-wrong', outcome: 'applied' }, { status: 200 }),
417
+ ]) {
418
+ const mock = vi.fn<typeof fetch>(async () => badResponse())
419
+ vi.stubGlobal('fetch', mock)
420
+ await expect(
421
+ executeReviewedActionWithRecovery({
422
+ actionId: 'apps/Deployment/scale',
423
+ target: { namespace: 'prod', name: 'web' },
424
+ uid: 'uid-1',
425
+ parameters: { replicas: 4 },
426
+ preview: makePreview(),
427
+ createId: () => 'exec-sent',
428
+ }),
429
+ ).rejects.toSatisfy((err: unknown) =>
430
+ err instanceof ResourceActionError &&
431
+ err.code === 'dispatch_unknown' &&
432
+ err.dispatch === 'unknown' &&
433
+ err.retry === 'none' &&
434
+ isResourceActionDispatchUncertain(err),
435
+ )
436
+ expect(mock).toHaveBeenCalledTimes(1)
437
+ }
438
+ })
439
+
440
+ it('preserves validated executionId when pod eviction returns a non-accepted 200 outcome and never retries', async () => {
441
+ const preview = makePreview({
442
+ actionId: 'core/Pod/evict',
443
+ target: { namespace: 'prod', name: 'web-0', uid: 'pod-1', apiVersion: 'v1' },
444
+ })
445
+
446
+ for (const outcome of ['applied', 'noop'] as const) {
447
+ const mock = vi.fn<typeof fetch>(async () =>
448
+ Response.json({ executionId: `exec-evict-${outcome}`, outcome }, { status: 200 }),
449
+ )
450
+ vi.stubGlobal('fetch', mock)
451
+
452
+ await expect(
453
+ executeReviewedActionWithRecovery({
454
+ actionId: 'core/Pod/evict',
455
+ target: { namespace: 'prod', name: 'web-0' },
456
+ uid: 'pod-1',
457
+ preview,
458
+ createId: () => `exec-evict-${outcome}`,
459
+ }),
460
+ ).rejects.toSatisfy((err: unknown) =>
461
+ err instanceof ResourceActionError &&
462
+ err.status === 200 &&
463
+ err.code === 'dispatch_unknown' &&
464
+ err.dispatch === 'unknown' &&
465
+ err.retry === 'none' &&
466
+ err.executionId === `exec-evict-${outcome}` &&
467
+ readResourceActionError(err)?.executionId === `exec-evict-${outcome}` &&
468
+ isResourceActionDispatchUncertain(err),
469
+ )
470
+ expect(mock).toHaveBeenCalledTimes(1)
471
+ }
472
+ })
473
+
474
+ it('treats replacement UID as terminal during reapproval while keeping same-UID changes confirmable', async () => {
475
+ const firstPreview = makePreview()
476
+ const replacedPreview = makePreview({
477
+ target: { namespace: 'prod', name: 'web', uid: 'uid-replacement', apiVersion: 'apps/v1' },
478
+ fromPreview: {
479
+ digest: 'v1:sha256:digest-replacement',
480
+ actionVersion: 1,
481
+ apiVersion: 'apps/v1',
482
+ preconditions: [{ resourceVersion: '1', uid: 'uid-replacement' }],
483
+ },
484
+ })
485
+
486
+ // Case 1: server target_replaced / none / not_dispatched (including Pod evict) never re-previews
487
+ const directReplacedFetch = vi.fn<typeof fetch>(async () =>
488
+ Response.json(
489
+ { code: 'target_replaced', message: 'object recreated', retry: 'none', dispatch: 'not_dispatched' },
490
+ { status: 409 },
491
+ ),
492
+ )
493
+ vi.stubGlobal('fetch', directReplacedFetch)
494
+ await expect(
495
+ executeReviewedActionWithRecovery({
496
+ actionId: 'apps/Deployment/scale',
497
+ target: { namespace: 'prod', name: 'web' },
498
+ uid: 'uid-1',
499
+ parameters: { replicas: 4 },
500
+ preview: firstPreview,
501
+ }),
502
+ ).rejects.toSatisfy(
503
+ (err: unknown) =>
504
+ err instanceof ResourceActionError &&
505
+ err.status === 409 &&
506
+ err.code === 'target_replaced' &&
507
+ err.retry === 'none' &&
508
+ err.dispatch === 'not_dispatched',
509
+ )
510
+ expect(directReplacedFetch).toHaveBeenCalledTimes(1)
511
+
512
+ const podReplacedFetch = vi.fn<typeof fetch>(async () =>
513
+ Response.json(
514
+ { code: 'target_replaced', message: 'Pod was recreated with a new UID.', retry: 'none', dispatch: 'not_dispatched' },
515
+ { status: 409 },
516
+ ),
517
+ )
518
+ vi.stubGlobal('fetch', podReplacedFetch)
519
+ await expect(
520
+ executeReviewedActionWithRecovery({
521
+ actionId: 'core/Pod/evict',
522
+ target: { namespace: 'prod', name: 'web-0' },
523
+ uid: 'pod-1',
524
+ preview: makePreview({
525
+ actionId: 'core/Pod/evict',
526
+ target: { namespace: 'prod', name: 'web-0', uid: 'pod-1', apiVersion: 'v1' },
527
+ }),
528
+ }),
529
+ ).rejects.toSatisfy(
530
+ (err: unknown) =>
531
+ err instanceof ResourceActionError &&
532
+ err.status === 409 &&
533
+ err.code === 'target_replaced' &&
534
+ err.retry === 'none' &&
535
+ err.dispatch === 'not_dispatched',
536
+ )
537
+ expect(podReplacedFetch).toHaveBeenCalledTimes(1)
538
+
539
+ // Case 2: preview_mismatch refresh sees replacement UID -> throws target_replaced
540
+ vi.stubGlobal(
541
+ 'fetch',
542
+ vi.fn<typeof fetch>(async (input) => {
543
+ if (String(input).endsWith('/execute')) {
544
+ return Response.json(
545
+ { code: 'preview_mismatch', message: 'changed', retry: 'reapprove', dispatch: 'not_dispatched' },
546
+ { status: 409 },
547
+ )
548
+ }
549
+ return Response.json(replacedPreview)
550
+ }),
551
+ )
552
+ await expect(
553
+ executeReviewedActionWithRecovery({
554
+ actionId: 'apps/Deployment/scale',
555
+ target: { namespace: 'prod', name: 'web' },
556
+ uid: 'uid-1',
557
+ parameters: { replicas: 4 },
558
+ preview: firstPreview,
559
+ }),
560
+ ).rejects.toSatisfy((err: unknown) => err instanceof ResourceActionError && err.code === 'target_replaced')
561
+
562
+ // Case 3: preview_mismatch refresh keeps same UID -> remains eligible for reapproval
563
+ const sameUidUpdated = makePreview({
564
+ summary: 'Scale Deployment prod/web from 3 to 4 replicas.',
565
+ fromPreview: {
566
+ digest: 'v1:sha256:digest-same-uid-2',
567
+ actionVersion: 1,
568
+ apiVersion: 'apps/v1',
569
+ preconditions: [{ resourceVersion: '12', uid: 'uid-1' }],
570
+ },
571
+ })
572
+ vi.stubGlobal(
573
+ 'fetch',
574
+ vi.fn<typeof fetch>(async (input) => {
575
+ if (String(input).endsWith('/execute')) {
576
+ return Response.json(
577
+ { code: 'preview_mismatch', message: 'intent changed', retry: 'reapprove', dispatch: 'not_dispatched' },
578
+ { status: 409 },
579
+ )
580
+ }
581
+ return Response.json(sameUidUpdated)
582
+ }),
583
+ )
584
+ const reapprove = await executeReviewedActionWithRecovery({
585
+ actionId: 'apps/Deployment/scale',
586
+ target: { namespace: 'prod', name: 'web' },
587
+ uid: 'uid-1',
588
+ parameters: { replicas: 4 },
589
+ preview: firstPreview,
590
+ })
591
+ expect(reapprove.status).toBe('reapprove')
592
+ expect(reapprove.preview?.target.uid).toBe('uid-1')
593
+ })
594
+
595
+ it('surfaces typed 409 connection_changed across access, preview, and execute without auto re-preview and drops the 409 invalid_request heuristic', async () => {
596
+ const reloadMessage = 'the active cluster connection changed since this view loaded; reload the page and try again'
597
+ const seen: Array<{ url: string; conn: string | null }> = []
598
+
599
+ vi.stubGlobal(
600
+ 'fetch',
601
+ vi.fn<typeof fetch>(async (input, init) => {
602
+ const url = String(input)
603
+ seen.push({ url, conn: new Headers(init?.headers).get('X-Radar-Connection') })
604
+ return Response.json(
605
+ {
606
+ code: 'connection_changed',
607
+ message: reloadMessage,
608
+ retry: 'none',
609
+ dispatch: 'not_dispatched',
610
+ },
611
+ { status: 409 },
612
+ )
613
+ }),
614
+ )
615
+
616
+ observeConnectionStatus({ connectionId: 'conn-2' })
617
+
618
+ await expect(
619
+ checkResourceActionAccess('core/Pod/evict', { namespace: 'prod', name: 'web-0' }, { connectionId: 'conn-1' }),
620
+ ).rejects.toSatisfy(
621
+ (err: unknown) =>
622
+ err instanceof ResourceActionError &&
623
+ err.status === 409 &&
624
+ err.code === 'connection_changed' &&
625
+ err.retry === 'none' &&
626
+ err.dispatch === 'not_dispatched' &&
627
+ err.message === reloadMessage &&
628
+ isConnectionChangedError(err) &&
629
+ !isResourceActionDispatchUncertain(err),
630
+ )
631
+
632
+ await expect(
633
+ previewResourceAction(
634
+ 'apps/Deployment/scale',
635
+ { target: { namespace: 'prod', name: 'web' }, parameters: { replicas: 4 } },
636
+ { connectionId: 'conn-1' },
637
+ ),
638
+ ).rejects.toSatisfy(
639
+ (err: unknown) =>
640
+ err instanceof ResourceActionError &&
641
+ err.status === 409 &&
642
+ err.code === 'connection_changed' &&
643
+ err.retry === 'none' &&
644
+ err.dispatch === 'not_dispatched' &&
645
+ err.message === reloadMessage &&
646
+ isConnectionChangedError(err) &&
647
+ !isResourceActionDispatchUncertain(err),
648
+ )
649
+
650
+ await expect(
651
+ executeReviewedActionWithRecovery({
652
+ actionId: 'apps/Deployment/scale',
653
+ target: { namespace: 'prod', name: 'web' },
654
+ uid: 'uid-1',
655
+ parameters: { replicas: 4 },
656
+ preview: makePreview(),
657
+ options: { connectionId: 'conn-1' },
658
+ }),
659
+ ).rejects.toSatisfy(
660
+ (err: unknown) =>
661
+ err instanceof ResourceActionError &&
662
+ err.status === 409 &&
663
+ err.code === 'connection_changed' &&
664
+ err.retry === 'none' &&
665
+ err.dispatch === 'not_dispatched' &&
666
+ err.message === reloadMessage &&
667
+ isConnectionChangedError(err) &&
668
+ !isResourceActionDispatchUncertain(err),
669
+ )
670
+
671
+ // Exactly one call per stage: execute 409 connection_changed must not trigger an automatic preview.
672
+ expect(seen).toEqual([
673
+ { url: '/api/resource-actions/core/Pod/evict/access', conn: 'conn-1' },
674
+ { url: '/api/resource-actions/apps/Deployment/scale/preview', conn: 'conn-1' },
675
+ { url: '/api/resource-actions/apps/Deployment/scale/execute', conn: 'conn-1' },
676
+ ])
677
+
678
+ // 409 invalid_request is no longer misclassified as connection_changed.
679
+ vi.stubGlobal(
680
+ 'fetch',
681
+ vi.fn<typeof fetch>(async () =>
682
+ Response.json(
683
+ { code: 'invalid_request', message: 'conflict invalid request', retry: 'none', dispatch: 'not_dispatched' },
684
+ { status: 409 },
685
+ ),
686
+ ),
687
+ )
688
+ await expect(
689
+ previewResourceAction(
690
+ 'apps/Deployment/scale',
691
+ { target: { namespace: 'prod', name: 'web' }, parameters: { replicas: 4 } },
692
+ { connectionId: 'conn-1' },
693
+ ),
694
+ ).rejects.toSatisfy(
695
+ (err: unknown) =>
696
+ err instanceof ResourceActionError &&
697
+ err.status === 409 &&
698
+ err.code === 'invalid_request' &&
699
+ !isConnectionChangedError(err),
700
+ )
701
+ })
702
+
703
+ it('handles open-enum future error codes, unknown write dispatch values, and unknown warning severities safely', async () => {
704
+ // 1. Unknown error code with retry: reapprove + dispatch: not_dispatched refreshes preview once for explicit reapproval.
705
+ const refreshedPreview = makePreview({
706
+ summary: 'Refreshed preview after future policy drift.',
707
+ fromPreview: {
708
+ digest: 'v1:sha256:digest-future-2',
709
+ actionVersion: 1,
710
+ apiVersion: 'apps/v1',
711
+ preconditions: [{ resourceVersion: '15', uid: 'uid-1' }],
712
+ },
713
+ })
714
+ const reapproveCalls: string[] = []
715
+ vi.stubGlobal(
716
+ 'fetch',
717
+ vi.fn<typeof fetch>(async (input) => {
718
+ const url = String(input)
719
+ reapproveCalls.push(url)
720
+ if (url.endsWith('/execute')) {
721
+ return Response.json(
722
+ { code: 'future_policy_drift', message: 'Policy changed before execution.', retry: 'reapprove', dispatch: 'not_dispatched' },
723
+ { status: 409 },
724
+ )
725
+ }
726
+ return Response.json(refreshedPreview)
727
+ }),
728
+ )
729
+ const reapprove = await executeReviewedActionWithRecovery({
730
+ actionId: 'apps/Deployment/scale',
731
+ target: { namespace: 'prod', name: 'web' },
732
+ uid: 'uid-1',
733
+ parameters: { replicas: 4 },
734
+ preview: makePreview(),
735
+ })
736
+ expect(reapprove).toEqual({
737
+ status: 'reapprove',
738
+ preview: refreshedPreview,
739
+ reason: 'Policy changed before execution.',
740
+ })
741
+ expect(reapproveCalls).toEqual([
742
+ '/api/resource-actions/apps/Deployment/scale/execute',
743
+ '/api/resource-actions/apps/Deployment/scale/preview',
744
+ ])
745
+
746
+ // 2. Unknown error code with retry: later + dispatch: not_dispatched is not uncertain and never auto-retries.
747
+ const laterFetch = vi.fn<typeof fetch>(async () =>
748
+ Response.json(
749
+ { code: 'future_rate_limited', message: 'Try again shortly.', retry: 'later', dispatch: 'not_dispatched' },
750
+ { status: 503 },
751
+ ),
752
+ )
753
+ vi.stubGlobal('fetch', laterFetch)
754
+ await expect(
755
+ executeReviewedActionWithRecovery({
756
+ actionId: 'apps/Deployment/scale',
757
+ target: { namespace: 'prod', name: 'web' },
758
+ uid: 'uid-1',
759
+ parameters: { replicas: 4 },
760
+ preview: makePreview(),
761
+ }),
762
+ ).rejects.toSatisfy(
763
+ (err: unknown) =>
764
+ err instanceof ResourceActionError &&
765
+ err.code === 'future_rate_limited' &&
766
+ err.retry === 'later' &&
767
+ err.dispatch === 'not_dispatched' &&
768
+ !isResourceActionDispatchUncertain(err),
769
+ )
770
+ expect(laterFetch).toHaveBeenCalledTimes(1)
771
+
772
+ // 3. Unknown or removed write dispatch values are normalized to unknown/none even on HTTP 409 with retry: reapprove or known codes.
773
+ for (const payload of [
774
+ { code: 'future_ambiguous', message: 'Write may have landed.', retry: 'reapprove', dispatch: 'partially_applied' },
775
+ { code: 'execution_conflict', message: 'Write already applied.', retry: 'none', dispatch: 'applied' },
776
+ { code: 'connection_changed', message: 'Connection lost after write.', retry: 'none', dispatch: 'unknown' },
777
+ ]) {
778
+ const uncertainFetch = vi.fn<typeof fetch>(async () => Response.json(payload, { status: 409 }))
779
+ vi.stubGlobal('fetch', uncertainFetch)
780
+ await expect(
781
+ executeReviewedActionWithRecovery({
782
+ actionId: 'apps/Deployment/scale',
783
+ target: { namespace: 'prod', name: 'web' },
784
+ uid: 'uid-1',
785
+ parameters: { replicas: 4 },
786
+ preview: makePreview(),
787
+ }),
788
+ ).rejects.toSatisfy(
789
+ (err: unknown) =>
790
+ err instanceof ResourceActionError &&
791
+ err.dispatch === 'unknown' &&
792
+ err.retry === 'none' &&
793
+ isResourceActionDispatchUncertain(err),
794
+ )
795
+ expect(uncertainFetch).toHaveBeenCalledTimes(1)
796
+ }
797
+
798
+ // 4. Preview with unknown warning severity is accepted and triggers previewHasWarnings (blocking auto-execute).
799
+ vi.stubGlobal(
800
+ 'fetch',
801
+ vi.fn<typeof fetch>(async () =>
802
+ Response.json(
803
+ makePreview({
804
+ warnings: [{ code: 'future_caution', severity: 'critical', message: 'Future policy warning.' }],
805
+ }),
806
+ ),
807
+ ),
808
+ )
809
+ const previewWithUnknownSeverity = await previewResourceAction('apps/Deployment/scale', {
810
+ target: { namespace: 'prod', name: 'web' },
811
+ parameters: { replicas: 4 },
812
+ })
813
+ expect(previewWithUnknownSeverity.warnings).toEqual([
814
+ { code: 'future_caution', severity: 'critical', message: 'Future policy warning.' },
815
+ ])
816
+ expect(previewHasWarnings(previewWithUnknownSeverity)).toBe(true)
817
+ })
818
+
819
+ it('marks preview network errors as not_dispatched rather than dispatch_unknown', async () => {
820
+ vi.stubGlobal('fetch', vi.fn<typeof fetch>(async () => { throw new TypeError('Failed to fetch') }))
821
+ await expect(
822
+ previewResourceAction('apps/Deployment/scale', { target: { namespace: 'prod', name: 'web' }, parameters: { replicas: 4 } }),
823
+ ).rejects.toSatisfy((err: unknown) =>
824
+ err instanceof ResourceActionError &&
825
+ err.dispatch === 'not_dispatched' &&
826
+ !isResourceActionDispatchUncertain(err),
827
+ )
828
+ })
829
+ })