@skyhook-io/radar-app 1.22.1 → 1.23.0

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 (234) hide show
  1. package/package.json +8 -8
  2. package/src/App.tsx +131 -38
  3. package/src/RadarApp.basename.test.tsx +177 -0
  4. package/src/RadarApp.settings.test.tsx +33 -0
  5. package/src/RadarApp.tsx +5 -0
  6. package/src/api/agentSandbox.ts +259 -0
  7. package/src/api/client.autoPromConnect.test.tsx +43 -0
  8. package/src/api/client.metricsRelayCheck.test.tsx +134 -0
  9. package/src/api/client.ts +128 -25
  10. package/src/api/cloudInstallDiscover.test.tsx +76 -0
  11. package/src/api/diagnose.ts +4 -0
  12. package/src/api/kagent.test.ts +82 -0
  13. package/src/api/kagent.ts +230 -0
  14. package/src/api/prometheusCharts.ts +5 -0
  15. package/src/api/radarFeatures.test.ts +9 -0
  16. package/src/api/radarFeatures.ts +13 -0
  17. package/src/api/substrateWorkspace.test.ts +72 -0
  18. package/src/api/substrateWorkspace.ts +1394 -0
  19. package/src/api/vulnerabilities.ts +207 -9
  20. package/src/api/workloadSource.test.tsx +1172 -0
  21. package/src/api/workloadSource.ts +408 -0
  22. package/src/components/APIUnreachableBanner.test.tsx +19 -0
  23. package/src/components/APIUnreachableBanner.tsx +20 -0
  24. package/src/components/CloudConnectFlow.tsx +46 -7
  25. package/src/components/CloudFunnelButton.test.tsx +193 -7
  26. package/src/components/CloudFunnelButton.tsx +127 -32
  27. package/src/components/ConnectionErrorView.test.tsx +63 -2
  28. package/src/components/ConnectionErrorView.tsx +88 -68
  29. package/src/components/SelfManagedStart.tsx +12 -2
  30. package/src/components/agentsandbox/AgentSandboxKindLists.tsx +41 -0
  31. package/src/components/agentsandbox/AgentSandboxLists.test.tsx +410 -0
  32. package/src/components/agentsandbox/AgentSandboxOverview.test.tsx +333 -0
  33. package/src/components/agentsandbox/AgentSandboxOverview.tsx +555 -0
  34. package/src/components/agentsandbox/AgentSandboxSidebar.test.tsx +97 -0
  35. package/src/components/agentsandbox/AgentSandboxSummary.test.tsx +439 -0
  36. package/src/components/agentsandbox/AgentSandboxSummary.tsx +956 -0
  37. package/src/components/agentsandbox/AgentSandboxTables.tsx +966 -0
  38. package/src/components/agentsandbox/AgentSandboxView.tsx +34 -0
  39. package/src/components/agentsandbox/agentsandbox.fixtures.ts +135 -0
  40. package/src/components/agentsandbox/data.ts +135 -0
  41. package/src/components/agentsandbox/host.test.ts +27 -0
  42. package/src/components/agentsandbox/host.tsx +85 -0
  43. package/src/components/agentsandbox/labels.test.ts +42 -0
  44. package/src/components/agentsandbox/labels.ts +146 -0
  45. package/src/components/agentsandbox/listFilters.ts +85 -0
  46. package/src/components/agentsandbox/lists.ts +52 -0
  47. package/src/components/agentsandbox/routes.ts +23 -0
  48. package/src/components/agentsandbox/shared.tsx +321 -0
  49. package/src/components/agentsandbox/useAgentSandboxSidebarWorkspace.ts +69 -0
  50. package/src/components/agentsandbox/workspace.fixtures.ts +125 -0
  51. package/src/components/agentsandbox/workspace.tsx +258 -0
  52. package/src/components/agentsandbox/workspaceRoute.ts +18 -0
  53. package/src/components/applications/ApplicationsView.openResource.test.tsx +248 -3
  54. package/src/components/applications/ApplicationsView.tsx +156 -3
  55. package/src/components/audit/VulnerabilitiesColumns.test.tsx +487 -0
  56. package/src/components/audit/VulnerabilitiesRisk.test.tsx +318 -0
  57. package/src/components/audit/VulnerabilitiesView.test.tsx +458 -13
  58. package/src/components/audit/VulnerabilitiesView.tsx +639 -199
  59. package/src/components/cloudHints/AgentSetupCloudRow.tsx +28 -0
  60. package/src/components/cloudHints/CloudHintLink.tsx +29 -0
  61. package/src/components/cloudHints/SharedInstallAiLine.tsx +36 -0
  62. package/src/components/cloudHints/cloudHints.test.ts +126 -0
  63. package/src/components/cloudHints/cloudHints.ts +131 -0
  64. package/src/components/cloudHints/cloudHintsGate.test.tsx +70 -0
  65. package/src/components/cloudHints/cloudLinks.test.ts +52 -0
  66. package/src/components/cloudHints/cloudLinks.ts +31 -0
  67. package/src/components/cloudHints/hintStorage.ts +28 -0
  68. package/src/components/cnpg/CNPGView.tsx +4 -7
  69. package/src/components/diagnose/ActivityTurn.tsx +6 -4
  70. package/src/components/diagnose/AgentSetupNotice.tsx +5 -0
  71. package/src/components/diagnose/AssessmentCard.tsx +1 -2
  72. package/src/components/diagnose/ContinueInAgentButton.test.tsx +7 -0
  73. package/src/components/diagnose/DiagnoseContext.tsx +7 -0
  74. package/src/components/diagnose/DiagnoseSurface.escape.test.tsx +215 -0
  75. package/src/components/diagnose/DiagnoseSurface.tsx +57 -1
  76. package/src/components/diagnose/Home.test.tsx +6 -0
  77. package/src/components/diagnose/Home.tsx +10 -3
  78. package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +1 -1
  79. package/src/components/diagnose/InvestigationEvidencePane.tsx +19 -2
  80. package/src/components/diagnose/InvestigationFindingsFooter.test.tsx +413 -0
  81. package/src/components/diagnose/InvestigationView.tsx +120 -23
  82. package/src/components/diagnose/investigationEvidence/identity.test.ts +1 -1
  83. package/src/components/diagnose/investigationEvidence/projection.test.ts +1 -1
  84. package/src/components/diagnose/investigationState.ts +9 -0
  85. package/src/components/diagnose/parts.test.tsx +11 -3
  86. package/src/components/diagnose/toolCallLabel.ts +3 -0
  87. package/src/components/gitops/RemoteDestinationCloudHint.tsx +6 -14
  88. package/src/components/home/ActivitySummary.tsx +3 -8
  89. package/src/components/home/ClusterHealthCard.tsx +91 -17
  90. package/src/components/home/ClusterHealthCard.utilization.test.tsx +187 -0
  91. package/src/components/home/HomeAgentBlock.tsx +2 -0
  92. package/src/components/home/HomeView.tsx +9 -29
  93. package/src/components/home/MCPSetupDialog.test.tsx +9 -0
  94. package/src/components/home/MCPSetupDialog.tsx +6 -2
  95. package/src/components/home/McpCloudLine.test.tsx +162 -0
  96. package/src/components/home/McpCloudLine.tsx +95 -0
  97. package/src/components/home/ProblemsPanel.investigate.test.tsx +2 -2
  98. package/src/components/home/TopologyPreview.test.tsx +31 -30
  99. package/src/components/home/TopologyPreview.tsx +19 -28
  100. package/src/components/home/mcpToolCatalog.test.ts +10 -0
  101. package/src/components/home/mcpToolCatalog.ts +7 -7
  102. package/src/components/issues/ClusterSchedulingBlockerRow.tsx +35 -0
  103. package/src/components/issues/IssuesPane.render.test.tsx +36 -1
  104. package/src/components/issues/IssuesPane.tsx +181 -23
  105. package/src/components/issues/SinceLastVisitRow.render.test.tsx +302 -0
  106. package/src/components/issues/SinceLastVisitRow.tsx +71 -0
  107. package/src/components/issues/sinceLastVisit.test.ts +266 -0
  108. package/src/components/issues/sinceLastVisit.ts +439 -0
  109. package/src/components/kagent/KagentAgentRenderer.test.ts +32 -0
  110. package/src/components/kagent/KagentAgentRenderer.tsx +87 -0
  111. package/src/components/kagent/KagentAgentSessions.test.tsx +166 -0
  112. package/src/components/kagent/KagentAgentSessions.tsx +124 -0
  113. package/src/components/kagent/KagentDetailPage.tsx +106 -0
  114. package/src/components/kagent/KagentLists.tsx +412 -0
  115. package/src/components/kagent/KagentOverview.tsx +234 -0
  116. package/src/components/kagent/KagentPages.tsx +690 -0
  117. package/src/components/kagent/KagentRuntimeTabs.test.tsx +219 -0
  118. package/src/components/kagent/KagentRuntimeTabs.tsx +283 -0
  119. package/src/components/kagent/KagentSidebar.test.tsx +112 -0
  120. package/src/components/kagent/KagentView.tsx +109 -0
  121. package/src/components/kagent/KagentWorkspace.test.tsx +876 -0
  122. package/src/components/kagent/host.tsx +144 -0
  123. package/src/components/kagent/routes.ts +31 -0
  124. package/src/components/kagent/shared.tsx +336 -0
  125. package/src/components/kagent/useKagentRuntime.test.tsx +77 -0
  126. package/src/components/kagent/useKagentSidebarWorkspace.ts +67 -0
  127. package/src/components/kagent/workspace.fixtures.ts +108 -0
  128. package/src/components/kagent/workspaceRoute.ts +18 -0
  129. package/src/components/resource/MetricsNotConnected.test.tsx +28 -0
  130. package/src/components/resource/MetricsNotConnected.tsx +10 -7
  131. package/src/components/resource/PrometheusCharts.tsx +10 -1
  132. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +9 -0
  133. package/src/components/resource/PrometheusChartsGrid.tsx +3 -3
  134. package/src/components/resource/SubstrateHealthCharts.test.tsx +13 -1
  135. package/src/components/resource/SubstrateHealthCharts.tsx +9 -15
  136. package/src/components/resources/ResourceDetailDrawer.tsx +1 -0
  137. package/src/components/resources/ResourcesView.tsx +2 -6
  138. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +5 -4
  139. package/src/components/resources/renderers/PodRenderer.tsx +8 -2
  140. package/src/components/resources/renderers/RolloutRenderer.tsx +4 -1
  141. package/src/components/resources/renderers/WorkloadRenderer.tsx +4 -1
  142. package/src/components/settings/LocalIntegrationStatus.test.tsx +1 -0
  143. package/src/components/settings/LocalIntegrationStatus.tsx +3 -2
  144. package/src/components/settings/SettingsDialog.tsx +84 -16
  145. package/src/components/settings/SubstrateSettings.lifecycle.test.tsx +210 -0
  146. package/src/components/settings/SubstrateSettings.test.tsx +131 -0
  147. package/src/components/settings/SubstrateSettings.tsx +544 -0
  148. package/src/components/settings/settings-state.test.ts +21 -3
  149. package/src/components/settings/settings-state.ts +13 -3
  150. package/src/components/share/ShareLinkButton.test.tsx +360 -0
  151. package/src/components/share/ShareLinkButton.tsx +391 -0
  152. package/src/components/share/openShareInCloud.test.ts +29 -0
  153. package/src/components/share/openShareInCloud.ts +10 -0
  154. package/src/components/share/shareLink.test.ts +129 -0
  155. package/src/components/share/shareLink.ts +175 -0
  156. package/src/components/substrate/SubstrateActorDrawer.tsx +87 -0
  157. package/src/components/substrate/SubstrateActorOverview.tsx +489 -0
  158. package/src/components/substrate/SubstrateActorPage.tsx +384 -0
  159. package/src/components/substrate/SubstrateActors.test.tsx +1094 -0
  160. package/src/components/substrate/SubstrateActors.tsx +612 -0
  161. package/src/components/substrate/SubstrateAttentionList.tsx +441 -0
  162. package/src/components/substrate/SubstrateConnect.tsx +88 -0
  163. package/src/components/substrate/SubstrateOverview.test.tsx +396 -0
  164. package/src/components/substrate/SubstrateOverview.tsx +575 -0
  165. package/src/components/substrate/SubstratePages.test.tsx +478 -0
  166. package/src/components/substrate/SubstratePool.test.tsx +462 -0
  167. package/src/components/substrate/SubstratePoolPage.tsx +95 -0
  168. package/src/components/substrate/SubstratePoolSummary.tsx +485 -0
  169. package/src/components/substrate/SubstrateSidebar.test.tsx +101 -0
  170. package/src/components/substrate/SubstrateStateBar.tsx +63 -0
  171. package/src/components/substrate/SubstrateTemplates.tsx +376 -0
  172. package/src/components/substrate/SubstrateView.tsx +173 -0
  173. package/src/components/substrate/SubstrateWorkerPodContext.tsx +73 -0
  174. package/src/components/substrate/SubstrateWorkers.tsx +389 -0
  175. package/src/components/substrate/attention.ts +81 -0
  176. package/src/components/substrate/contextPin.tsx +69 -0
  177. package/src/components/substrate/host.tsx +83 -0
  178. package/src/components/substrate/kubectlTarget.test.tsx +77 -0
  179. package/src/components/substrate/readings.test.ts +484 -0
  180. package/src/components/substrate/readings.ts +997 -0
  181. package/src/components/substrate/routes.ts +103 -0
  182. package/src/components/substrate/shared.tsx +426 -0
  183. package/src/components/substrate/substrate.fixtures.ts +325 -0
  184. package/src/components/substrate/useSubstrateSidebarWorkspace.ts +87 -0
  185. package/src/components/substrate/workspaceRoute.ts +23 -0
  186. package/src/components/traffic/TrafficConnectionsTable.test.tsx +9 -0
  187. package/src/components/traffic/TrafficConnectionsTable.tsx +4 -2
  188. package/src/components/traffic/TrafficFilterSidebar.tsx +19 -14
  189. package/src/components/traffic/TrafficFlowList.test.tsx +63 -0
  190. package/src/components/traffic/TrafficFlowList.tsx +9 -5
  191. package/src/components/traffic/TrafficGraph.test.tsx +26 -0
  192. package/src/components/traffic/TrafficGraph.tsx +17 -14
  193. package/src/components/traffic/TrafficGraphTooLarge.tsx +2 -0
  194. package/src/components/traffic/TrafficGraphUnavailable.tsx +3 -1
  195. package/src/components/traffic/TrafficView.tsx +26 -56
  196. package/src/components/traffic/trafficFilters.test.ts +61 -1
  197. package/src/components/traffic/trafficFilters.ts +68 -8
  198. package/src/components/velero/VeleroOverview.tsx +2 -2
  199. package/src/components/velero/VeleroView.tsx +3 -6
  200. package/src/components/vulnerabilities/columns.tsx +132 -0
  201. package/src/components/vulnerabilities/filters.tsx +317 -0
  202. package/src/components/vulnerabilities/owner.test.ts +54 -0
  203. package/src/components/vulnerabilities/owner.tsx +163 -0
  204. package/src/components/vulnerabilities/parts.test.ts +126 -12
  205. package/src/components/vulnerabilities/parts.tsx +612 -52
  206. package/src/components/vulnerabilities/traffic.test.tsx +65 -0
  207. package/src/components/vulnerabilities/traffic.tsx +40 -0
  208. package/src/components/workload/WorkloadView.substrateVersion.test.tsx +88 -0
  209. package/src/components/workload/WorkloadView.tsx +119 -14
  210. package/src/components/workload/WorkloadView.workloadSource.test.tsx +121 -0
  211. package/src/components/workspace/layout.tsx +13 -7
  212. package/src/components/workspace/sidebar.test.ts +48 -0
  213. package/src/components/workspace/sidebar.ts +73 -3
  214. package/src/components/workspace/table.ts +2 -1
  215. package/src/context/ConnectionContext.tsx +24 -5
  216. package/src/context/ConnectionProvider.connectionId.test.tsx +14 -0
  217. package/src/context/ConnectionProvider.handover.test.tsx +94 -0
  218. package/src/context/DiagnoseCustomization.tsx +20 -2
  219. package/src/contexts/RegistryAccessMode.test.tsx +51 -0
  220. package/src/contexts/RegistryAccessMode.tsx +25 -0
  221. package/src/hooks/useEventSource.test.tsx +275 -4
  222. package/src/hooks/useEventSource.ts +278 -51
  223. package/src/index.ts +1 -0
  224. package/src/integrations/resourceHost.ts +12 -6
  225. package/src/integrations/resourceHosts.test.tsx +27 -1
  226. package/src/integrations/resourceHosts.tsx +15 -7
  227. package/src/integrations/sidebarWorkspaces.test.tsx +63 -0
  228. package/src/integrations/sidebarWorkspaces.ts +41 -0
  229. package/src/integrations/workspaceRoute.ts +1 -1
  230. package/src/integrations/workspaceRoutes.ts +7 -1
  231. package/src/integrations/workspaceScreens.tsx +6 -0
  232. package/src/utils/navigation.test.ts +1 -6
  233. package/src/utils/navigation.ts +9 -44
  234. package/src/utils/network-policy-navigation.test.ts +21 -36
@@ -0,0 +1,1172 @@
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
+ useWorkloadSources,
13
+ workloadSourceTargetKey,
14
+ WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS,
15
+ WORKLOAD_SOURCE_REFETCH_INTERVAL_MS,
16
+ workloadSourceInvalidationScope,
17
+ } from './workloadSource'
18
+
19
+ const host = vi.hoisted(() => ({ radarVersion: 'v1.20.0' as string | undefined }))
20
+ vi.mock('../context/RadarUpgradeHost', () => ({ useRadarUpgradeHost: () => host }))
21
+
22
+ const CHI_404 = () =>
23
+ new Response('404 page not found\n', {
24
+ status: 404,
25
+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },
26
+ })
27
+
28
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
29
+
30
+ describe('supportsWorkloadSource', () => {
31
+ it('supports backend workloadSourceTargets kinds including CronJob and excludes unrelated kinds/groups', () => {
32
+ expect(supportsWorkloadSource('deployments', 'apps')).toBe(true)
33
+ expect(supportsWorkloadSource('statefulsets', 'apps')).toBe(true)
34
+ expect(supportsWorkloadSource('daemonsets', 'apps')).toBe(true)
35
+ expect(supportsWorkloadSource('replicasets', 'apps')).toBe(true)
36
+ expect(supportsWorkloadSource('jobs', 'batch')).toBe(true)
37
+ expect(supportsWorkloadSource('cronjobs', 'batch')).toBe(true)
38
+ expect(supportsWorkloadSource('rollouts', 'argoproj.io')).toBe(true)
39
+ expect(supportsWorkloadSource('workflows', 'argoproj.io')).toBe(true)
40
+
41
+ expect(supportsWorkloadSource('pods', '')).toBe(false)
42
+ expect(supportsWorkloadSource('jobs', 'example.io')).toBe(false)
43
+ expect(supportsWorkloadSource('cronjobs', 'example.io')).toBe(false)
44
+ expect(supportsWorkloadSource('rollouts', 'other.io')).toBe(false)
45
+ })
46
+ })
47
+
48
+ describe('useWorkloadSource capability gating', () => {
49
+ const requested: string[] = []
50
+ let element: HTMLDivElement
51
+ let root: ReturnType<typeof createRoot>
52
+ let client: QueryClient
53
+
54
+ beforeEach(() => {
55
+ requested.length = 0
56
+ host.radarVersion = 'v1.20.0'
57
+ element = document.createElement('div')
58
+ root = createRoot(element)
59
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, retryDelay: 0 } } })
60
+ })
61
+
62
+ afterEach(async () => {
63
+ await act(async () => root.unmount())
64
+ client.clear()
65
+ vi.unstubAllGlobals()
66
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
67
+ })
68
+
69
+ async function render(node: React.ReactNode) {
70
+ await act(async () => {
71
+ root.render(<QueryClientProvider client={client}>{node}</QueryClientProvider>)
72
+ })
73
+ await act(async () => {
74
+ await new Promise((resolve) => setTimeout(resolve, 0))
75
+ })
76
+ }
77
+
78
+ function Probe({
79
+ kind = 'deployments',
80
+ namespace = 'shop',
81
+ name = 'web',
82
+ enabled = true,
83
+ uid,
84
+ }: {
85
+ kind?: string
86
+ namespace?: string
87
+ name?: string
88
+ enabled?: boolean
89
+ uid?: string
90
+ }) {
91
+ const query = useWorkloadSource(kind, namespace, name, enabled, uid)
92
+ const state = toWorkloadSourceState(query)
93
+ return (
94
+ <div>
95
+ <span data-status>{state.status}</span>
96
+ {state.status === 'ready' && (
97
+ <>
98
+ <span data-repo>{state.data.images[0]?.source.repository?.value ?? ''}</span>
99
+ <span data-rev>{state.data.images[0]?.source.revision?.value ?? ''}</span>
100
+ <span data-observed>{state.data.observedAt}</span>
101
+ {state.refreshError && <span data-refresh-error>{state.refreshError}</span>}
102
+ {state.onRetry && (
103
+ <button type="button" data-retry onClick={state.onRetry}>
104
+ Retry
105
+ </button>
106
+ )}
107
+ </>
108
+ )}
109
+ {state.status === 'error' && <span data-error>{state.message}</span>}
110
+ {state.status === 'unsupported' && <span data-upgrade>{state.upgrade?.feature ?? ''}</span>}
111
+ </div>
112
+ )
113
+ }
114
+
115
+ it('fetches /workloads/{kind}/{ns}/{name}/source when workloadSource capability is supported', async () => {
116
+ vi.stubGlobal(
117
+ 'fetch',
118
+ vi.fn((input: RequestInfo | URL) => {
119
+ const url = String(input)
120
+ requested.push(url)
121
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
122
+ return Promise.resolve(
123
+ Response.json({
124
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
125
+ observedAt: '2026-11-29T00:00:00Z',
126
+ images: [
127
+ {
128
+ container: 'web',
129
+ kind: 'container',
130
+ image: 'ghcr.io/skyhook-io/web:v1',
131
+ pods: 1,
132
+ source: {
133
+ repository: { value: 'https://github.com/skyhook-io/radar', from: 'provenance' },
134
+ },
135
+ provenance: 'read',
136
+ },
137
+ ],
138
+ }),
139
+ )
140
+ }
141
+ return new Promise<Response>(() => {})
142
+ }),
143
+ )
144
+
145
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
146
+ client.setQueryData(['version-check', getApiBase()], {})
147
+
148
+ await render(<Probe />)
149
+ await vi.waitFor(() => expect(element.querySelector('[data-status]')?.textContent).toBe('ready'))
150
+ expect(element.querySelector('[data-repo]')?.textContent).toBe('https://github.com/skyhook-io/radar')
151
+ expect(requested).toContain(`${getApiBase()}/workloads/deployments/shop/web/source`)
152
+ })
153
+
154
+ it('reports unsupported without hitting the endpoint when capabilities omit workloadSource', async () => {
155
+ vi.stubGlobal(
156
+ 'fetch',
157
+ vi.fn((input: RequestInfo | URL) => {
158
+ requested.push(String(input))
159
+ return new Promise<Response>(() => {})
160
+ }),
161
+ )
162
+
163
+ client.setQueryData(['capabilities'], { features: { workloadHistory: true } })
164
+ client.setQueryData(['version-check', getApiBase()], { currentVersion: 'v1.20.0' })
165
+
166
+ await render(<Probe />)
167
+ await vi.waitFor(() => expect(element.querySelector('[data-status]')?.textContent).toBe('unsupported'))
168
+ expect(element.querySelector('[data-upgrade]')?.textContent).toBe('Workload source')
169
+ expect(requested.some((url) => url.includes('/source'))).toBe(false)
170
+ })
171
+
172
+ it('treats chi unknown-route 404 during capabilities probe as unsupported', async () => {
173
+ vi.stubGlobal(
174
+ 'fetch',
175
+ vi.fn((input: RequestInfo | URL) => {
176
+ const url = String(input)
177
+ requested.push(url)
178
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
179
+ return Promise.resolve(CHI_404())
180
+ }
181
+ return new Promise<Response>(() => {})
182
+ }),
183
+ )
184
+
185
+ await render(<Probe />)
186
+ await vi.waitFor(() => expect(element.querySelector('[data-status]')?.textContent).toBe('unsupported'))
187
+ })
188
+
189
+ it('surfaces real API errors as error state', async () => {
190
+ vi.stubGlobal(
191
+ 'fetch',
192
+ vi.fn((input: RequestInfo | URL) => {
193
+ const url = String(input)
194
+ requested.push(url)
195
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
196
+ return Promise.resolve(
197
+ Response.json({ error: 'no access to pods in namespace shop' }, { status: 403 }),
198
+ )
199
+ }
200
+ return new Promise<Response>(() => {})
201
+ }),
202
+ )
203
+
204
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
205
+ client.setQueryData(['version-check', getApiBase()], {})
206
+
207
+ await render(<Probe />)
208
+ await vi.waitFor(() => expect(element.querySelector('[data-status]')?.textContent).toBe('error'))
209
+ expect(element.querySelector('[data-error]')?.textContent).toContain('no access to pods in namespace shop')
210
+ })
211
+
212
+ 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 () => {
213
+ let call = 0
214
+ let releaseSecond: (() => void) | undefined
215
+ vi.stubGlobal(
216
+ 'fetch',
217
+ vi.fn((input: RequestInfo | URL) => {
218
+ const url = String(input)
219
+ requested.push(url)
220
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
221
+ call += 1
222
+ if (call === 1) {
223
+ return Promise.resolve(
224
+ Response.json({
225
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
226
+ observedAt: '2026-11-29T00:00:00Z',
227
+ images: [
228
+ {
229
+ container: 'web',
230
+ kind: 'container',
231
+ image: 'ghcr.io/skyhook-io/web:v1',
232
+ pods: 1,
233
+ source: {
234
+ repository: { value: 'https://github.com/skyhook-io/radar', from: 'provenance' },
235
+ revision: { value: 'aaaaaaa1111111', from: 'provenance' },
236
+ },
237
+ provenance: 'read',
238
+ },
239
+ ],
240
+ }),
241
+ )
242
+ }
243
+ if (call === 2) {
244
+ return new Promise<Response>((resolve) => {
245
+ releaseSecond = () =>
246
+ resolve(
247
+ Response.json({
248
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
249
+ observedAt: '2026-11-29T00:01:00Z',
250
+ images: [
251
+ {
252
+ container: 'web',
253
+ kind: 'container',
254
+ image: 'ghcr.io/skyhook-io/web:v2',
255
+ pods: 1,
256
+ source: {
257
+ repository: { value: 'https://github.com/skyhook-io/radar', from: 'provenance' },
258
+ revision: { value: 'bbbbbbb2222222', from: 'provenance' },
259
+ },
260
+ provenance: 'read',
261
+ },
262
+ ],
263
+ }),
264
+ )
265
+ })
266
+ }
267
+ return Promise.resolve(
268
+ Response.json({ error: 'registry unavailable' }, { status: 503 }),
269
+ )
270
+ }
271
+ return new Promise<Response>(() => {})
272
+ }),
273
+ )
274
+
275
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
276
+ client.setQueryData(['version-check', getApiBase()], {})
277
+
278
+ await render(<Probe uid="uid-1" />)
279
+ await vi.waitFor(() => expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111'))
280
+ expect(element.querySelector('[data-observed]')?.textContent).toBe('2026-11-29T00:00:00Z')
281
+
282
+ // Query key is stable: ['workload-source', apiBase, kind, namespace, name, uid, ...gatedKey]
283
+ const cachedQueries = client.getQueryCache().findAll({ queryKey: ['workload-source'] })
284
+ expect(cachedQueries).toHaveLength(1)
285
+ expect(cachedQueries[0].queryKey.slice(0, 6)).toEqual([
286
+ 'workload-source',
287
+ getApiBase(),
288
+ 'deployments',
289
+ 'shop',
290
+ 'web',
291
+ 'uid-1',
292
+ ])
293
+
294
+ // Pod change in the workload's namespace invalidates and refetches despite staleTime,
295
+ // while keeping the previous answer visible during the in-flight refetch.
296
+ const invalidator = createWorkloadSourceInvalidator(0)
297
+ await act(async () => {
298
+ invalidator.handleEvent(client, {
299
+ kind: 'Pod',
300
+ group: '',
301
+ namespace: 'shop',
302
+ name: 'web-abc123',
303
+ operation: 'update',
304
+ })
305
+ })
306
+ await vi.waitFor(() => expect(call).toBe(2))
307
+ expect(element.querySelector('[data-status]')?.textContent).toBe('ready')
308
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111')
309
+
310
+ await act(async () => {
311
+ releaseSecond?.()
312
+ })
313
+ await vi.waitFor(() => expect(element.querySelector('[data-rev]')?.textContent).toBe('bbbbbbb2222222'))
314
+ expect(element.querySelector('[data-observed]')?.textContent).toBe('2026-11-29T00:01:00Z')
315
+
316
+ // Subsequent refresh fails: keep cached data for the same UID and surface refreshError.
317
+ await act(async () => {
318
+ invalidator.handleEvent(client, {
319
+ kind: 'Pod',
320
+ group: '',
321
+ namespace: 'shop',
322
+ name: 'web-abc123',
323
+ operation: 'update',
324
+ })
325
+ })
326
+ await vi.waitFor(() =>
327
+ expect(element.querySelector('[data-refresh-error]')?.textContent).toContain('registry unavailable'),
328
+ )
329
+ expect(element.querySelector('[data-status]')?.textContent).toBe('ready')
330
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('bbbbbbb2222222')
331
+ expect(element.querySelector('[data-retry]')).not.toBeNull()
332
+ invalidator.reset()
333
+ })
334
+
335
+ it.each([401, 403, 404])('drops cached data on same-UID refresh %i instead of showing stale source', async (status) => {
336
+ let call = 0
337
+ vi.stubGlobal(
338
+ 'fetch',
339
+ vi.fn((input: RequestInfo | URL) => {
340
+ const url = String(input)
341
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
342
+ call += 1
343
+ if (call === 1) {
344
+ return Promise.resolve(
345
+ Response.json({
346
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
347
+ observedAt: '2026-11-29T00:00:00Z',
348
+ images: [
349
+ {
350
+ container: 'web',
351
+ kind: 'container',
352
+ image: 'ghcr.io/skyhook-io/web:v1',
353
+ pods: 1,
354
+ source: { revision: { value: 'aaaaaaa1111111', from: 'provenance' } },
355
+ provenance: 'read',
356
+ },
357
+ ],
358
+ }),
359
+ )
360
+ }
361
+ return Promise.resolve(Response.json({ error: `status ${status}` }, { status }))
362
+ }
363
+ return new Promise<Response>(() => {})
364
+ }),
365
+ )
366
+
367
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
368
+ client.setQueryData(['version-check', getApiBase()], {})
369
+
370
+ await render(<Probe uid="uid-1" />)
371
+ await vi.waitFor(() => expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111'))
372
+
373
+ await act(async () => {
374
+ await client.invalidateQueries({ queryKey: ['workload-source'] })
375
+ })
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(`status ${status}`)
379
+ })
380
+
381
+ it('drops cached data and refetches when workload UID changes (same-name replacement)', async () => {
382
+ let call = 0
383
+ vi.stubGlobal(
384
+ 'fetch',
385
+ vi.fn((input: RequestInfo | URL) => {
386
+ const url = String(input)
387
+ requested.push(url)
388
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
389
+ call += 1
390
+ if (call === 1) {
391
+ return Promise.resolve(
392
+ Response.json({
393
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
394
+ observedAt: '2026-11-29T00:00:00Z',
395
+ images: [
396
+ {
397
+ container: 'web',
398
+ kind: 'container',
399
+ image: 'ghcr.io/skyhook-io/web:v1',
400
+ pods: 1,
401
+ source: {
402
+ revision: { value: 'aaaaaaa1111111', from: 'provenance' },
403
+ },
404
+ provenance: 'read',
405
+ },
406
+ ],
407
+ }),
408
+ )
409
+ }
410
+ return Promise.resolve(Response.json({ error: 'forbidden' }, { status: 403 }))
411
+ }
412
+ return new Promise<Response>(() => {})
413
+ }),
414
+ )
415
+
416
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
417
+ client.setQueryData(['version-check', getApiBase()], {})
418
+
419
+ await render(<Probe uid="uid-old" />)
420
+ await vi.waitFor(() => expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111'))
421
+
422
+ // Same name, new UID: must NOT carry over old workload's cached response on error.
423
+ await render(<Probe uid="uid-new" />)
424
+ await vi.waitFor(() => expect(element.querySelector('[data-status]')?.textContent).toBe('error'))
425
+ expect(element.querySelector('[data-rev]')).toBeNull()
426
+ expect(element.querySelector('[data-error]')?.textContent).toContain('forbidden')
427
+ })
428
+
429
+ it('keeps showing the answer while the UID first arrives (no skeleton flash)', async () => {
430
+ let release: (() => void) | undefined
431
+ let call = 0
432
+ vi.stubGlobal(
433
+ 'fetch',
434
+ vi.fn((input: RequestInfo | URL) => {
435
+ const url = String(input)
436
+ requested.push(url)
437
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
438
+ call += 1
439
+ const body = Response.json({
440
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
441
+ observedAt: '2026-11-29T00:00:00Z',
442
+ images: [
443
+ {
444
+ container: 'web',
445
+ kind: 'container',
446
+ image: 'ghcr.io/skyhook-io/web:v1',
447
+ pods: 1,
448
+ source: { revision: { value: 'aaaaaaa1111111', from: 'provenance' } },
449
+ provenance: 'read',
450
+ },
451
+ ],
452
+ })
453
+ if (call === 1) return Promise.resolve(body)
454
+ return new Promise<Response>((resolve) => {
455
+ release = () => resolve(body)
456
+ })
457
+ }
458
+ return new Promise<Response>(() => {})
459
+ }),
460
+ )
461
+
462
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
463
+ client.setQueryData(['version-check', getApiBase()], {})
464
+
465
+ // First render from a list row: no UID yet.
466
+ await render(<Probe />)
467
+ await vi.waitFor(() => expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111'))
468
+
469
+ // The full object arrives with its UID: the key changes, but the same workload's answer stays up.
470
+ await render(<Probe uid="uid-1" />)
471
+ await vi.waitFor(() => expect(call).toBe(2))
472
+ expect(element.querySelector('[data-status]')?.textContent).toBe('ready')
473
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111')
474
+ release?.()
475
+ })
476
+
477
+ it('refetches every 2 minutes while mounted and visible, but not while backgrounded or disabled', async () => {
478
+ vi.useFakeTimers()
479
+ const flushReactQuery = async () => {
480
+ await act(async () => {
481
+ await vi.advanceTimersByTimeAsync(1)
482
+ })
483
+ }
484
+ const wasFocused = focusManager.isFocused()
485
+ focusManager.setFocused(true)
486
+ try {
487
+ let call = 0
488
+ vi.stubGlobal(
489
+ 'fetch',
490
+ vi.fn((input: RequestInfo | URL) => {
491
+ const url = String(input)
492
+ requested.push(url)
493
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
494
+ call += 1
495
+ return Promise.resolve(
496
+ Response.json({
497
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
498
+ observedAt: `2026-11-29T00:0${call}:00Z`,
499
+ images: [
500
+ {
501
+ container: 'web',
502
+ kind: 'container',
503
+ image: `ghcr.io/skyhook-io/web:v${call}`,
504
+ pods: 1,
505
+ source: { revision: { value: `rev${call}000000`, from: 'provenance' } },
506
+ provenance: 'read',
507
+ },
508
+ ],
509
+ }),
510
+ )
511
+ }
512
+ return new Promise<Response>(() => {})
513
+ }),
514
+ )
515
+
516
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
517
+ client.setQueryData(['version-check', getApiBase()], {})
518
+
519
+ await act(async () => {
520
+ root.render(
521
+ <QueryClientProvider client={client}>
522
+ <Probe uid="uid-1" />
523
+ </QueryClientProvider>,
524
+ )
525
+ })
526
+ await flushReactQuery()
527
+ expect(call).toBe(1)
528
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('rev1000000')
529
+
530
+ // Not yet 2 minutes -> no background refetch.
531
+ await act(async () => {
532
+ await vi.advanceTimersByTimeAsync(WORKLOAD_SOURCE_REFETCH_INTERVAL_MS - 1_000)
533
+ })
534
+ await flushReactQuery()
535
+ expect(call).toBe(1)
536
+
537
+ // At 2 minutes while visible -> refetches and updates.
538
+ await act(async () => {
539
+ await vi.advanceTimersByTimeAsync(1_000)
540
+ })
541
+ await flushReactQuery()
542
+ expect(call).toBe(2)
543
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('rev2000000')
544
+
545
+ // Hidden / backgrounded tab -> refetchIntervalInBackground: false prevents polling.
546
+ focusManager.setFocused(false)
547
+ await act(async () => {
548
+ await vi.advanceTimersByTimeAsync(WORKLOAD_SOURCE_REFETCH_INTERVAL_MS * 2)
549
+ })
550
+ await flushReactQuery()
551
+ expect(call).toBe(2)
552
+
553
+ // Visible again, but disabled (e.g. switched off Overview tab) -> no polling.
554
+ await act(async () => {
555
+ root.render(
556
+ <QueryClientProvider client={client}>
557
+ <Probe uid="uid-1" enabled={false} />
558
+ </QueryClientProvider>,
559
+ )
560
+ })
561
+ focusManager.setFocused(true)
562
+ await act(async () => {
563
+ await vi.advanceTimersByTimeAsync(WORKLOAD_SOURCE_REFETCH_INTERVAL_MS * 2)
564
+ })
565
+ await flushReactQuery()
566
+ expect(call).toBe(2)
567
+ } finally {
568
+ focusManager.setFocused(wasFocused)
569
+ vi.useRealTimers()
570
+ }
571
+ })
572
+
573
+ it('does not abort a slow in-flight fetch under continuous SSE invalidation events', async () => {
574
+ vi.useFakeTimers()
575
+ const flushReactQuery = async () => {
576
+ await act(async () => {
577
+ await vi.advanceTimersByTimeAsync(1)
578
+ })
579
+ }
580
+ const invalidator = createWorkloadSourceInvalidator(WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS)
581
+ try {
582
+ let call = 0
583
+ let abortedCount = 0
584
+ let resolveSlowFetch: (() => void) | undefined
585
+
586
+ vi.stubGlobal(
587
+ 'fetch',
588
+ vi.fn((input: RequestInfo | URL, init?: RequestInit) => {
589
+ const url = String(input)
590
+ requested.push(url)
591
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
592
+ call += 1
593
+ if (call === 1) {
594
+ return Promise.resolve(
595
+ Response.json({
596
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
597
+ observedAt: '2026-11-29T00:00:00Z',
598
+ images: [
599
+ {
600
+ container: 'web',
601
+ kind: 'container',
602
+ image: 'ghcr.io/skyhook-io/web:v1',
603
+ pods: 1,
604
+ source: { revision: { value: 'aaaaaaa1111111', from: 'provenance' } },
605
+ provenance: 'read',
606
+ },
607
+ ],
608
+ }),
609
+ )
610
+ }
611
+ return new Promise<Response>((resolve, reject) => {
612
+ init?.signal?.addEventListener('abort', () => {
613
+ abortedCount += 1
614
+ reject(new DOMException('Aborted', 'AbortError'))
615
+ })
616
+ resolveSlowFetch = () =>
617
+ resolve(
618
+ Response.json({
619
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
620
+ observedAt: '2026-11-29T00:00:12Z',
621
+ images: [
622
+ {
623
+ container: 'web',
624
+ kind: 'container',
625
+ image: 'ghcr.io/skyhook-io/web:v2',
626
+ pods: 1,
627
+ source: { revision: { value: 'ccccccc3333333', from: 'provenance' } },
628
+ provenance: 'read',
629
+ },
630
+ ],
631
+ }),
632
+ )
633
+ })
634
+ }
635
+ return new Promise<Response>(() => {})
636
+ }),
637
+ )
638
+
639
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
640
+ client.setQueryData(['version-check', getApiBase()], {})
641
+
642
+ await act(async () => {
643
+ root.render(
644
+ <QueryClientProvider client={client}>
645
+ <Probe uid="uid-1" />
646
+ </QueryClientProvider>,
647
+ )
648
+ })
649
+ await flushReactQuery()
650
+ expect(call).toBe(1)
651
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111')
652
+
653
+ // Leading-edge Pod event starts the slow refresh (call 2).
654
+ await act(async () => {
655
+ invalidator.handleEvent(client, {
656
+ kind: 'Pod',
657
+ group: '',
658
+ namespace: 'shop',
659
+ name: 'web-1',
660
+ operation: 'update',
661
+ })
662
+ })
663
+ await flushReactQuery()
664
+ expect(call).toBe(2)
665
+
666
+ // Continuous Pod churn every 2s across multiple 5s throttle windows
667
+ // (fires both trailing-edge timers and subsequent leading-edge invalidations).
668
+ for (let i = 0; i < 6; i += 1) {
669
+ await act(async () => {
670
+ await vi.advanceTimersByTimeAsync(2_000)
671
+ invalidator.handleEvent(client, {
672
+ kind: 'Pod',
673
+ group: '',
674
+ namespace: 'shop',
675
+ name: `web-${i + 2}`,
676
+ operation: 'update',
677
+ })
678
+ })
679
+ await flushReactQuery()
680
+ }
681
+
682
+ // The slow in-flight fetch was never aborted or restarted.
683
+ expect(abortedCount).toBe(0)
684
+ expect(call).toBe(2)
685
+
686
+ // When the slow fetch finally completes, the screen updates with the new revision.
687
+ await act(async () => {
688
+ resolveSlowFetch?.()
689
+ })
690
+ await flushReactQuery()
691
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('ccccccc3333333')
692
+ } finally {
693
+ invalidator.reset()
694
+ vi.useRealTimers()
695
+ }
696
+ })
697
+
698
+ it.each([401, 403, 404])(
699
+ 'evicts cached source on %i so a later 500 cannot resurrect forbidden/deleted data',
700
+ async (evictStatus) => {
701
+ let step: 200 | 401 | 403 | 404 | 500 = 200
702
+ vi.stubGlobal(
703
+ 'fetch',
704
+ vi.fn((input: RequestInfo | URL) => {
705
+ const url = String(input)
706
+ requested.push(url)
707
+ if (url.endsWith('/workloads/deployments/shop/web/source')) {
708
+ if (step === 200) {
709
+ return Promise.resolve(
710
+ Response.json({
711
+ workload: { group: 'apps', kind: 'Deployment', namespace: 'shop', name: 'web' },
712
+ observedAt: '2026-11-29T00:00:00Z',
713
+ images: [
714
+ {
715
+ container: 'web',
716
+ kind: 'container',
717
+ image: 'ghcr.io/skyhook-io/web:v1',
718
+ pods: 1,
719
+ source: { revision: { value: 'aaaaaaa1111111', from: 'provenance' } },
720
+ provenance: 'read',
721
+ },
722
+ ],
723
+ }),
724
+ )
725
+ }
726
+ return Promise.resolve(Response.json({ error: `status ${step}` }, { status: step }))
727
+ }
728
+ return new Promise<Response>(() => {})
729
+ }),
730
+ )
731
+
732
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
733
+ client.setQueryData(['version-check', getApiBase()], {})
734
+
735
+ await render(<Probe uid="uid-1" />)
736
+ await vi.waitFor(() => {
737
+ expect(element.querySelector('[data-status]')?.textContent).toBe('ready')
738
+ expect(element.querySelector('[data-rev]')?.textContent).toBe('aaaaaaa1111111')
739
+ })
740
+
741
+ step = evictStatus as 401 | 403 | 404
742
+ await act(async () => {
743
+ await client.invalidateQueries({ queryKey: ['workload-source'] })
744
+ })
745
+ await vi.waitFor(() => {
746
+ expect(element.querySelector('[data-status]')?.textContent).toBe('error')
747
+ expect(element.querySelector('[data-error]')?.textContent).toContain(`status ${evictStatus}`)
748
+ expect(element.querySelector('[data-rev]')).toBeNull()
749
+ })
750
+
751
+ step = 500
752
+ await act(async () => {
753
+ await client.invalidateQueries({ queryKey: ['workload-source'] })
754
+ })
755
+ await vi.waitFor(() => {
756
+ expect(element.querySelector('[data-status]')?.textContent).toBe('error')
757
+ expect(element.querySelector('[data-error]')?.textContent).toContain('status 500')
758
+ expect(element.querySelector('[data-rev]')).toBeNull()
759
+ })
760
+ },
761
+ )
762
+ })
763
+
764
+ describe('createWorkloadSourceInvalidator', () => {
765
+ let client: QueryClient
766
+
767
+ beforeEach(() => {
768
+ vi.useFakeTimers()
769
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
770
+ })
771
+
772
+ afterEach(() => {
773
+ client.clear()
774
+ vi.useRealTimers()
775
+ })
776
+
777
+ function seedSourceQuery(kind: string, namespace: string, name: string, uid = 'uid-1') {
778
+ client.setQueryData(
779
+ ['workload-source', getApiBase(), kind, namespace, name, uid, 'supported'],
780
+ {
781
+ workload: { group: 'apps', kind: 'Deployment', namespace, name },
782
+ observedAt: '2026-11-29T00:00:00Z',
783
+ images: [],
784
+ },
785
+ )
786
+ }
787
+
788
+ it('throttles bursts to at most once per 5s per workload (leading + trailing)', () => {
789
+ seedSourceQuery('deployments', 'shop', 'web')
790
+ seedSourceQuery('deployments', 'shop', 'api')
791
+ const invalidateSpy = vi.spyOn(client, 'invalidateQueries')
792
+ const invalidator = createWorkloadSourceInvalidator()
793
+
794
+ // First Pod event invalidates both workloads in the namespace immediately.
795
+ invalidator.handleEvent(client, {
796
+ kind: 'Pod',
797
+ group: '',
798
+ namespace: 'shop',
799
+ name: 'web-1',
800
+ operation: 'update',
801
+ })
802
+ expect(invalidateSpy).toHaveBeenCalledTimes(2)
803
+
804
+ // Further Pod events within the 5s window are coalesced, not immediately invalidated.
805
+ vi.advanceTimersByTime(1_000)
806
+ invalidator.handleEvent(client, {
807
+ kind: 'Pod',
808
+ group: '',
809
+ namespace: 'shop',
810
+ name: 'web-1',
811
+ operation: 'update',
812
+ })
813
+ vi.advanceTimersByTime(2_000)
814
+ invalidator.handleEvent(client, {
815
+ kind: 'Pod',
816
+ group: '',
817
+ namespace: 'shop',
818
+ name: 'web-2',
819
+ operation: 'add',
820
+ })
821
+ expect(invalidateSpy).toHaveBeenCalledTimes(2)
822
+
823
+ // Still inside 5s window at 4999ms.
824
+ vi.advanceTimersByTime(1_999)
825
+ expect(invalidateSpy).toHaveBeenCalledTimes(2)
826
+
827
+ // At 5000ms the trailing invalidation fires once per workload.
828
+ vi.advanceTimersByTime(1)
829
+ expect(invalidateSpy).toHaveBeenCalledTimes(4)
830
+
831
+ // No further events -> no more invalidations.
832
+ vi.advanceTimersByTime(WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS * 2)
833
+ expect(invalidateSpy).toHaveBeenCalledTimes(4)
834
+
835
+ // Independent per-workload throttling: updating only shop/web doesn't block shop/api.
836
+ invalidator.handleEvent(client, {
837
+ kind: 'Deployment',
838
+ group: 'apps',
839
+ namespace: 'shop',
840
+ name: 'web',
841
+ operation: 'update',
842
+ })
843
+ expect(invalidateSpy).toHaveBeenCalledTimes(5)
844
+ vi.advanceTimersByTime(1_000)
845
+ invalidator.handleEvent(client, {
846
+ kind: 'Deployment',
847
+ group: 'apps',
848
+ namespace: 'shop',
849
+ name: 'api',
850
+ operation: 'update',
851
+ })
852
+ expect(invalidateSpy).toHaveBeenCalledTimes(6)
853
+
854
+ invalidator.reset()
855
+ })
856
+
857
+ it('does not invalidate workloads in unrelated namespaces or for unrelated workloads/resources', () => {
858
+ seedSourceQuery('deployments', 'shop', 'web')
859
+ seedSourceQuery('deployments', 'billing', 'ledger')
860
+ const invalidateSpy = vi.spyOn(client, 'invalidateQueries')
861
+ const invalidator = createWorkloadSourceInvalidator()
862
+
863
+ // Pod in an unrelated namespace does not invalidate shop/web or billing/ledger.
864
+ invalidator.handleEvent(client, {
865
+ kind: 'Pod',
866
+ group: '',
867
+ namespace: 'payments',
868
+ name: 'worker-1',
869
+ operation: 'update',
870
+ })
871
+ expect(invalidateSpy).not.toHaveBeenCalled()
872
+
873
+ // Pod in shop invalidates only shop/web, not billing/ledger.
874
+ invalidator.handleEvent(client, {
875
+ kind: 'Pod',
876
+ group: '',
877
+ namespace: 'shop',
878
+ name: 'web-1',
879
+ operation: 'update',
880
+ })
881
+ expect(invalidateSpy).toHaveBeenCalledTimes(1)
882
+ expect(invalidateSpy).toHaveBeenCalledWith(
883
+ {
884
+ queryKey: ['workload-source', getApiBase(), 'deployments', 'shop', 'web'],
885
+ },
886
+ { cancelRefetch: false },
887
+ )
888
+
889
+ // A different Deployment in billing does not invalidate billing/ledger.
890
+ invalidator.handleEvent(client, {
891
+ kind: 'Deployment',
892
+ group: 'apps',
893
+ namespace: 'billing',
894
+ name: 'invoicer',
895
+ operation: 'update',
896
+ })
897
+ expect(invalidateSpy).toHaveBeenCalledTimes(1)
898
+
899
+ // Unrelated kinds and wrong API groups do not invalidate anything.
900
+ for (const event of [
901
+ { kind: 'ConfigMap', group: '', namespace: 'shop', name: 'cfg', operation: 'update' as const },
902
+ { kind: 'PodMetrics', group: 'metrics.k8s.io', namespace: 'shop', name: 'web-1', operation: 'update' as const },
903
+ { kind: 'Application', group: 'app.k8s.io', namespace: 'argocd', name: 'web', operation: 'update' as const },
904
+ { kind: 'Kustomization', group: 'kustomize.config.k8s.io', namespace: 'flux-system', name: 'web', operation: 'update' as const },
905
+ { kind: 'HelmChart', group: 'helm.cattle.io', namespace: 'kube-system', name: 'traefik', operation: 'update' as const },
906
+ { kind: 'Bucket', group: 's3.aws.upbound.io', namespace: 'shop', name: 'assets', operation: 'update' as const },
907
+ { kind: 'ArtifactGenerator', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'gen', operation: 'update' as const },
908
+ ]) {
909
+ invalidator.handleEvent(client, event)
910
+ }
911
+ expect(invalidateSpy).toHaveBeenCalledTimes(1)
912
+
913
+ invalidator.reset()
914
+ })
915
+
916
+ it('invalidates workloads when GitOps managers or Flux sources change (even across namespaces)', () => {
917
+ seedSourceQuery('deployments', 'shop', 'web')
918
+ const invalidateSpy = vi.spyOn(client, 'invalidateQueries')
919
+ const invalidator = createWorkloadSourceInvalidator()
920
+
921
+ const gitopsEvents = [
922
+ { kind: 'Application', group: 'argoproj.io', namespace: 'argocd', name: 'shop-app', operation: 'update' as const },
923
+ { kind: 'Kustomization', group: 'kustomize.toolkit.fluxcd.io', namespace: 'flux-system', name: 'shop', operation: 'update' as const },
924
+ { kind: 'HelmRelease', group: 'helm.toolkit.fluxcd.io', namespace: 'flux-system', name: 'shop', operation: 'update' as const },
925
+ { kind: 'GitRepository', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'fleet', operation: 'update' as const },
926
+ { kind: 'OCIRepository', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'manifests', operation: 'update' as const },
927
+ { kind: 'Bucket', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'manifests-s3', operation: 'update' as const },
928
+ { kind: 'HelmRepository', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'charts', operation: 'update' as const },
929
+ { kind: 'HelmChart', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'shop-chart', operation: 'update' as const },
930
+ { kind: 'ExternalArtifact', group: 'source.toolkit.fluxcd.io', namespace: 'flux-system', name: 'ext-art', operation: 'update' as const },
931
+ { kind: 'ArtifactGenerator', group: 'source.extensions.fluxcd.io', namespace: 'flux-system', name: 'gen', operation: 'update' as const },
932
+ ]
933
+
934
+ for (const [idx, event] of gitopsEvents.entries()) {
935
+ expect(workloadSourceInvalidationScope(event)).toEqual({ scope: 'all' })
936
+ invalidator.handleEvent(client, event)
937
+ expect(invalidateSpy).toHaveBeenCalledTimes(idx + 1)
938
+ vi.advanceTimersByTime(WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS)
939
+ }
940
+
941
+ invalidator.reset()
942
+ })
943
+
944
+ it('cancels pending trailing invalidations on reset (context switch / unmount)', () => {
945
+ seedSourceQuery('deployments', 'shop', 'web')
946
+ const invalidateSpy = vi.spyOn(client, 'invalidateQueries')
947
+ const invalidator = createWorkloadSourceInvalidator()
948
+
949
+ invalidator.handleEvent(client, {
950
+ kind: 'Pod',
951
+ group: '',
952
+ namespace: 'shop',
953
+ name: 'web-1',
954
+ operation: 'update',
955
+ })
956
+ vi.advanceTimersByTime(1_000)
957
+ invalidator.handleEvent(client, {
958
+ kind: 'Pod',
959
+ group: '',
960
+ namespace: 'shop',
961
+ name: 'web-2',
962
+ operation: 'update',
963
+ })
964
+ expect(invalidateSpy).toHaveBeenCalledTimes(1)
965
+
966
+ invalidator.reset()
967
+ vi.advanceTimersByTime(WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS * 2)
968
+ expect(invalidateSpy).toHaveBeenCalledTimes(1)
969
+ })
970
+ })
971
+
972
+ describe('useWorkloadSources', () => {
973
+ let element: HTMLDivElement
974
+ let root: ReturnType<typeof createRoot>
975
+ let client: QueryClient
976
+ const targets = [
977
+ { kind: 'Deployment', group: 'apps', namespace: 'staging', name: 'api' },
978
+ { kind: 'Deployment', group: 'apps', namespace: 'prod', name: 'api' },
979
+ ]
980
+
981
+ beforeEach(() => {
982
+ host.radarVersion = 'v1.20.0'
983
+ element = document.createElement('div')
984
+ root = createRoot(element)
985
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, retryDelay: 0 } } })
986
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
987
+ client.setQueryData(['version-check', getApiBase()], {})
988
+ })
989
+
990
+ afterEach(async () => {
991
+ await act(async () => root.unmount())
992
+ client.clear()
993
+ vi.unstubAllGlobals()
994
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
995
+ })
996
+
997
+ function Probe() {
998
+ const reads = useWorkloadSources(targets)
999
+ return (
1000
+ <div data-reads>
1001
+ {JSON.stringify(
1002
+ reads
1003
+ ? targets.map((t) => {
1004
+ const r = reads.get(workloadSourceTargetKey(t))
1005
+ if (!r) return null
1006
+ if (r.status === 'unreadable') return `unreadable:${r.denied}`
1007
+ if (r.status === 'ready') return r.stale ? 'ready:stale' : 'ready'
1008
+ return r.status
1009
+ })
1010
+ : null,
1011
+ )}
1012
+ </div>
1013
+ )
1014
+ }
1015
+
1016
+ it('reads each workload, reports a refusal as denied, and keeps out of the per-Pod invalidation keys', async () => {
1017
+ vi.stubGlobal('fetch', vi.fn((input: RequestInfo | URL) => {
1018
+ const url = String(input)
1019
+ if (url.endsWith('/workloads/deployments/staging/api/source')) {
1020
+ return Promise.resolve(Response.json({ workload: targets[0], observedAt: '2026-11-29T00:00:00Z', images: [] }))
1021
+ }
1022
+ if (url.endsWith('/workloads/deployments/prod/api/source')) {
1023
+ return Promise.resolve(Response.json({ error: 'no access to pods in namespace prod' }, { status: 403 }))
1024
+ }
1025
+ return new Promise<Response>(() => {})
1026
+ }))
1027
+ await act(async () => {
1028
+ root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>)
1029
+ })
1030
+ await vi.waitFor(() => expect(element.querySelector('[data-reads]')?.textContent).toBe('["ready","unreadable:true"]'))
1031
+ expect(client.getQueryCache().findAll({ queryKey: ['workload-source'] })).toHaveLength(0)
1032
+ expect(client.getQueryCache().findAll({ queryKey: ['app-workload-source'] })).toHaveLength(2)
1033
+ })
1034
+
1035
+ it.each([
1036
+ [401, false],
1037
+ [403, true],
1038
+ [404, false],
1039
+ ])('drops cached source data on refresh %i', async (status, expectedDenied) => {
1040
+ let phase: 'initial' | 'refresh' = 'initial'
1041
+ vi.stubGlobal('fetch', vi.fn((input: RequestInfo | URL) => {
1042
+ const url = String(input)
1043
+ if (url.endsWith('/workloads/deployments/staging/api/source')) {
1044
+ if (phase === 'refresh') {
1045
+ return Promise.resolve(Response.json({ error: `status ${status}` }, { status }))
1046
+ }
1047
+ return Promise.resolve(Response.json({ workload: targets[0], observedAt: '2026-11-29T00:00:00Z', images: [] }))
1048
+ }
1049
+ if (url.endsWith('/workloads/deployments/prod/api/source')) {
1050
+ return Promise.resolve(Response.json({ workload: targets[1], observedAt: '2026-11-29T00:00:00Z', images: [] }))
1051
+ }
1052
+ return new Promise<Response>(() => {})
1053
+ }))
1054
+
1055
+ await act(async () => {
1056
+ root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>)
1057
+ })
1058
+ await vi.waitFor(() => expect(element.querySelector('[data-reads]')?.textContent).toBe('["ready","ready"]'))
1059
+
1060
+ phase = 'refresh'
1061
+ await act(async () => {
1062
+ await client.invalidateQueries({ queryKey: ['app-workload-source'] })
1063
+ })
1064
+ await vi.waitFor(() =>
1065
+ expect(element.querySelector('[data-reads]')?.textContent).toBe(`["unreadable:${expectedDenied}","ready"]`),
1066
+ )
1067
+ })
1068
+
1069
+ it('keeps cached source data as stale on transient 5xx and network errors', async () => {
1070
+ let phase: 'initial' | 'refresh' = 'initial'
1071
+ vi.stubGlobal('fetch', vi.fn((input: RequestInfo | URL) => {
1072
+ const url = String(input)
1073
+ if (url.endsWith('/workloads/deployments/staging/api/source')) {
1074
+ if (phase === 'refresh') {
1075
+ return Promise.resolve(Response.json({ error: 'upstream unavailable' }, { status: 503 }))
1076
+ }
1077
+ return Promise.resolve(Response.json({ workload: targets[0], observedAt: '2026-11-29T00:00:00Z', images: [] }))
1078
+ }
1079
+ if (url.endsWith('/workloads/deployments/prod/api/source')) {
1080
+ if (phase === 'refresh') {
1081
+ return Promise.reject(new TypeError('Failed to fetch'))
1082
+ }
1083
+ return Promise.resolve(Response.json({ workload: targets[1], observedAt: '2026-11-29T00:00:00Z', images: [] }))
1084
+ }
1085
+ return new Promise<Response>(() => {})
1086
+ }))
1087
+
1088
+ await act(async () => {
1089
+ root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>)
1090
+ })
1091
+ await vi.waitFor(() => expect(element.querySelector('[data-reads]')?.textContent).toBe('["ready","ready"]'))
1092
+
1093
+ phase = 'refresh'
1094
+ await act(async () => {
1095
+ await client.invalidateQueries({ queryKey: ['app-workload-source'] })
1096
+ })
1097
+ await vi.waitFor(() =>
1098
+ expect(element.querySelector('[data-reads]')?.textContent).toBe('["ready:stale","ready:stale"]'),
1099
+ )
1100
+ })
1101
+
1102
+ it('evicts cached source on 403 so a later 500 cannot resurrect forbidden data (200 -> 403 -> 500)', async () => {
1103
+ let stagingStatus: 200 | 403 | 500 = 200
1104
+ vi.stubGlobal('fetch', vi.fn((input: RequestInfo | URL) => {
1105
+ const url = String(input)
1106
+ if (url.endsWith('/workloads/deployments/staging/api/source')) {
1107
+ if (stagingStatus === 200) {
1108
+ return Promise.resolve(Response.json({ workload: targets[0], observedAt: '2026-11-29T00:00:00Z', images: [] }))
1109
+ }
1110
+ return Promise.resolve(Response.json({ error: `status ${stagingStatus}` }, { status: stagingStatus }))
1111
+ }
1112
+ if (url.endsWith('/workloads/deployments/prod/api/source')) {
1113
+ return Promise.resolve(Response.json({ workload: targets[1], observedAt: '2026-11-29T00:00:00Z', images: [] }))
1114
+ }
1115
+ return new Promise<Response>(() => {})
1116
+ }))
1117
+
1118
+ await act(async () => {
1119
+ root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>)
1120
+ })
1121
+ await vi.waitFor(() => expect(element.querySelector('[data-reads]')?.textContent).toBe('["ready","ready"]'))
1122
+
1123
+ stagingStatus = 403
1124
+ await act(async () => {
1125
+ await client.invalidateQueries({ queryKey: ['app-workload-source'] })
1126
+ })
1127
+ await vi.waitFor(() =>
1128
+ expect(element.querySelector('[data-reads]')?.textContent).toBe('["unreadable:true","ready"]'),
1129
+ )
1130
+
1131
+ stagingStatus = 500
1132
+ await act(async () => {
1133
+ await client.invalidateQueries({ queryKey: ['app-workload-source'] })
1134
+ })
1135
+ await vi.waitFor(() =>
1136
+ expect(element.querySelector('[data-reads]')?.textContent).toBe('["unreadable:false","ready"]'),
1137
+ )
1138
+ })
1139
+
1140
+ it('does not fetch while workloadSource support is unknown, and fetches once capabilities report supported', async () => {
1141
+ client.removeQueries({ queryKey: ['capabilities'] })
1142
+ const fetched: string[] = []
1143
+ vi.stubGlobal('fetch', vi.fn((input: RequestInfo | URL) => {
1144
+ const url = String(input)
1145
+ fetched.push(url)
1146
+ if (url.endsWith('/workloads/deployments/staging/api/source')) {
1147
+ return Promise.resolve(Response.json({ workload: targets[0], observedAt: '2026-11-29T00:00:00Z', images: [] }))
1148
+ }
1149
+ if (url.endsWith('/workloads/deployments/prod/api/source')) {
1150
+ return Promise.resolve(Response.json({ workload: targets[1], observedAt: '2026-11-29T00:00:00Z', images: [] }))
1151
+ }
1152
+ return new Promise<Response>(() => {})
1153
+ }))
1154
+
1155
+ await act(async () => {
1156
+ root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>)
1157
+ })
1158
+ await act(async () => {
1159
+ await new Promise((resolve) => setTimeout(resolve, 0))
1160
+ })
1161
+ expect(fetched.filter((u) => u.includes('/source'))).toEqual([])
1162
+ expect(element.querySelector('[data-reads]')?.textContent).toBe('null')
1163
+
1164
+ await act(async () => {
1165
+ client.setQueryData(['capabilities'], { features: { workloadSource: true } })
1166
+ })
1167
+ await vi.waitFor(() =>
1168
+ expect(element.querySelector('[data-reads]')?.textContent).toBe('["ready","ready"]'),
1169
+ )
1170
+ expect(fetched.filter((u) => u.includes('/source'))).toHaveLength(2)
1171
+ })
1172
+ })