@skyhook-io/radar-app 1.22.1 → 1.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +96 -28
  3. package/src/RadarApp.tsx +5 -0
  4. package/src/api/client.ts +6 -1
  5. package/src/api/workloadSource.test.tsx +857 -0
  6. package/src/api/workloadSource.ts +292 -0
  7. package/src/components/APIUnreachableBanner.test.tsx +19 -0
  8. package/src/components/APIUnreachableBanner.tsx +20 -0
  9. package/src/components/ConnectionErrorView.test.tsx +63 -2
  10. package/src/components/ConnectionErrorView.tsx +88 -68
  11. package/src/components/diagnose/ActivityTurn.tsx +6 -4
  12. package/src/components/diagnose/AssessmentCard.tsx +1 -2
  13. package/src/components/diagnose/ContinueInAgentButton.test.tsx +7 -0
  14. package/src/components/diagnose/Home.test.tsx +6 -0
  15. package/src/components/diagnose/Home.tsx +10 -3
  16. package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +1 -1
  17. package/src/components/diagnose/InvestigationEvidencePane.tsx +19 -2
  18. package/src/components/diagnose/InvestigationFindingsFooter.test.tsx +413 -0
  19. package/src/components/diagnose/InvestigationView.tsx +120 -23
  20. package/src/components/diagnose/investigationEvidence/identity.test.ts +1 -1
  21. package/src/components/diagnose/investigationEvidence/projection.test.ts +1 -1
  22. package/src/components/diagnose/investigationState.ts +9 -0
  23. package/src/components/diagnose/parts.test.tsx +11 -3
  24. package/src/components/diagnose/toolCallLabel.ts +3 -0
  25. package/src/components/home/ActivitySummary.tsx +3 -8
  26. package/src/components/home/ClusterHealthCard.tsx +91 -17
  27. package/src/components/home/ClusterHealthCard.utilization.test.tsx +187 -0
  28. package/src/components/home/HomeView.tsx +6 -26
  29. package/src/components/home/TopologyPreview.test.tsx +31 -30
  30. package/src/components/home/TopologyPreview.tsx +19 -28
  31. package/src/components/home/mcpToolCatalog.ts +3 -3
  32. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +5 -4
  33. package/src/components/resources/renderers/RolloutRenderer.tsx +4 -1
  34. package/src/components/resources/renderers/WorkloadRenderer.tsx +4 -1
  35. package/src/components/workload/WorkloadView.tsx +67 -1
  36. package/src/components/workload/WorkloadView.workloadSource.test.tsx +121 -0
  37. package/src/context/ConnectionContext.tsx +24 -5
  38. package/src/context/ConnectionProvider.connectionId.test.tsx +14 -0
  39. package/src/context/ConnectionProvider.handover.test.tsx +94 -0
  40. package/src/context/DiagnoseCustomization.tsx +20 -2
  41. package/src/hooks/useEventSource.test.tsx +275 -4
  42. package/src/hooks/useEventSource.ts +278 -51
  43. package/src/index.ts +1 -0
  44. package/src/utils/navigation.test.ts +1 -6
  45. package/src/utils/navigation.ts +9 -44
  46. package/src/utils/network-policy-navigation.test.ts +21 -36
@@ -0,0 +1,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}>
@@ -9,8 +9,10 @@ class TestStream extends EventTarget {
9
9
  onopen?: () => void
10
10
  onerror?: () => void
11
11
  close = vi.fn()
12
- constructor() {
12
+ params: URLSearchParams
13
+ constructor(url: string) {
13
14
  super()
15
+ this.params = new URL(url, 'http://radar.test').searchParams
14
16
  TestStream.opened.push(this)
15
17
  }
16
18
  send(type: string, data: unknown) {
@@ -23,11 +25,14 @@ const hook = createRef<ReturnType<typeof useEventSource>>()
23
25
  const changed = vi.fn()
24
26
  const complete = vi.fn()
25
27
  const eventReceived = vi.fn()
26
- function Probe() {
27
- const result = useEventSource([], 'resources', { onContextChanged: changed, onContextSwitchComplete: complete, onK8sEvent: eventReceived })
28
+ const connectionState = vi.fn()
29
+ const deferredReady = vi.fn()
30
+ function Probe({ wantsTopology = true, viewMode = 'resources' as 'resources' | 'traffic', filter = undefined as string[] | undefined }) {
31
+ const result = useEventSource([], viewMode, { onContextChanged: changed, onContextSwitchComplete: complete, onK8sEvent: eventReceived, onConnectionStateChange: connectionState, onDeferredReady: deferredReady }, filter, false, wantsTopology)
28
32
  useImperativeHandle(hook, () => result, [result])
29
33
  return null
30
34
  }
35
+ const render = (props: Parameters<typeof Probe>[0]) => act(() => root.render(<Probe {...props} />))
31
36
 
32
37
  beforeEach(() => {
33
38
  vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
@@ -35,7 +40,7 @@ beforeEach(() => {
35
40
  TestStream.opened = []
36
41
  vi.clearAllMocks()
37
42
  root = createRoot(document.createElement('div'))
38
- act(() => root.render(<Probe />))
43
+ render({})
39
44
  })
40
45
  afterEach(() => {
41
46
  act(() => root.unmount())
@@ -83,3 +88,269 @@ test('an ordered stream completion keeps its target topology when the matching p
83
88
  expect(complete).toHaveBeenCalledOnce()
84
89
  expect(hook.current!.topology?.nodes[0].id).toBe('target')
85
90
  })
91
+
92
+ test('a tab asks for topology frames, and the view that shapes them, only while it draws the graph', () => {
93
+ expect(TestStream.opened[0].params.get('topology')).toBe('1')
94
+ render({ wantsTopology: false, viewMode: 'traffic' })
95
+ const off = TestStream.opened[1]
96
+ expect(off.params.has('topology')).toBe(false)
97
+ expect(off.params.has('view')).toBe(false)
98
+ render({ wantsTopology: true, viewMode: 'traffic' })
99
+ const on = TestStream.opened[2]
100
+ expect(on.params.get('topology')).toBe('1')
101
+ expect(on.params.get('view')).toBe('traffic')
102
+ })
103
+
104
+ test('status comes from topology_status, and its arrival ends a switch wait', () => {
105
+ render({ wantsTopology: false })
106
+ act(() => hook.current!.applyContextChange('target', 'op'))
107
+ expect(hook.current!.topologyStatus).toBeNull()
108
+ const stream = TestStream.opened.at(-1)!
109
+ act(() => stream.send('topology_status', { requiresNamespaceFilter: true, crdDiscoveryStatus: 'discovering' }))
110
+ expect(complete).toHaveBeenCalledOnce()
111
+ expect(hook.current!.topologyStatus).toEqual({ requiresNamespaceFilter: true, crdDiscoveryStatus: 'discovering' })
112
+ expect(hook.current!.topology).toBeNull()
113
+ })
114
+
115
+ test('an older Radar that sends every tab the graph feeds status and switch completion, not the graph', () => {
116
+ render({ wantsTopology: false })
117
+ act(() => hook.current!.applyContextChange('target', 'op'))
118
+ const stream = TestStream.opened.at(-1)!
119
+ act(() => stream.send('topology', { nodes: [{ id: 'unwanted' }], edges: [], requiresNamespaceFilter: true, crdDiscoveryStatus: 'ready' }))
120
+ expect(complete).toHaveBeenCalledOnce()
121
+ expect(hook.current!.topology).toBeNull()
122
+ expect(hook.current!.topologyStatus).toEqual({ requiresNamespaceFilter: true, crdDiscoveryStatus: 'ready' })
123
+ })
124
+
125
+ test('new parameters hand over: the old stream delivers until the new one starts, which is not a reconnect', () => {
126
+ const old = TestStream.opened[0]
127
+ act(() => old.send('connection_state', { state: 'connected', context: 'c' }))
128
+ expect(connectionState).toHaveBeenLastCalledWith({ state: 'connected', context: 'c' }, { handover: false })
129
+ render({ wantsTopology: false })
130
+ const next = TestStream.opened[1]
131
+ expect(old.close).not.toHaveBeenCalled()
132
+ act(() => old.send('k8s_event', { name: 'during-handover' }))
133
+ expect(eventReceived).toHaveBeenCalledOnce()
134
+ act(() => next.send('connection_state', { state: 'connected', context: 'c' }))
135
+ expect(connectionState).toHaveBeenLastCalledWith({ state: 'connected', context: 'c' }, { handover: true })
136
+ expect(hook.current!.connected).toBe(true)
137
+ })
138
+
139
+ // Old stream live, new parameters, new stream promoted: the old one drains.
140
+ function handOver() {
141
+ const old = TestStream.opened.at(-1)!
142
+ act(() => old.send('connection_state', { state: 'connected', context: 'c' }))
143
+ render({ wantsTopology: false })
144
+ const next = TestStream.opened.at(-1)!
145
+ act(() => next.send('connection_state', { state: 'connected', context: 'c' }))
146
+ return { old, next }
147
+ }
148
+
149
+ test('a change the old stream had queued before the new one subscribed still arrives; it closes once the new one reads', () => {
150
+ vi.useFakeTimers()
151
+ try {
152
+ const { old, next } = handOver()
153
+ act(() => old.send('k8s_event', { name: 'queued-behind-a-large-frame' }))
154
+ expect(eventReceived).toHaveBeenCalledOnce()
155
+ act(() => old.send('topology_status', { requiresNamespaceFilter: true }))
156
+ expect(hook.current!.topologyStatus?.requiresNamespaceFilter).not.toBe(true)
157
+ act(() => vi.advanceTimersByTime(3000))
158
+ // Still building its first frame: not yet reading its own changes.
159
+ expect(old.close).not.toHaveBeenCalled()
160
+ act(() => next.send('topology_status', { requiresNamespaceFilter: false }))
161
+ expect(old.close).toHaveBeenCalledOnce()
162
+ act(() => old.send('k8s_event', { name: 'after-close' }))
163
+ expect(eventReceived).toHaveBeenCalledOnce()
164
+ expect(connectionState).toHaveBeenLastCalledWith({ state: 'connected', context: 'c' }, { handover: true })
165
+ } finally {
166
+ vi.useRealTimers()
167
+ }
168
+ })
169
+
170
+ test('a drain whose new stream never starts reading ends as a reconnect', () => {
171
+ vi.useFakeTimers()
172
+ try {
173
+ const { old } = handOver()
174
+ act(() => vi.advanceTimersByTime(30_000))
175
+ expect(old.close).toHaveBeenCalledOnce()
176
+ expect(connectionState).toHaveBeenLastCalledWith({ state: 'connected', context: 'c' }, { handover: false })
177
+ } finally {
178
+ vi.useRealTimers()
179
+ }
180
+ })
181
+
182
+ test('an old stream that fails while draining ends as a reconnect', () => {
183
+ const { old } = handOver()
184
+ act(() => old.onerror?.())
185
+ expect(old.close).toHaveBeenCalled()
186
+ expect(connectionState).toHaveBeenLastCalledWith({ state: 'connected', context: 'c' }, { handover: false })
187
+ })
188
+
189
+ test('a second handover while the first still drains is not a handover', () => {
190
+ const { old, next } = handOver()
191
+ render({ wantsTopology: true })
192
+ const third = TestStream.opened.at(-1)!
193
+ act(() => third.send('connection_state', { state: 'connected', context: 'c' }))
194
+ expect(old.close).toHaveBeenCalled()
195
+ expect(next.close).toHaveBeenCalled()
196
+ expect(connectionState).toHaveBeenLastCalledWith({ state: 'connected', context: 'c' }, { handover: false })
197
+ })
198
+
199
+ test('deferred readiness counts from a draining stream', () => {
200
+ const { old } = handOver()
201
+ act(() => old.send('deferred_ready', {}))
202
+ expect(deferredReady).toHaveBeenCalledOnce()
203
+ })
204
+
205
+ test('a namespace filter change reconnects instead of handing over', () => {
206
+ const old = TestStream.opened[0]
207
+ act(() => old.send('connection_state', { state: 'connected', context: 'c' }))
208
+ render({ filter: ['shop'] })
209
+ expect(old.close).toHaveBeenCalled()
210
+ const next = TestStream.opened.at(-1)!
211
+ expect(next.params.get('namespaces')).toBe('shop')
212
+ act(() => next.send('connection_state', { state: 'connected', context: 'c' }))
213
+ expect(connectionState).toHaveBeenLastCalledWith({ state: 'connected', context: 'c' }, { handover: false })
214
+ })
215
+
216
+ test('a cluster switch that reaches only the draining stream reconnects', () => {
217
+ const old = TestStream.opened[0]
218
+ act(() => old.send('connection_state', { state: 'connected', context: 'c' }))
219
+ render({ wantsTopology: false })
220
+ const next = TestStream.opened[1]
221
+ act(() => next.send('connection_state', { state: 'connected', context: 'c' }))
222
+ act(() => old.send('context_changed', { context: 'target', switchId: 'op' }))
223
+ expect(changed).toHaveBeenCalledOnce()
224
+ expect(next.close).toHaveBeenCalled()
225
+ expect(old.close).toHaveBeenCalled()
226
+ expect(TestStream.opened).toHaveLength(3)
227
+ })
228
+
229
+ test('a handover stream that fails before delivering falls back to a hard reconnect', () => {
230
+ vi.useFakeTimers()
231
+ try {
232
+ const old = TestStream.opened[0]
233
+ act(() => old.send('connection_state', { state: 'connected', context: 'c' }))
234
+ render({ wantsTopology: false })
235
+ const next = TestStream.opened[1]
236
+ act(() => next.onerror?.())
237
+ expect(next.close).toHaveBeenCalled()
238
+ expect(old.close).toHaveBeenCalled()
239
+ expect(hook.current!.connected).toBe(false)
240
+ act(() => vi.advanceTimersByTime(3000))
241
+ const retry = TestStream.opened[2]
242
+ expect(retry.params.has('topology')).toBe(false)
243
+ } finally {
244
+ vi.useRealTimers()
245
+ }
246
+ })
247
+
248
+ test('a stream that dropped is not handed over: a parameter change during backoff reconnects at once, as a reconnect', () => {
249
+ vi.useFakeTimers()
250
+ try {
251
+ const old = TestStream.opened[0]
252
+ act(() => old.send('connection_state', { state: 'connected', context: 'c' }))
253
+ act(() => old.onerror?.())
254
+ render({ wantsTopology: false })
255
+ const next = TestStream.opened[1]
256
+ act(() => next.send('connection_state', { state: 'connected', context: 'c' }))
257
+ expect(connectionState).toHaveBeenLastCalledWith({ state: 'connected', context: 'c' }, { handover: false })
258
+ act(() => vi.advanceTimersByTime(30_000))
259
+ expect(TestStream.opened).toHaveLength(2)
260
+ } finally {
261
+ vi.useRealTimers()
262
+ }
263
+ })
264
+
265
+ test('a handover whose old stream dropped first is not reported as one', () => {
266
+ const old = TestStream.opened[0]
267
+ act(() => old.send('connection_state', { state: 'connected', context: 'c' }))
268
+ render({ wantsTopology: false })
269
+ const next = TestStream.opened[1]
270
+ act(() => old.onerror?.())
271
+ act(() => next.send('connection_state', { state: 'connected', context: 'c' }))
272
+ expect(connectionState).toHaveBeenLastCalledWith({ state: 'connected', context: 'c' }, { handover: false })
273
+ })
274
+
275
+ test('a cluster switch during a handover drops the new stream, which may hold the old cluster’s frames', () => {
276
+ const old = TestStream.opened[0]
277
+ act(() => old.send('connection_state', { state: 'connected', context: 'c' }))
278
+ render({ wantsTopology: false })
279
+ const pending = TestStream.opened[1]
280
+ act(() => old.send('context_changed', { context: 'target', switchId: 'op' }))
281
+ expect(pending.close).toHaveBeenCalled()
282
+ const fresh = TestStream.opened[2]
283
+ expect(fresh).toBeDefined()
284
+ act(() => pending.send('topology_status', { requiresNamespaceFilter: true }))
285
+ expect(complete).not.toHaveBeenCalled()
286
+ act(() => fresh.send('topology_status', { requiresNamespaceFilter: false }))
287
+ expect(complete).toHaveBeenCalledOnce()
288
+ expect(hook.current!.topologyStatus?.requiresNamespaceFilter).toBe(false)
289
+ })
290
+
291
+ test('a failed handover clears the graph it was replacing', () => {
292
+ const old = TestStream.opened[0]
293
+ act(() => old.send('topology', { nodes: [{ id: 'graph' }], edges: [] }))
294
+ expect(hook.current!.topology).not.toBeNull()
295
+ render({ wantsTopology: false })
296
+ act(() => TestStream.opened[1].onerror?.())
297
+ expect(hook.current!.topology).toBeNull()
298
+ })
299
+
300
+ test('a new stream’s first graph shows at once, not after the previous stream’s throttle', () => {
301
+ const old = TestStream.opened[0]
302
+ act(() => old.send('topology', { nodes: [{ id: 'resources-view' }], edges: [] }))
303
+ render({ wantsTopology: true, viewMode: 'traffic' })
304
+ const next = TestStream.opened[1]
305
+ act(() => {
306
+ next.send('connection_state', { state: 'connected', context: 'c' })
307
+ next.send('topology', { nodes: [{ id: 'traffic-view' }], edges: [] })
308
+ })
309
+ expect(hook.current!.topology?.nodes[0].id).toBe('traffic-view')
310
+ })
311
+
312
+ test('a parameter change while a reconnect is still connecting is not a handover', () => {
313
+ vi.useFakeTimers()
314
+ try {
315
+ const old = TestStream.opened[0]
316
+ act(() => old.send('connection_state', { state: 'connected', context: 'c' }))
317
+ act(() => old.onerror?.())
318
+ act(() => vi.advanceTimersByTime(3000))
319
+ const reconnecting = TestStream.opened[1]
320
+ render({ wantsTopology: false })
321
+ expect(reconnecting.close).toHaveBeenCalled()
322
+ const next = TestStream.opened[2]
323
+ act(() => next.send('connection_state', { state: 'connected', context: 'c' }))
324
+ expect(connectionState).toHaveBeenLastCalledWith({ state: 'connected', context: 'c' }, { handover: false })
325
+ } finally {
326
+ vi.useRealTimers()
327
+ }
328
+ })
329
+
330
+ test('a reconnect that opened but hasn’t reported its state is not handed over from', () => {
331
+ vi.useFakeTimers()
332
+ try {
333
+ const old = TestStream.opened[0]
334
+ act(() => old.send('connection_state', { state: 'connected', context: 'c' }))
335
+ act(() => old.onerror?.())
336
+ act(() => vi.advanceTimersByTime(3000))
337
+ const reconnecting = TestStream.opened[1]
338
+ act(() => reconnecting.onopen?.())
339
+ render({ wantsTopology: false })
340
+ expect(reconnecting.close).toHaveBeenCalled()
341
+ const next = TestStream.opened[2]
342
+ act(() => next.send('connection_state', { state: 'connected', context: 'c' }))
343
+ expect(connectionState).toHaveBeenLastCalledWith({ state: 'connected', context: 'c' }, { handover: false })
344
+ } finally {
345
+ vi.useRealTimers()
346
+ }
347
+ })
348
+
349
+ test('a cluster switch on the new stream ends the drain', () => {
350
+ const { old, next } = handOver()
351
+ act(() => next.send('context_changed', { context: 'target' }))
352
+ expect(changed).toHaveBeenCalledOnce()
353
+ expect(old.close).toHaveBeenCalled()
354
+ act(() => old.send('context_changed', { context: 'target' }))
355
+ expect(changed).toHaveBeenCalledOnce()
356
+ })