@skyhook-io/radar-app 1.22.1 → 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 (46) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +96 -28
  3. package/src/RadarApp.tsx +5 -0
  4. package/src/api/client.ts +6 -1
  5. package/src/api/workloadSource.test.tsx +857 -0
  6. package/src/api/workloadSource.ts +292 -0
  7. package/src/components/APIUnreachableBanner.test.tsx +19 -0
  8. package/src/components/APIUnreachableBanner.tsx +20 -0
  9. package/src/components/ConnectionErrorView.test.tsx +63 -2
  10. package/src/components/ConnectionErrorView.tsx +88 -68
  11. package/src/components/diagnose/ActivityTurn.tsx +6 -4
  12. package/src/components/diagnose/AssessmentCard.tsx +1 -2
  13. package/src/components/diagnose/ContinueInAgentButton.test.tsx +7 -0
  14. package/src/components/diagnose/Home.test.tsx +6 -0
  15. package/src/components/diagnose/Home.tsx +10 -3
  16. package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +1 -1
  17. package/src/components/diagnose/InvestigationEvidencePane.tsx +19 -2
  18. package/src/components/diagnose/InvestigationFindingsFooter.test.tsx +413 -0
  19. package/src/components/diagnose/InvestigationView.tsx +120 -23
  20. package/src/components/diagnose/investigationEvidence/identity.test.ts +1 -1
  21. package/src/components/diagnose/investigationEvidence/projection.test.ts +1 -1
  22. package/src/components/diagnose/investigationState.ts +9 -0
  23. package/src/components/diagnose/parts.test.tsx +11 -3
  24. package/src/components/diagnose/toolCallLabel.ts +3 -0
  25. package/src/components/home/ActivitySummary.tsx +3 -8
  26. package/src/components/home/ClusterHealthCard.tsx +91 -17
  27. package/src/components/home/ClusterHealthCard.utilization.test.tsx +187 -0
  28. package/src/components/home/HomeView.tsx +6 -26
  29. package/src/components/home/TopologyPreview.test.tsx +31 -30
  30. package/src/components/home/TopologyPreview.tsx +19 -28
  31. package/src/components/home/mcpToolCatalog.ts +3 -3
  32. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +5 -4
  33. package/src/components/resources/renderers/RolloutRenderer.tsx +4 -1
  34. package/src/components/resources/renderers/WorkloadRenderer.tsx +4 -1
  35. package/src/components/workload/WorkloadView.tsx +67 -1
  36. package/src/components/workload/WorkloadView.workloadSource.test.tsx +121 -0
  37. package/src/context/ConnectionContext.tsx +24 -5
  38. package/src/context/ConnectionProvider.connectionId.test.tsx +14 -0
  39. package/src/context/ConnectionProvider.handover.test.tsx +94 -0
  40. package/src/context/DiagnoseCustomization.tsx +20 -2
  41. package/src/hooks/useEventSource.test.tsx +275 -4
  42. package/src/hooks/useEventSource.ts +278 -51
  43. package/src/index.ts +1 -0
  44. package/src/utils/navigation.test.ts +1 -6
  45. package/src/utils/navigation.ts +9 -44
  46. package/src/utils/network-policy-navigation.test.ts +21 -36
@@ -0,0 +1,857 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { focusManager, QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
6
+ import { getApiBase } from './config'
7
+ import {
8
+ createWorkloadSourceInvalidator,
9
+ supportsWorkloadSource,
10
+ toWorkloadSourceState,
11
+ useWorkloadSource,
12
+ WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS,
13
+ WORKLOAD_SOURCE_REFETCH_INTERVAL_MS,
14
+ workloadSourceInvalidationScope,
15
+ } from './workloadSource'
16
+
17
+ const host = vi.hoisted(() => ({ radarVersion: 'v1.20.0' as string | undefined }))
18
+ vi.mock('../context/RadarUpgradeHost', () => ({ useRadarUpgradeHost: () => host }))
19
+
20
+ const CHI_404 = () =>
21
+ new Response('404 page not found\n', {
22
+ status: 404,
23
+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },
24
+ })
25
+
26
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
27
+
28
+ describe('supportsWorkloadSource', () => {
29
+ it('supports backend workloadSourceTargets kinds including CronJob and excludes unrelated kinds/groups', () => {
30
+ expect(supportsWorkloadSource('deployments', 'apps')).toBe(true)
31
+ expect(supportsWorkloadSource('statefulsets', 'apps')).toBe(true)
32
+ expect(supportsWorkloadSource('daemonsets', 'apps')).toBe(true)
33
+ expect(supportsWorkloadSource('replicasets', 'apps')).toBe(true)
34
+ expect(supportsWorkloadSource('jobs', 'batch')).toBe(true)
35
+ expect(supportsWorkloadSource('cronjobs', 'batch')).toBe(true)
36
+ expect(supportsWorkloadSource('rollouts', 'argoproj.io')).toBe(true)
37
+ expect(supportsWorkloadSource('workflows', 'argoproj.io')).toBe(true)
38
+
39
+ expect(supportsWorkloadSource('pods', '')).toBe(false)
40
+ expect(supportsWorkloadSource('jobs', 'example.io')).toBe(false)
41
+ expect(supportsWorkloadSource('cronjobs', 'example.io')).toBe(false)
42
+ expect(supportsWorkloadSource('rollouts', 'other.io')).toBe(false)
43
+ })
44
+ })
45
+
46
+ describe('useWorkloadSource capability gating', () => {
47
+ const requested: string[] = []
48
+ let element: HTMLDivElement
49
+ let root: ReturnType<typeof createRoot>
50
+ let client: QueryClient
51
+
52
+ beforeEach(() => {
53
+ requested.length = 0
54
+ host.radarVersion = 'v1.20.0'
55
+ element = document.createElement('div')
56
+ root = createRoot(element)
57
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, retryDelay: 0 } } })
58
+ })
59
+
60
+ afterEach(async () => {
61
+ await act(async () => root.unmount())
62
+ client.clear()
63
+ vi.unstubAllGlobals()
64
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
65
+ })
66
+
67
+ async function render(node: React.ReactNode) {
68
+ await act(async () => {
69
+ root.render(<QueryClientProvider client={client}>{node}</QueryClientProvider>)
70
+ })
71
+ await act(async () => {
72
+ await new Promise((resolve) => setTimeout(resolve, 0))
73
+ })
74
+ }
75
+
76
+ function Probe({
77
+ kind = 'deployments',
78
+ namespace = 'shop',
79
+ name = 'web',
80
+ enabled = true,
81
+ uid,
82
+ }: {
83
+ kind?: string
84
+ namespace?: string
85
+ name?: string
86
+ enabled?: boolean
87
+ uid?: string
88
+ }) {
89
+ const query = useWorkloadSource(kind, namespace, name, enabled, uid)
90
+ const state = toWorkloadSourceState(query)
91
+ return (
92
+ <div>
93
+ <span data-status>{state.status}</span>
94
+ {state.status === 'ready' && (
95
+ <>
96
+ <span data-repo>{state.data.images[0]?.source.repository?.value ?? ''}</span>
97
+ <span data-rev>{state.data.images[0]?.source.revision?.value ?? ''}</span>
98
+ <span data-observed>{state.data.observedAt}</span>
99
+ {state.refreshError && <span data-refresh-error>{state.refreshError}</span>}
100
+ {state.onRetry && (
101
+ <button type="button" data-retry onClick={state.onRetry}>
102
+ Retry
103
+ </button>
104
+ )}
105
+ </>
106
+ )}
107
+ {state.status === 'error' && <span data-error>{state.message}</span>}
108
+ {state.status === 'unsupported' && <span data-upgrade>{state.upgrade?.feature ?? ''}</span>}
109
+ </div>
110
+ )
111
+ }
112
+
113
+ it('fetches /workloads/{kind}/{ns}/{name}/source when workloadSource capability is supported', async () => {
114
+ vi.stubGlobal(
115
+ 'fetch',
116
+ vi.fn((input: RequestInfo | URL) => {
117
+ const url = String(input)
118
+ requested.push(url)
119
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
120
+ return Promise.resolve(
121
+ Response.json({
122
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
123
+ observedAt: '2026-11-29T00:00:00Z',
124
+ images: [
125
+ {
126
+ container: 'web',
127
+ kind: 'container',
128
+ image: 'ghcr.io/skyhook-io/web:v1',
129
+ pods: 1,
130
+ source: {
131
+ repository: { value: 'https://github.com/skyhook-io/radar', from: 'provenance' },
132
+ },
133
+ provenance: 'read',
134
+ },
135
+ ],
136
+ }),
137
+ )
138
+ }
139
+ return new Promise<Response>(() => {})
140
+ }),
141
+ )
142
+
143
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
144
+ client.setQueryData(['version-check', getApiBase()], {})
145
+
146
+ await render(<Probe />)
147
+ await vi.waitFor(() => expect(element.querySelector('[data-status]')?.textContent).toBe('ready'))
148
+ expect(element.querySelector('[data-repo]')?.textContent).toBe('https://github.com/skyhook-io/radar')
149
+ expect(requested).toContain(`${getApiBase()}/workloads/deployments/shop/web/source`)
150
+ })
151
+
152
+ it('reports unsupported without hitting the endpoint when capabilities omit workloadSource', async () => {
153
+ vi.stubGlobal(
154
+ 'fetch',
155
+ vi.fn((input: RequestInfo | URL) => {
156
+ requested.push(String(input))
157
+ return new Promise<Response>(() => {})
158
+ }),
159
+ )
160
+
161
+ client.setQueryData(['capabilities'], { features: { workloadHistory: true } })
162
+ client.setQueryData(['version-check', getApiBase()], { currentVersion: 'v1.20.0' })
163
+
164
+ await render(<Probe />)
165
+ await vi.waitFor(() => expect(element.querySelector('[data-status]')?.textContent).toBe('unsupported'))
166
+ expect(element.querySelector('[data-upgrade]')?.textContent).toBe('Workload source')
167
+ expect(requested.some((url) => url.includes('/source'))).toBe(false)
168
+ })
169
+
170
+ it('treats chi unknown-route 404 during capabilities probe as unsupported', async () => {
171
+ vi.stubGlobal(
172
+ 'fetch',
173
+ vi.fn((input: RequestInfo | URL) => {
174
+ const url = String(input)
175
+ requested.push(url)
176
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
177
+ return Promise.resolve(CHI_404())
178
+ }
179
+ return new Promise<Response>(() => {})
180
+ }),
181
+ )
182
+
183
+ await render(<Probe />)
184
+ await vi.waitFor(() => expect(element.querySelector('[data-status]')?.textContent).toBe('unsupported'))
185
+ })
186
+
187
+ it('surfaces real API errors as error state', async () => {
188
+ vi.stubGlobal(
189
+ 'fetch',
190
+ vi.fn((input: RequestInfo | URL) => {
191
+ const url = String(input)
192
+ requested.push(url)
193
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
194
+ return Promise.resolve(
195
+ Response.json({ error: 'no access to pods in namespace shop' }, { status: 403 }),
196
+ )
197
+ }
198
+ return new Promise<Response>(() => {})
199
+ }),
200
+ )
201
+
202
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
203
+ client.setQueryData(['version-check', getApiBase()], {})
204
+
205
+ await render(<Probe />)
206
+ await vi.waitFor(() => expect(element.querySelector('[data-status]')?.textContent).toBe('error'))
207
+ expect(element.querySelector('[data-error]')?.textContent).toContain('no access to pods in namespace shop')
208
+ })
209
+
210
+ it('invalidates on a Pod change event in the workload namespace, keeps showing previous answer during refetch, and surfaces refresh errors alongside cached data', async () => {
211
+ let call = 0
212
+ let releaseSecond: (() => void) | undefined
213
+ vi.stubGlobal(
214
+ 'fetch',
215
+ vi.fn((input: RequestInfo | URL) => {
216
+ const url = String(input)
217
+ requested.push(url)
218
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
219
+ call += 1
220
+ if (call === 1) {
221
+ return Promise.resolve(
222
+ Response.json({
223
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
224
+ observedAt: '2026-11-29T00:00:00Z',
225
+ images: [
226
+ {
227
+ container: 'web',
228
+ kind: 'container',
229
+ image: 'ghcr.io/skyhook-io/web:v1',
230
+ pods: 1,
231
+ source: {
232
+ repository: { value: 'https://github.com/skyhook-io/radar', from: 'provenance' },
233
+ revision: { value: 'aaaaaaa1111111', from: 'provenance' },
234
+ },
235
+ provenance: 'read',
236
+ },
237
+ ],
238
+ }),
239
+ )
240
+ }
241
+ if (call === 2) {
242
+ return new Promise<Response>((resolve) => {
243
+ releaseSecond = () =>
244
+ resolve(
245
+ Response.json({
246
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
247
+ observedAt: '2026-11-29T00:01:00Z',
248
+ images: [
249
+ {
250
+ container: 'web',
251
+ kind: 'container',
252
+ image: 'ghcr.io/skyhook-io/web:v2',
253
+ pods: 1,
254
+ source: {
255
+ repository: { value: 'https://github.com/skyhook-io/radar', from: 'provenance' },
256
+ revision: { value: 'bbbbbbb2222222', from: 'provenance' },
257
+ },
258
+ provenance: 'read',
259
+ },
260
+ ],
261
+ }),
262
+ )
263
+ })
264
+ }
265
+ return Promise.resolve(
266
+ Response.json({ error: 'registry unavailable' }, { status: 503 }),
267
+ )
268
+ }
269
+ return new Promise<Response>(() => {})
270
+ }),
271
+ )
272
+
273
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
274
+ client.setQueryData(['version-check', getApiBase()], {})
275
+
276
+ await render(<Probe uid="uid-1" />)
277
+ await vi.waitFor(() => expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111'))
278
+ expect(element.querySelector('[data-observed]')?.textContent).toBe('2026-11-29T00:00:00Z')
279
+
280
+ // Query key is stable: ['workload-source', apiBase, kind, namespace, name, uid, ...gatedKey]
281
+ const cachedQueries = client.getQueryCache().findAll({ queryKey: ['workload-source'] })
282
+ expect(cachedQueries).toHaveLength(1)
283
+ expect(cachedQueries[0].queryKey.slice(0, 6)).toEqual([
284
+ 'workload-source',
285
+ getApiBase(),
286
+ 'deployments',
287
+ 'shop',
288
+ 'web',
289
+ 'uid-1',
290
+ ])
291
+
292
+ // Pod change in the workload's namespace invalidates and refetches despite staleTime,
293
+ // while keeping the previous answer visible during the in-flight refetch.
294
+ const invalidator = createWorkloadSourceInvalidator(0)
295
+ await act(async () => {
296
+ invalidator.handleEvent(client, {
297
+ kind: 'Pod',
298
+ group: '',
299
+ namespace: 'shop',
300
+ name: 'web-abc123',
301
+ operation: 'update',
302
+ })
303
+ })
304
+ await vi.waitFor(() => expect(call).toBe(2))
305
+ expect(element.querySelector('[data-status]')?.textContent).toBe('ready')
306
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111')
307
+
308
+ await act(async () => {
309
+ releaseSecond?.()
310
+ })
311
+ await vi.waitFor(() => expect(element.querySelector('[data-rev]')?.textContent).toBe('bbbbbbb2222222'))
312
+ expect(element.querySelector('[data-observed]')?.textContent).toBe('2026-11-29T00:01:00Z')
313
+
314
+ // Subsequent refresh fails: keep cached data for the same UID and surface refreshError.
315
+ await act(async () => {
316
+ invalidator.handleEvent(client, {
317
+ kind: 'Pod',
318
+ group: '',
319
+ namespace: 'shop',
320
+ name: 'web-abc123',
321
+ operation: 'update',
322
+ })
323
+ })
324
+ await vi.waitFor(() =>
325
+ expect(element.querySelector('[data-refresh-error]')?.textContent).toContain('registry unavailable'),
326
+ )
327
+ expect(element.querySelector('[data-status]')?.textContent).toBe('ready')
328
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('bbbbbbb2222222')
329
+ expect(element.querySelector('[data-retry]')).not.toBeNull()
330
+ invalidator.reset()
331
+ })
332
+
333
+ it('drops cached data and refetches when workload UID changes (same-name replacement)', async () => {
334
+ let call = 0
335
+ vi.stubGlobal(
336
+ 'fetch',
337
+ vi.fn((input: RequestInfo | URL) => {
338
+ const url = String(input)
339
+ requested.push(url)
340
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
341
+ call += 1
342
+ if (call === 1) {
343
+ return Promise.resolve(
344
+ Response.json({
345
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
346
+ observedAt: '2026-11-29T00:00:00Z',
347
+ images: [
348
+ {
349
+ container: 'web',
350
+ kind: 'container',
351
+ image: 'ghcr.io/skyhook-io/web:v1',
352
+ pods: 1,
353
+ source: {
354
+ revision: { value: 'aaaaaaa1111111', from: 'provenance' },
355
+ },
356
+ provenance: 'read',
357
+ },
358
+ ],
359
+ }),
360
+ )
361
+ }
362
+ return Promise.resolve(Response.json({ error: 'forbidden' }, { status: 403 }))
363
+ }
364
+ return new Promise<Response>(() => {})
365
+ }),
366
+ )
367
+
368
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
369
+ client.setQueryData(['version-check', getApiBase()], {})
370
+
371
+ await render(<Probe uid="uid-old" />)
372
+ await vi.waitFor(() => expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111'))
373
+
374
+ // Same name, new UID: must NOT carry over old workload's cached response on error.
375
+ await render(<Probe uid="uid-new" />)
376
+ await vi.waitFor(() => expect(element.querySelector('[data-status]')?.textContent).toBe('error'))
377
+ expect(element.querySelector('[data-rev]')).toBeNull()
378
+ expect(element.querySelector('[data-error]')?.textContent).toContain('forbidden')
379
+ })
380
+
381
+ it('keeps showing the answer while the UID first arrives (no skeleton flash)', async () => {
382
+ let release: (() => void) | undefined
383
+ let call = 0
384
+ vi.stubGlobal(
385
+ 'fetch',
386
+ vi.fn((input: RequestInfo | URL) => {
387
+ const url = String(input)
388
+ requested.push(url)
389
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
390
+ call += 1
391
+ const body = Response.json({
392
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
393
+ observedAt: '2026-11-29T00:00:00Z',
394
+ images: [
395
+ {
396
+ container: 'web',
397
+ kind: 'container',
398
+ image: 'ghcr.io/skyhook-io/web:v1',
399
+ pods: 1,
400
+ source: { revision: { value: 'aaaaaaa1111111', from: 'provenance' } },
401
+ provenance: 'read',
402
+ },
403
+ ],
404
+ })
405
+ if (call === 1) return Promise.resolve(body)
406
+ return new Promise<Response>((resolve) => {
407
+ release = () => resolve(body)
408
+ })
409
+ }
410
+ return new Promise<Response>(() => {})
411
+ }),
412
+ )
413
+
414
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
415
+ client.setQueryData(['version-check', getApiBase()], {})
416
+
417
+ // First render from a list row: no UID yet.
418
+ await render(<Probe />)
419
+ await vi.waitFor(() => expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111'))
420
+
421
+ // The full object arrives with its UID: the key changes, but the same workload's answer stays up.
422
+ await render(<Probe uid="uid-1" />)
423
+ await vi.waitFor(() => expect(call).toBe(2))
424
+ expect(element.querySelector('[data-status]')?.textContent).toBe('ready')
425
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111')
426
+ release?.()
427
+ })
428
+
429
+ it('refetches every 2 minutes while mounted and visible, but not while backgrounded or disabled', async () => {
430
+ vi.useFakeTimers()
431
+ const flushReactQuery = async () => {
432
+ await act(async () => {
433
+ await vi.advanceTimersByTimeAsync(1)
434
+ })
435
+ }
436
+ const wasFocused = focusManager.isFocused()
437
+ focusManager.setFocused(true)
438
+ try {
439
+ let call = 0
440
+ vi.stubGlobal(
441
+ 'fetch',
442
+ vi.fn((input: RequestInfo | URL) => {
443
+ const url = String(input)
444
+ requested.push(url)
445
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
446
+ call += 1
447
+ return Promise.resolve(
448
+ Response.json({
449
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
450
+ observedAt: `2026-11-29T00:0${call}:00Z`,
451
+ images: [
452
+ {
453
+ container: 'web',
454
+ kind: 'container',
455
+ image: `ghcr.io/skyhook-io/web:v${call}`,
456
+ pods: 1,
457
+ source: { revision: { value: `rev${call}000000`, from: 'provenance' } },
458
+ provenance: 'read',
459
+ },
460
+ ],
461
+ }),
462
+ )
463
+ }
464
+ return new Promise<Response>(() => {})
465
+ }),
466
+ )
467
+
468
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
469
+ client.setQueryData(['version-check', getApiBase()], {})
470
+
471
+ await act(async () => {
472
+ root.render(
473
+ <QueryClientProvider client={client}>
474
+ <Probe uid="uid-1" />
475
+ </QueryClientProvider>,
476
+ )
477
+ })
478
+ await flushReactQuery()
479
+ expect(call).toBe(1)
480
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('rev1000000')
481
+
482
+ // Not yet 2 minutes -> no background refetch.
483
+ await act(async () => {
484
+ await vi.advanceTimersByTimeAsync(WORKLOAD_SOURCE_REFETCH_INTERVAL_MS - 1_000)
485
+ })
486
+ await flushReactQuery()
487
+ expect(call).toBe(1)
488
+
489
+ // At 2 minutes while visible -> refetches and updates.
490
+ await act(async () => {
491
+ await vi.advanceTimersByTimeAsync(1_000)
492
+ })
493
+ await flushReactQuery()
494
+ expect(call).toBe(2)
495
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('rev2000000')
496
+
497
+ // Hidden / backgrounded tab -> refetchIntervalInBackground: false prevents polling.
498
+ focusManager.setFocused(false)
499
+ await act(async () => {
500
+ await vi.advanceTimersByTimeAsync(WORKLOAD_SOURCE_REFETCH_INTERVAL_MS * 2)
501
+ })
502
+ await flushReactQuery()
503
+ expect(call).toBe(2)
504
+
505
+ // Visible again, but disabled (e.g. switched off Overview tab) -> no polling.
506
+ await act(async () => {
507
+ root.render(
508
+ <QueryClientProvider client={client}>
509
+ <Probe uid="uid-1" enabled={false} />
510
+ </QueryClientProvider>,
511
+ )
512
+ })
513
+ focusManager.setFocused(true)
514
+ await act(async () => {
515
+ await vi.advanceTimersByTimeAsync(WORKLOAD_SOURCE_REFETCH_INTERVAL_MS * 2)
516
+ })
517
+ await flushReactQuery()
518
+ expect(call).toBe(2)
519
+ } finally {
520
+ focusManager.setFocused(wasFocused)
521
+ vi.useRealTimers()
522
+ }
523
+ })
524
+
525
+ it('does not abort a slow in-flight fetch under continuous SSE invalidation events', async () => {
526
+ vi.useFakeTimers()
527
+ const flushReactQuery = async () => {
528
+ await act(async () => {
529
+ await vi.advanceTimersByTimeAsync(1)
530
+ })
531
+ }
532
+ const invalidator = createWorkloadSourceInvalidator(WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS)
533
+ try {
534
+ let call = 0
535
+ let abortedCount = 0
536
+ let resolveSlowFetch: (() => void) | undefined
537
+
538
+ vi.stubGlobal(
539
+ 'fetch',
540
+ vi.fn((input: RequestInfo | URL, init?: RequestInit) => {
541
+ const url = String(input)
542
+ requested.push(url)
543
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
544
+ call += 1
545
+ if (call === 1) {
546
+ return Promise.resolve(
547
+ Response.json({
548
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
549
+ observedAt: '2026-11-29T00:00:00Z',
550
+ images: [
551
+ {
552
+ container: 'web',
553
+ kind: 'container',
554
+ image: 'ghcr.io/skyhook-io/web:v1',
555
+ pods: 1,
556
+ source: { revision: { value: 'aaaaaaa1111111', from: 'provenance' } },
557
+ provenance: 'read',
558
+ },
559
+ ],
560
+ }),
561
+ )
562
+ }
563
+ return new Promise<Response>((resolve, reject) => {
564
+ init?.signal?.addEventListener('abort', () => {
565
+ abortedCount += 1
566
+ reject(new DOMException('Aborted', 'AbortError'))
567
+ })
568
+ resolveSlowFetch = () =>
569
+ resolve(
570
+ Response.json({
571
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
572
+ observedAt: '2026-11-29T00:00:12Z',
573
+ images: [
574
+ {
575
+ container: 'web',
576
+ kind: 'container',
577
+ image: 'ghcr.io/skyhook-io/web:v2',
578
+ pods: 1,
579
+ source: { revision: { value: 'ccccccc3333333', from: 'provenance' } },
580
+ provenance: 'read',
581
+ },
582
+ ],
583
+ }),
584
+ )
585
+ })
586
+ }
587
+ return new Promise<Response>(() => {})
588
+ }),
589
+ )
590
+
591
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
592
+ client.setQueryData(['version-check', getApiBase()], {})
593
+
594
+ await act(async () => {
595
+ root.render(
596
+ <QueryClientProvider client={client}>
597
+ <Probe uid="uid-1" />
598
+ </QueryClientProvider>,
599
+ )
600
+ })
601
+ await flushReactQuery()
602
+ expect(call).toBe(1)
603
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111')
604
+
605
+ // Leading-edge Pod event starts the slow refresh (call 2).
606
+ await act(async () => {
607
+ invalidator.handleEvent(client, {
608
+ kind: 'Pod',
609
+ group: '',
610
+ namespace: 'shop',
611
+ name: 'web-1',
612
+ operation: 'update',
613
+ })
614
+ })
615
+ await flushReactQuery()
616
+ expect(call).toBe(2)
617
+
618
+ // Continuous Pod churn every 2s across multiple 5s throttle windows
619
+ // (fires both trailing-edge timers and subsequent leading-edge invalidations).
620
+ for (let i = 0; i < 6; i += 1) {
621
+ await act(async () => {
622
+ await vi.advanceTimersByTimeAsync(2_000)
623
+ invalidator.handleEvent(client, {
624
+ kind: 'Pod',
625
+ group: '',
626
+ namespace: 'shop',
627
+ name: `web-${i + 2}`,
628
+ operation: 'update',
629
+ })
630
+ })
631
+ await flushReactQuery()
632
+ }
633
+
634
+ // The slow in-flight fetch was never aborted or restarted.
635
+ expect(abortedCount).toBe(0)
636
+ expect(call).toBe(2)
637
+
638
+ // When the slow fetch finally completes, the screen updates with the new revision.
639
+ await act(async () => {
640
+ resolveSlowFetch?.()
641
+ })
642
+ await flushReactQuery()
643
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('ccccccc3333333')
644
+ } finally {
645
+ invalidator.reset()
646
+ vi.useRealTimers()
647
+ }
648
+ })
649
+ })
650
+
651
+ describe('createWorkloadSourceInvalidator', () => {
652
+ let client: QueryClient
653
+
654
+ beforeEach(() => {
655
+ vi.useFakeTimers()
656
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
657
+ })
658
+
659
+ afterEach(() => {
660
+ client.clear()
661
+ vi.useRealTimers()
662
+ })
663
+
664
+ function seedSourceQuery(kind: string, namespace: string, name: string, uid = 'uid-1') {
665
+ client.setQueryData(
666
+ ['workload-source', getApiBase(), kind, namespace, name, uid, 'supported'],
667
+ {
668
+ workload: { group: 'apps', kind: 'Deployment', namespace, name },
669
+ observedAt: '2026-11-29T00:00:00Z',
670
+ images: [],
671
+ },
672
+ )
673
+ }
674
+
675
+ it('throttles bursts to at most once per 5s per workload (leading + trailing)', () => {
676
+ seedSourceQuery('deployments', 'shop', 'web')
677
+ seedSourceQuery('deployments', 'shop', 'api')
678
+ const invalidateSpy = vi.spyOn(client, 'invalidateQueries')
679
+ const invalidator = createWorkloadSourceInvalidator()
680
+
681
+ // First Pod event invalidates both workloads in the namespace immediately.
682
+ invalidator.handleEvent(client, {
683
+ kind: 'Pod',
684
+ group: '',
685
+ namespace: 'shop',
686
+ name: 'web-1',
687
+ operation: 'update',
688
+ })
689
+ expect(invalidateSpy).toHaveBeenCalledTimes(2)
690
+
691
+ // Further Pod events within the 5s window are coalesced, not immediately invalidated.
692
+ vi.advanceTimersByTime(1_000)
693
+ invalidator.handleEvent(client, {
694
+ kind: 'Pod',
695
+ group: '',
696
+ namespace: 'shop',
697
+ name: 'web-1',
698
+ operation: 'update',
699
+ })
700
+ vi.advanceTimersByTime(2_000)
701
+ invalidator.handleEvent(client, {
702
+ kind: 'Pod',
703
+ group: '',
704
+ namespace: 'shop',
705
+ name: 'web-2',
706
+ operation: 'add',
707
+ })
708
+ expect(invalidateSpy).toHaveBeenCalledTimes(2)
709
+
710
+ // Still inside 5s window at 4999ms.
711
+ vi.advanceTimersByTime(1_999)
712
+ expect(invalidateSpy).toHaveBeenCalledTimes(2)
713
+
714
+ // At 5000ms the trailing invalidation fires once per workload.
715
+ vi.advanceTimersByTime(1)
716
+ expect(invalidateSpy).toHaveBeenCalledTimes(4)
717
+
718
+ // No further events -> no more invalidations.
719
+ vi.advanceTimersByTime(WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS * 2)
720
+ expect(invalidateSpy).toHaveBeenCalledTimes(4)
721
+
722
+ // Independent per-workload throttling: updating only shop/web doesn't block shop/api.
723
+ invalidator.handleEvent(client, {
724
+ kind: 'Deployment',
725
+ group: 'apps',
726
+ namespace: 'shop',
727
+ name: 'web',
728
+ operation: 'update',
729
+ })
730
+ expect(invalidateSpy).toHaveBeenCalledTimes(5)
731
+ vi.advanceTimersByTime(1_000)
732
+ invalidator.handleEvent(client, {
733
+ kind: 'Deployment',
734
+ group: 'apps',
735
+ namespace: 'shop',
736
+ name: 'api',
737
+ operation: 'update',
738
+ })
739
+ expect(invalidateSpy).toHaveBeenCalledTimes(6)
740
+
741
+ invalidator.reset()
742
+ })
743
+
744
+ it('does not invalidate workloads in unrelated namespaces or for unrelated workloads/resources', () => {
745
+ seedSourceQuery('deployments', 'shop', 'web')
746
+ seedSourceQuery('deployments', 'billing', 'ledger')
747
+ const invalidateSpy = vi.spyOn(client, 'invalidateQueries')
748
+ const invalidator = createWorkloadSourceInvalidator()
749
+
750
+ // Pod in an unrelated namespace does not invalidate shop/web or billing/ledger.
751
+ invalidator.handleEvent(client, {
752
+ kind: 'Pod',
753
+ group: '',
754
+ namespace: 'payments',
755
+ name: 'worker-1',
756
+ operation: 'update',
757
+ })
758
+ expect(invalidateSpy).not.toHaveBeenCalled()
759
+
760
+ // Pod in shop invalidates only shop/web, not billing/ledger.
761
+ invalidator.handleEvent(client, {
762
+ kind: 'Pod',
763
+ group: '',
764
+ namespace: 'shop',
765
+ name: 'web-1',
766
+ operation: 'update',
767
+ })
768
+ expect(invalidateSpy).toHaveBeenCalledTimes(1)
769
+ expect(invalidateSpy).toHaveBeenCalledWith(
770
+ {
771
+ queryKey: ['workload-source', getApiBase(), 'deployments', 'shop', 'web'],
772
+ },
773
+ { cancelRefetch: false },
774
+ )
775
+
776
+ // A different Deployment in billing does not invalidate billing/ledger.
777
+ invalidator.handleEvent(client, {
778
+ kind: 'Deployment',
779
+ group: 'apps',
780
+ namespace: 'billing',
781
+ name: 'invoicer',
782
+ operation: 'update',
783
+ })
784
+ expect(invalidateSpy).toHaveBeenCalledTimes(1)
785
+
786
+ // Unrelated kinds and wrong API groups do not invalidate anything.
787
+ for (const event of [
788
+ { kind: 'ConfigMap', group: '', namespace: 'shop', name: 'cfg', operation: 'update' as const },
789
+ { kind: 'PodMetrics', group: 'metrics.k8s.io', namespace: 'shop', name: 'web-1', operation: 'update' as const },
790
+ { kind: 'Application', group: 'app.k8s.io', namespace: 'argocd', name: 'web', operation: 'update' as const },
791
+ { kind: 'Kustomization', group: 'kustomize.config.k8s.io', namespace: 'flux-system', name: 'web', operation: 'update' as const },
792
+ { kind: 'HelmChart', group: 'helm.cattle.io', namespace: 'kube-system', name: 'traefik', operation: 'update' as const },
793
+ { kind: 'Bucket', group: 's3.aws.upbound.io', namespace: 'shop', name: 'assets', operation: 'update' as const },
794
+ { kind: 'ArtifactGenerator', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'gen', operation: 'update' as const },
795
+ ]) {
796
+ invalidator.handleEvent(client, event)
797
+ }
798
+ expect(invalidateSpy).toHaveBeenCalledTimes(1)
799
+
800
+ invalidator.reset()
801
+ })
802
+
803
+ it('invalidates workloads when GitOps managers or Flux sources change (even across namespaces)', () => {
804
+ seedSourceQuery('deployments', 'shop', 'web')
805
+ const invalidateSpy = vi.spyOn(client, 'invalidateQueries')
806
+ const invalidator = createWorkloadSourceInvalidator()
807
+
808
+ const gitopsEvents = [
809
+ { kind: 'Application', group: 'argoproj.io', namespace: 'argocd', name: 'shop-app', operation: 'update' as const },
810
+ { kind: 'Kustomization', group: 'kustomize.toolkit.fluxcd.io', namespace: 'flux-system', name: 'shop', operation: 'update' as const },
811
+ { kind: 'HelmRelease', group: 'helm.toolkit.fluxcd.io', namespace: 'flux-system', name: 'shop', operation: 'update' as const },
812
+ { kind: 'GitRepository', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'fleet', operation: 'update' as const },
813
+ { kind: 'OCIRepository', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'manifests', operation: 'update' as const },
814
+ { kind: 'Bucket', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'manifests-s3', operation: 'update' as const },
815
+ { kind: 'HelmRepository', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'charts', operation: 'update' as const },
816
+ { kind: 'HelmChart', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'shop-chart', operation: 'update' as const },
817
+ { kind: 'ExternalArtifact', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'ext-art', operation: 'update' as const },
818
+ { kind: 'ArtifactGenerator', group: 'source.extensions.fluxcd.io', namespace: 'flux-system', name: 'gen', operation: 'update' as const },
819
+ ]
820
+
821
+ for (const [idx, event] of gitopsEvents.entries()) {
822
+ expect(workloadSourceInvalidationScope(event)).toEqual({ scope: 'all' })
823
+ invalidator.handleEvent(client, event)
824
+ expect(invalidateSpy).toHaveBeenCalledTimes(idx + 1)
825
+ vi.advanceTimersByTime(WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS)
826
+ }
827
+
828
+ invalidator.reset()
829
+ })
830
+
831
+ it('cancels pending trailing invalidations on reset (context switch / unmount)', () => {
832
+ seedSourceQuery('deployments', 'shop', 'web')
833
+ const invalidateSpy = vi.spyOn(client, 'invalidateQueries')
834
+ const invalidator = createWorkloadSourceInvalidator()
835
+
836
+ invalidator.handleEvent(client, {
837
+ kind: 'Pod',
838
+ group: '',
839
+ namespace: 'shop',
840
+ name: 'web-1',
841
+ operation: 'update',
842
+ })
843
+ vi.advanceTimersByTime(1_000)
844
+ invalidator.handleEvent(client, {
845
+ kind: 'Pod',
846
+ group: '',
847
+ namespace: 'shop',
848
+ name: 'web-2',
849
+ operation: 'update',
850
+ })
851
+ expect(invalidateSpy).toHaveBeenCalledTimes(1)
852
+
853
+ invalidator.reset()
854
+ vi.advanceTimersByTime(WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS * 2)
855
+ expect(invalidateSpy).toHaveBeenCalledTimes(1)
856
+ })
857
+ })