@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
@@ -1,13 +1,12 @@
1
- import { useLayoutEffect, useState, type ReactNode } from 'react'
1
+ import { useId, useLayoutEffect, useState, type ReactNode } from 'react'
2
2
  import { AlertTriangle } from 'lucide-react'
3
- import { pluralize } from '@skyhook-io/k8s-ui'
3
+ import { DialogPortal, pluralize } from '@skyhook-io/k8s-ui'
4
4
  import { useSwitchContext, fetchSessionCounts, SwitchContextError, type SessionCounts } from '../api/client'
5
5
  import { finishSwitch, followSwitch, followingSwitch, switchInProgress, useTrackedContextSwitch } from '../api/contextSwitch'
6
6
  import { useConnection } from '../context/ConnectionContext'
7
7
  import { useContextSwitch } from '../context/ContextSwitchContext'
8
8
  import { useToast } from './ui/Toast'
9
9
  import { Tooltip } from './ui/Tooltip'
10
- import { useDock } from './dock'
11
10
  import type { ContextInfo, SelectedResource } from '../types'
12
11
  import { parseContextForSwitcher } from '../utils/context-name'
13
12
 
@@ -36,8 +35,10 @@ export function useContextSwitchFlow() {
36
35
  const switchContext = useSwitchContext()
37
36
  const { isSwitching, startSwitch, endSwitch, setOpenAfterSwitch, setFailedSwitch } = useContextSwitch()
38
37
  const { showError } = useToast()
39
- const { tabs } = useDock()
40
38
  const [pending, setPending] = useState<PendingSwitch | null>(null)
39
+ // Separate from `pending`, which the dialog keeps showing while it animates out.
40
+ const [confirming, setConfirming] = useState(false)
41
+ const titleId = useId()
41
42
  const [sessionCounts, setSessionCounts] = useState<SessionCounts | null>(null)
42
43
 
43
44
  const performSwitch = async ({ context, openAfter }: PendingSwitch) => {
@@ -74,15 +75,15 @@ export function useContextSwitchFlow() {
74
75
  setFailedSwitch(null)
75
76
  return
76
77
  }
77
- // Active sessions (port forwards from API + terminal tabs from dock) get
78
- // a confirmation prompt — switching contexts kills both.
78
+ // A switch ends the connection's port forwards and Pod and node terminals,
79
+ // so live ones get a confirmation. Local host terminals survive it.
79
80
  try {
80
81
  const counts = await fetchSessionCounts()
81
- const terminalTabs = tabs.filter(t => t.type === 'terminal').length
82
- const total = counts.portForwards + terminalTabs
82
+ const total = counts.portForwards + counts.execSessions
83
83
  if (total > 0) {
84
- setSessionCounts({ ...counts, execSessions: terminalTabs, total })
84
+ setSessionCounts({ ...counts, total })
85
85
  setPending({ context, openAfter })
86
+ setConfirming(true)
86
87
  return
87
88
  }
88
89
  } catch (error) {
@@ -99,21 +100,18 @@ export function useContextSwitchFlow() {
99
100
  }
100
101
 
101
102
  const confirm = () => {
102
- if (pending) performSwitch(pending)
103
- setPending(null)
103
+ if (confirming && pending) performSwitch(pending)
104
+ setConfirming(false)
104
105
  }
105
106
 
106
- const cancel = () => {
107
- setPending(null)
108
- setSessionCounts(null)
109
- }
107
+ const cancel = () => setConfirming(false)
110
108
 
111
- const confirmDialog: ReactNode = pending && sessionCounts ? (
112
- <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50">
113
- <div className="bg-theme-surface border border-theme-border rounded-lg shadow-xl max-w-md mx-4 overflow-hidden">
109
+ const confirmDialog: ReactNode = (
110
+ <DialogPortal open={confirming} onClose={cancel} className="w-full max-w-md" ariaLabelledBy={titleId}>
111
+ {pending && sessionCounts && <>
114
112
  <div className="px-4 py-3 border-b border-theme-border flex items-center gap-2">
115
113
  <AlertTriangle className="w-5 h-5 text-amber-400" />
116
- <span className="font-medium text-theme-text-primary">Active Sessions</span>
114
+ <h2 id={titleId} className="font-medium text-theme-text-primary">Active Sessions</h2>
117
115
  </div>
118
116
  <div className="px-4 py-4">
119
117
  <p className="text-sm text-theme-text-secondary mb-3">
@@ -154,9 +152,9 @@ export function useContextSwitchFlow() {
154
152
  Switch Anyway
155
153
  </button>
156
154
  </div>
157
- </div>
158
- </div>
159
- ) : null
155
+ </>}
156
+ </DialogPortal>
157
+ )
160
158
 
161
159
  return {
162
160
  requestSwitch,
@@ -10,6 +10,7 @@ import { workloadPodAwaitsScheduling } from '../capacity/podDemandGate'
10
10
  import { Stethoscope } from 'lucide-react'
11
11
  import {
12
12
  WorkloadView as BaseWorkloadView,
13
+ WorkloadSourceSection,
13
14
  EditableYamlView,
14
15
  FetchResult,
15
16
  Section,
@@ -113,11 +114,19 @@ import { RightsizingStrip } from '../resource/RightsizingStrip'
113
114
  import { PrometheusChartsGrid } from '../resource/PrometheusChartsGrid'
114
115
  import { DatadogSetupHint, DatadogWorkloadCharts, useDatadogWorkloadCharts, WorkloadCostRightsizing } from '../resource/DatadogWorkloadCharts'
115
116
  import { PodDebugAction, usePodDetailAccess, type PodDebugTarget } from '../resources/PodDebugAction'
117
+ import { PodEvictAction, podEvictAccessKey, type PodEvictTarget } from '../resources/PodEvictAction'
116
118
  import { useNavCustomization } from '../../context/NavCustomization'
117
119
  import { RestartEventLane } from '../resource/RestartChart'
118
120
  import { WorkloadCostTab } from '../cost/WorkloadCostTab'
119
121
  import { isOpenCostWorkloadKind } from '../cost/kinds'
120
122
  import { isRadarFeatureUnsupported } from '../../api/radarFeatures'
123
+ import { useResourceActionAdapter } from '../../api/resourceActions'
124
+ import { getApiBase } from '../../api/config'
125
+ import {
126
+ supportsWorkloadSource,
127
+ toWorkloadSourceState,
128
+ useWorkloadSource,
129
+ } from '../../api/workloadSource'
121
130
  import { useTrafficAvailable } from '../../api/traffic'
122
131
  import { useIssueExpansion, useIssueRowNotes } from '../issues/useIssueExpansion'
123
132
  import { isNotFoundError, useResourceAudit, useResourceIssues, useSubjectIssues, useRadarFeature, useTrace, fetchTraceWithProbes, fetchInClusterCapability, runInClusterMerged } from '../../api/client'
@@ -343,7 +352,8 @@ function useActionsBarProps(
343
352
  group: string | undefined,
344
353
  cascadeEnabled: boolean,
345
354
  nodeUID: string,
346
- pod?: PodDebugTarget,
355
+ pod?: PodDebugTarget & PodEvictTarget,
356
+ podEvictEnabled = true,
347
357
  ) {
348
358
  const [deletePreviewOpen, setDeletePreviewOpen] = useState(false)
349
359
  const { showCopied } = useToast()
@@ -362,6 +372,7 @@ function useActionsBarProps(
362
372
  const showPortForward = canPortForward || !isLocal
363
373
 
364
374
  const deleteMutation = useDeleteResource()
375
+ const resourceActionAdapter = useResourceActionAdapter()
365
376
  const restartWorkloadMutation = useRestartWorkload()
366
377
  const pauseDeploymentMutation = usePauseDeployment()
367
378
  const resumeDeploymentMutation = useResumeDeployment()
@@ -392,8 +403,13 @@ function useActionsBarProps(
392
403
  const { support: replicaSetLogSupport } = useRadarFeature('replicaSetLogs')
393
404
  const isAppsReplicaSet = kind === 'replicasets' && group === 'apps'
394
405
  const { support: deploymentPauseSupport } = useRadarFeature('deploymentPause')
406
+ const deploymentPauseAvailable =
407
+ deploymentPauseSupport === 'supported' ||
408
+ (resourceActionAdapter.support === 'supported' &&
409
+ resourceActionAdapter.supportsAction('apps/Deployment/pause') &&
410
+ resourceActionAdapter.supportsAction('apps/Deployment/resume'))
395
411
  const canPauseDeployments = !workloadWritesPending &&
396
- canPauseDeployment({ name: kind, group }, workloadWrites, deploymentPauseSupport === 'supported')
412
+ canPauseDeployment({ name: kind, group }, workloadWrites, deploymentPauseAvailable)
397
413
  const cronJobPermissionsReady = kind === 'cronjobs' && group === 'batch' && !workloadWritesPending
398
414
  const allowCronJobTrigger = cronJobPermissionsReady && canTriggerCronJob(workloadWrites)
399
415
  const allowCronJobSuspend = cronJobPermissionsReady && canSuspendCronJob(workloadWrites)
@@ -457,6 +473,7 @@ function useActionsBarProps(
457
473
  canPortForward: showPortForward,
458
474
  onOpenTerminal: openTerminal,
459
475
  podDebugAction: pod && <PodDebugAction key={pod.metadata.uid} pod={pod} defaultImage={debugImage} unverifiedReview={unverifiedReview} debugDenial={debugDenial} reviewStatus={reviewStatus} />,
476
+ podEvictAction: pod && <PodEvictAction pod={pod} adapter={resourceActionAdapter} enabled={podEvictEnabled} />,
460
477
  onOpenLogs: openLogs,
461
478
  onOpenWorkloadLogs: openWorkloadLogs,
462
479
  replicaSetLogs: isAppsReplicaSet && replicaSetLogSupport === 'supported',
@@ -496,6 +513,7 @@ function useActionsBarProps(
496
513
  restartWorkloadMutation.mutate(params)
497
514
  : undefined,
498
515
  isRestarting: restartWorkloadMutation.isPending,
516
+ resourceActionAdapter,
499
517
  onPauseDeployment: canPauseDeployments
500
518
  ? (params: Parameters<typeof pauseDeploymentMutation.mutate>[0]) =>
501
519
  pauseDeploymentMutation.mutate(params)
@@ -728,6 +746,7 @@ export function WorkloadView({
728
746
  ...(apiKind === 'pods' && !effectiveGroup && resource?.metadata?.uid ? [
729
747
  queryClient.invalidateQueries({queryKey: ['capabilities', namespace], exact: true}),
730
748
  queryClient.invalidateQueries({queryKey: podDebugAccessKey(namespace, name, resource.metadata.uid)}),
749
+ queryClient.invalidateQueries({queryKey: podEvictAccessKey(namespace, name, resource.metadata.uid)}),
731
750
  ] : []),
732
751
  ...(apiKind === 'rayjobs' && effectiveGroup === 'ray.io' ? [
733
752
  queryClient.refetchQueries({ queryKey: ['resource', 'jobs', namespace, name, 'batch'], type: 'active' }),
@@ -741,6 +760,10 @@ export function WorkloadView({
741
760
  queryKey: ['workload-pods', apiKind, namespace, name],
742
761
  ...(apiKind === 'rayclusters' ? { type: 'active' as const } : {}),
743
762
  }),
763
+ queryClient.refetchQueries({
764
+ queryKey: ['workload-source', getApiBase(), apiKind.toLowerCase(), namespace, name],
765
+ type: 'active',
766
+ }),
744
767
  ])
745
768
  }, [apiKind, effectiveGroup, name, namespace, queryClient, refetchResource, resource?.metadata?.uid, resource?.spec?.clusterSelector, onRefresh])
746
769
  const podWorkloadOwner = useMemo(
@@ -936,7 +959,8 @@ export function WorkloadView({
936
959
  effectiveGroup,
937
960
  !resourceLoading && Boolean(resource),
938
961
  apiKind === 'nodes' && !effectiveGroup ? resource?.metadata?.uid ?? '' : '',
939
- apiKind === 'pods' && resource?.apiVersion === 'v1' && resource?.kind === 'Pod' ? resource : undefined,
962
+ apiKind === 'pods' && !effectiveGroup && resource?.apiVersion === 'v1' && resource?.kind === 'Pod' && resource?.metadata?.namespace === namespace && resource?.metadata?.name === name ? resource : undefined,
963
+ rest.active !== false && !resourceLoading && !isNotFoundError(resourceError),
940
964
  )
941
965
  const desktopDownload = useDesktopDownload()
942
966
 
@@ -1276,8 +1300,52 @@ export function WorkloadView({
1276
1300
  [],
1277
1301
  )
1278
1302
 
1303
+ const drawerScopeKey = `${apiKind}|${namespace}|${name}|${rest.initialTab ?? 'detail'}`
1304
+ const [drawerViewState, setDrawerViewState] = useState<{
1305
+ scope: string
1306
+ view: 'overview' | 'yaml' | 'spec'
1307
+ }>(() => ({
1308
+ scope: drawerScopeKey,
1309
+ view: rest.initialTab === 'yaml' ? 'yaml' : 'overview',
1310
+ }))
1311
+ const drawerView: 'overview' | 'yaml' | 'spec' =
1312
+ drawerViewState.scope === drawerScopeKey
1313
+ ? drawerViewState.view
1314
+ : rest.initialTab === 'yaml'
1315
+ ? 'yaml'
1316
+ : 'overview'
1317
+ const handleDrawerViewChange = useCallback(
1318
+ (view: 'overview' | 'yaml' | 'spec') => {
1319
+ setDrawerViewState({ scope: drawerScopeKey, view })
1320
+ },
1321
+ [drawerScopeKey],
1322
+ )
1323
+
1279
1324
  const supportsWorkloadPods = ['deployments', 'statefulsets', 'daemonsets', 'rollouts'].includes(apiKind)
1280
1325
  const workloadPodsQuery = useWorkloadPods(supportsWorkloadPods ? apiKind : '', namespace, name)
1326
+ const workloadSourceSupported = Boolean(namespace) && supportsWorkloadSource(apiKind, effectiveGroup)
1327
+ const workloadSourceVisible = expanded ? migratedTab === 'overview' : drawerView === 'overview'
1328
+ const workloadSourceEnabled =
1329
+ workloadSourceSupported &&
1330
+ Boolean(resource) &&
1331
+ rest.active !== false &&
1332
+ !isNotFoundError(resourceError) &&
1333
+ workloadSourceVisible
1334
+ const workloadSourceUid =
1335
+ typeof resource?.metadata?.uid === 'string' && resource.metadata.uid ? resource.metadata.uid : undefined
1336
+ const workloadSourceQuery = useWorkloadSource(
1337
+ apiKind,
1338
+ namespace,
1339
+ name,
1340
+ workloadSourceEnabled,
1341
+ workloadSourceUid,
1342
+ )
1343
+ const workloadSource =
1344
+ workloadSourceSupported &&
1345
+ !isNotFoundError(resourceError) &&
1346
+ (workloadSourceEnabled || workloadSourceQuery.data || workloadSourceQuery.cachedData)
1347
+ ? toWorkloadSourceState(workloadSourceQuery)
1348
+ : undefined
1281
1349
  const workloadAwaitsCapacity =
1282
1350
  karpenter?.state === 'available' &&
1283
1351
  (workloadPodsQuery.data?.pods ?? []).some(workloadPodAwaitsScheduling)
@@ -1343,6 +1411,7 @@ export function WorkloadView({
1343
1411
  }
1344
1412
  workloadPodsLoading={supportsWorkloadPods ? workloadPodsQuery.isLoading : false}
1345
1413
  workloadPodsError={supportsWorkloadPods ? (workloadPodsQuery.error as Error | null) : null}
1414
+ workloadSource={workloadSource}
1346
1415
  servingResources={servingResources}
1347
1416
  renderServicePortAction={renderServicePortAction}
1348
1417
  renderServicePortPanel={renderServicePortPanel}
@@ -1385,6 +1454,7 @@ export function WorkloadView({
1385
1454
  activeTab={migratedTab}
1386
1455
  extraTabsComplete={migratedTab === 'deploys' ? true : undefined}
1387
1456
  onTabChange={handleTabChange}
1457
+ onDrawerViewChange={handleDrawerViewChange}
1388
1458
  // Render props
1389
1459
  renderLogsTab={(props) => (
1390
1460
  <LogsTabContent
@@ -1410,7 +1480,16 @@ export function WorkloadView({
1410
1480
  name={n}
1411
1481
  resource={res}
1412
1482
  selectedRunKey={selectedRunKey}
1413
- leadContent={leadContent}
1483
+ leadContent={
1484
+ workloadSource ? (
1485
+ <>
1486
+ {leadContent}
1487
+ <WorkloadSourceSection state={workloadSource} variant="card" />
1488
+ </>
1489
+ ) : (
1490
+ leadContent
1491
+ )
1492
+ }
1414
1493
  canViewLogs={baseActionsBarProps.canViewLogs}
1415
1494
  onSelectRun={handleSelectedRunChange}
1416
1495
  onSwitchToLogs={() => handleTabChange('logs')}
@@ -0,0 +1,121 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { MemoryRouter } from 'react-router-dom'
5
+ import { onlineManager, QueryClient, QueryClientProvider } from '@tanstack/react-query'
6
+ import { DockProvider, ToastProvider } from '@skyhook-io/k8s-ui'
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
8
+ import * as workloadSourceApi from '../../api/workloadSource'
9
+ import { WorkloadView } from './WorkloadView'
10
+
11
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
12
+
13
+ const DEPLOYMENT = {
14
+ apiVersion: 'apps/v1',
15
+ kind: 'Deployment',
16
+ metadata: { namespace: 'shop', name: 'web', uid: 'uid-web-1' },
17
+ spec: {
18
+ replicas: 1,
19
+ template: { spec: { containers: [{ name: 'web', image: 'ghcr.io/skyhook-io/web:v1' }] } },
20
+ },
21
+ status: { readyReplicas: 1, replicas: 1 },
22
+ }
23
+
24
+ describe('WorkloadView workloadSource query gating', () => {
25
+ let host: HTMLDivElement
26
+ let root: ReturnType<typeof createRoot>
27
+ let client: QueryClient
28
+ let wasOnline: boolean
29
+ let hookSpy: ReturnType<typeof vi.spyOn>
30
+
31
+ beforeEach(() => {
32
+ host = document.createElement('div')
33
+ document.body.appendChild(host)
34
+ root = createRoot(host)
35
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
36
+ client.setQueryData(['resource', 'deployments', 'shop', 'web', 'apps'], {
37
+ resource: DEPLOYMENT,
38
+ })
39
+ wasOnline = onlineManager.isOnline()
40
+ onlineManager.setOnline(false)
41
+ hookSpy = vi.spyOn(workloadSourceApi, 'useWorkloadSource')
42
+ })
43
+
44
+ afterEach(() => {
45
+ act(() => root.unmount())
46
+ host.remove()
47
+ hookSpy.mockRestore()
48
+ client.clear()
49
+ onlineManager.setOnline(wasOnline)
50
+ })
51
+
52
+ function lastEnabledArg(): boolean | undefined {
53
+ const call = hookSpy.mock.calls.at(-1)
54
+ return call?.[3] as boolean | undefined
55
+ }
56
+
57
+ async function renderView(
58
+ props: Partial<React.ComponentProps<typeof WorkloadView>>,
59
+ initialEntry = '/resources/deployments',
60
+ ) {
61
+ await act(async () => {
62
+ root.render(
63
+ <QueryClientProvider client={client}>
64
+ <ToastProvider>
65
+ <DockProvider>
66
+ <MemoryRouter key={initialEntry} initialEntries={[initialEntry]}>
67
+ <WorkloadView
68
+ kind="deployments"
69
+ group="apps"
70
+ namespace="shop"
71
+ name="web"
72
+ onBack={() => {}}
73
+ {...props}
74
+ />
75
+ </MemoryRouter>
76
+ </DockProvider>
77
+ </ToastProvider>
78
+ </QueryClientProvider>,
79
+ )
80
+ })
81
+ }
82
+
83
+ it('enables workload source on drawer overview, disables on drawer YAML, and toggles with the YAML button', async () => {
84
+ // Drawer opened to overview (even if the background page URL carries ?tab=deploys).
85
+ await renderView({ expanded: false, initialTab: 'detail' }, '/applications?tab=deploys')
86
+ expect(lastEnabledArg()).toBe(true)
87
+
88
+ // Clicking the YAML toggle hides the overview and disables the query.
89
+ const yamlButton = [...host.querySelectorAll('button')].find((b) => b.textContent?.trim() === 'YAML')
90
+ expect(yamlButton).toBeDefined()
91
+ await act(async () => {
92
+ yamlButton!.click()
93
+ })
94
+ expect(lastEnabledArg()).toBe(false)
95
+
96
+ // Clicking YAML again returns to overview and re-enables the query.
97
+ await act(async () => {
98
+ yamlButton!.click()
99
+ })
100
+ expect(lastEnabledArg()).toBe(true)
101
+ })
102
+
103
+ it('does not enable workload source when the drawer opens directly to YAML', async () => {
104
+ await renderView({ expanded: false, initialTab: 'yaml' })
105
+ expect(hookSpy).toHaveBeenCalled()
106
+ for (const call of hookSpy.mock.calls) {
107
+ expect(call[3]).toBe(false)
108
+ }
109
+ })
110
+
111
+ it('enables workload source in expanded mode only on the overview tab', async () => {
112
+ await renderView({ expanded: true }, '/workload/deployments/shop/web')
113
+ expect(lastEnabledArg()).toBe(true)
114
+
115
+ await renderView({ expanded: true }, '/workload/deployments/shop/web?tab=yaml')
116
+ expect(lastEnabledArg()).toBe(false)
117
+
118
+ await renderView({ expanded: true }, '/workload/deployments/shop/web?tab=timeline')
119
+ expect(lastEnabledArg()).toBe(false)
120
+ })
121
+ })
@@ -23,6 +23,10 @@ export interface ConnectionState {
23
23
  // The connection Radar is serving (see connectionBinding.ts). Empty while a
24
24
  // switch is between connections; never sent by an in-cluster or older Radar.
25
25
  connectionId?: string
26
+ // Set while the serving connection's API server doesn't answer Radar's
27
+ // reachability checks (RFC 3339). The state stays 'connected' and the cache
28
+ // keeps serving its last state. Absent: reachable, or an older Radar.
29
+ apiUnreachableSince?: string
26
30
  // Per-kind readiness while the initial informer sync runs ('connecting'
27
31
  // with informers started). Drives the progressive app shell — absent once
28
32
  // connected or before informers exist.
@@ -46,7 +50,7 @@ interface ConnectionContextValue {
46
50
  contextSwitch?: ContextSwitchOperation
47
51
  retry: () => void
48
52
  isRetrying: boolean
49
- updateFromSSE: (status: ConnectionState) => void
53
+ updateFromSSE: (status: ConnectionState, opts?: { handover: boolean }) => void
50
54
  }
51
55
 
52
56
  class ConnectionRetryError extends Error {
@@ -301,7 +305,10 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
301
305
  data.state === 'connected' && data.contextSwitch?.phase === 'succeeded' && data.contextSwitch.target === data.context) {
302
306
  followSwitch(data.contextSwitch.id)
303
307
  }
304
- const becameConnected = current.state !== 'connected' && data.state === 'connected'
308
+ // The API server answering again is a reconnect for the data too: what the
309
+ // views fetched during the outage may have failed or gone stale.
310
+ const becameConnected = data.state === 'connected' &&
311
+ (current.state !== 'connected' || (Boolean(current.apiUnreachableSince) && !data.apiUnreachableSince))
305
312
  setConnection({
306
313
  state: data.state,
307
314
  context: data.context,
@@ -310,6 +317,8 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
310
317
  errorType: data.errorType,
311
318
  progressMessage: data.progressMessage,
312
319
  disconnectedAt: data.disconnectedAt,
320
+ connectionId: data.connectionId,
321
+ apiUnreachableSince: data.apiUnreachableSince,
313
322
  syncStatus: data.syncStatus,
314
323
  })
315
324
  if (becameConnected) {
@@ -354,7 +363,7 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
354
363
  const retryError = error as ConnectionRetryError
355
364
  if (retryError.status === 409) {
356
365
  if (attempt) setConnection(prev => prev === attempt.pendingConnection ? attempt.previousConnection : prev)
357
- if (retryError.code !== 'reconnect_superseded') showApiNotice('Cluster retry unavailable', error.message, 'info')
366
+ if (retryError.code !== 'reconnect_superseded' && retryError.code !== 'switch_stopped') showApiNotice('Cluster retry unavailable', error.message, 'info')
358
367
  return
359
368
  }
360
369
  setConnection(prev => {
@@ -514,13 +523,15 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
514
523
  }, [retryMutation])
515
524
 
516
525
  // Handler for SSE connection_state events
517
- const updateFromSSE = useCallback((status: ConnectionState) => {
526
+ const updateFromSSE = useCallback((status: ConnectionState, opts?: { handover: boolean }) => {
518
527
  // Feed the retry-race guards: a live SSE stream means retry failures must
519
528
  // not clobber a recovery it already delivered. The generation bump lets
520
529
  // in-flight polls detect they raced this frame.
521
530
  sseActiveRef.current = true
522
531
  sseGenerationRef.current += 1
523
532
  observeConnectionStatus(status)
533
+ const previous = connectionRef.current
534
+ const previousState = previous.state
524
535
  setConnection(prev => {
525
536
  // Don't transition back to 'connecting' from 'connected'. This happens when the
526
537
  // pod restarts and the SSE reconnects while the new pod's K8s cache is still
@@ -539,7 +550,15 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
539
550
  return status
540
551
  })
541
552
 
542
- if (status.state === 'connected') {
553
+ // A frame that only says the API server stopped answering is not a
554
+ // reconnect: refetching now would just fail against the dead endpoint.
555
+ const onlyLostReachability = status.state === 'connected' && Boolean(status.apiUnreachableSince) && previousState === 'connected'
556
+ // Neither is a stream replaced for new parameters while connected to the
557
+ // same, reachable connection: the old stream delivered until the new one
558
+ // started, so nothing was missed.
559
+ const handedOver = Boolean(opts?.handover) && status.state === 'connected' && previousState === 'connected'
560
+ && status.context === previous.context && status.connectionId === previous.connectionId && !previous.apiUnreachableSince
561
+ if (status.state === 'connected' && !onlyLostReachability && !handedOver) {
543
562
  refreshCachesOnConnect()
544
563
  }
545
564
  }, [refreshCachesOnConnect])
@@ -90,3 +90,17 @@ it('keeps the connection SSE delivered when an older poll resolves after it', as
90
90
  expect(latest()?.connection.context).toBe('B')
91
91
  expect(connectionHeaderValue()).toBe('n-2')
92
92
  })
93
+
94
+ // A stream handover counts as one only on the same connection, so a poll that
95
+ // dropped the ID would turn every later handover into a full refetch.
96
+ it('keeps the connection ID a status poll reports', async () => {
97
+ await act(async () => {
98
+ await vi.advanceTimersByTimeAsync(10)
99
+ })
100
+ await act(async () => {
101
+ polls[0](statusA)
102
+ await vi.advanceTimersByTimeAsync(10)
103
+ })
104
+ expect(latest()?.connection.state).toBe('connected')
105
+ expect(latest()?.connection.connectionId).toBe('n-1')
106
+ })
@@ -0,0 +1,94 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
6
+ import { ConnectionProvider, useConnection } from './ConnectionContext'
7
+ import { resetConnectionBindingForTest } from '../api/connectionBinding'
8
+ import type { ConnectionState } from './ConnectionContext'
9
+
10
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
11
+
12
+ let root: Root
13
+ let container: HTMLDivElement
14
+ let client: QueryClient
15
+ const seen = vi.fn<(value: ReturnType<typeof useConnection>) => void>()
16
+ const latest = () => seen.mock.lastCall![0]
17
+
18
+ function Probe() {
19
+ seen(useConnection())
20
+ return null
21
+ }
22
+
23
+ const connected = { state: 'connected', context: 'A', connectionId: 'n-1' } as ConnectionState
24
+
25
+ beforeEach(async () => {
26
+ vi.useFakeTimers()
27
+ seen.mockClear()
28
+ resetConnectionBindingForTest()
29
+ vi.stubGlobal('fetch', vi.fn(() => new Promise<Response>(() => {})))
30
+ container = document.createElement('div')
31
+ document.body.appendChild(container)
32
+ root = createRoot(container)
33
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
34
+ await act(async () => {
35
+ root.render(
36
+ <QueryClientProvider client={client}>
37
+ <ConnectionProvider>
38
+ <Probe />
39
+ </ConnectionProvider>
40
+ </QueryClientProvider>,
41
+ )
42
+ })
43
+ })
44
+
45
+ afterEach(() => {
46
+ act(() => root.unmount())
47
+ container.remove()
48
+ vi.restoreAllMocks()
49
+ vi.unstubAllGlobals()
50
+ vi.useRealTimers()
51
+ resetConnectionBindingForTest()
52
+ })
53
+
54
+ async function deliver(status: ConnectionState, handover: boolean) {
55
+ await act(async () => {
56
+ latest().updateFromSSE(status, { handover })
57
+ // Past the cache refresh's 1.5 s throttle, so each delivery is judged alone.
58
+ await vi.advanceTimersByTimeAsync(2_000)
59
+ })
60
+ }
61
+
62
+ it('a stream handed over while connected is not a reconnect, so queries are not all refetched', async () => {
63
+ await deliver(connected, false)
64
+ const invalidate = vi.spyOn(client, 'invalidateQueries')
65
+
66
+ await deliver(connected, true)
67
+ expect(invalidate).not.toHaveBeenCalled()
68
+ expect(latest().connection.state).toBe('connected')
69
+
70
+ // Control: the same frame on a reconnected stream does refetch.
71
+ await deliver(connected, false)
72
+ expect(invalidate).toHaveBeenCalled()
73
+ })
74
+
75
+ it('a handover that finds the connection recovering still refreshes', async () => {
76
+ await deliver(connected, false)
77
+ // A retry, not the stream, moves a connected tab back to connecting.
78
+ await act(async () => {
79
+ latest().retry()
80
+ await vi.advanceTimersByTimeAsync(10)
81
+ })
82
+ expect(latest().connection.state).toBe('connecting')
83
+ const invalidate = vi.spyOn(client, 'invalidateQueries')
84
+
85
+ await deliver(connected, true)
86
+ expect(invalidate).toHaveBeenCalled()
87
+ })
88
+
89
+ it('a handover that lands on a different connection still refreshes', async () => {
90
+ await deliver(connected, false)
91
+ const invalidate = vi.spyOn(client, 'invalidateQueries')
92
+ await deliver({ ...connected, connectionId: 'n-2' } as ConnectionState, true)
93
+ expect(invalidate).toHaveBeenCalled()
94
+ })
@@ -21,6 +21,21 @@ export type RenderInvestigationRunActions = (props: {
21
21
  onRunUpdated: (run: RunSummary) => void;
22
22
  }) => ReactNode;
23
23
 
24
+ /** Content after a run's assessment, evidence, and next steps. To open a
25
+ * linked item, call revealInFindings once when that exact element is mounted.
26
+ * Give the element a tabIndex of -1 so keyboard focus follows the link. */
27
+ export type RenderInvestigationFindingsFooter = (props: {
28
+ run: RunSummary;
29
+ revealInFindings: (element: HTMLElement) => void;
30
+ /** Reveals a unique recorded read in Findings or its original Activity entry.
31
+ * Missing or ambiguous evidence has no link. */
32
+ evidenceLink: (evidenceRef: string) => (() => void) | undefined;
33
+ /** Returns to the current assessment, when the transcript contains one. */
34
+ viewAssessment?: () => void;
35
+ /** Opens Activity and focuses its editable follow-up input, when available. */
36
+ askQuestion?: () => void;
37
+ }) => ReactNode;
38
+
24
39
  /** Host action beside a refused start or follow-up, e.g. Radar Cloud's
25
40
  * "Upgrade" when an organization has used its investigations. Called only for
26
41
  * refusals that carry a code, reason or action; return null to show none. */
@@ -73,6 +88,7 @@ export type DiagnoseConsentCopy = {
73
88
  export interface DiagnoseCustomization {
74
89
  renderAction: RenderDiagnoseAction | undefined;
75
90
  renderRunActions?: RenderInvestigationRunActions;
91
+ renderFindingsFooter?: RenderInvestigationFindingsFooter;
76
92
  renderRefusalAction?: RenderInvestigationRefusalAction;
77
93
  consentCopy: DiagnoseConsentCopy | undefined;
78
94
  // undefined = default (CustomEvent → Radar's own Settings dialog);
@@ -93,6 +109,7 @@ export function DiagnoseCustomizationProvider({
93
109
  value,
94
110
  consentCopy,
95
111
  renderRunActions,
112
+ renderFindingsFooter,
96
113
  renderRefusalAction,
97
114
  onOpenSettings,
98
115
  children,
@@ -100,6 +117,7 @@ export function DiagnoseCustomizationProvider({
100
117
  value: RenderDiagnoseAction | undefined;
101
118
  consentCopy?: DiagnoseConsentCopy;
102
119
  renderRunActions?: RenderInvestigationRunActions;
120
+ renderFindingsFooter?: RenderInvestigationFindingsFooter;
103
121
  renderRefusalAction?: RenderInvestigationRefusalAction;
104
122
  /** Where "AI settings" affordances lead. Omit for Radar's own Settings
105
123
  * dialog; pass `null` to hide them. */
@@ -107,8 +125,8 @@ export function DiagnoseCustomizationProvider({
107
125
  children: ReactNode;
108
126
  }) {
109
127
  const ctx = useMemo(
110
- () => ({ renderAction: value, consentCopy, onOpenSettings, renderRunActions, renderRefusalAction }),
111
- [value, consentCopy, onOpenSettings, renderRunActions, renderRefusalAction],
128
+ () => ({ renderAction: value, consentCopy, onOpenSettings, renderRunActions, renderFindingsFooter, renderRefusalAction }),
129
+ [value, consentCopy, onOpenSettings, renderRunActions, renderFindingsFooter, renderRefusalAction],
112
130
  );
113
131
  return (
114
132
  <DiagnoseCustomizationContext.Provider value={ctx}>