@skyhook-io/radar-app 1.18.0 → 1.18.1

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 (69) hide show
  1. package/README.md +6 -0
  2. package/package.json +2 -3
  3. package/src/App.tsx +22 -6
  4. package/src/api/client.gitops-destination.test.tsx +55 -0
  5. package/src/api/client.resource-list.test.ts +76 -0
  6. package/src/api/client.ts +61 -20
  7. package/src/api/quotas.ts +9 -20
  8. package/src/api/radarFeatures.ts +2 -0
  9. package/src/api/resourceLists.test.ts +84 -0
  10. package/src/api/resourceLists.ts +71 -0
  11. package/src/components/cnpg/CNPGView.tsx +1 -0
  12. package/src/components/compare/CompareResourcePicker.test.tsx +58 -0
  13. package/src/components/compare/CompareViewRoute.tsx +5 -1
  14. package/src/components/compare/useCompareCandidates.ts +1 -1
  15. package/src/components/compare/useCompareLauncher.tsx +4 -2
  16. package/src/components/diagnose/StoryExcerpt.tsx +24 -5
  17. package/src/components/diagnose/investigationEvidence/adapters/listCoverage.test.ts +415 -0
  18. package/src/components/diagnose/investigationEvidence/adapters/resource.ts +107 -8
  19. package/src/components/diagnose/investigationEvidence/bodies/inventory.tsx +66 -16
  20. package/src/components/diagnose/investigationEvidence/builder.ts +13 -1
  21. package/src/components/diagnose/investigationEvidence/excerpt.ts +2 -0
  22. package/src/components/diagnose/investigationEvidence/observations.ts +1 -0
  23. package/src/components/diagnose/investigationEvidence/projection.test.ts +24 -1
  24. package/src/components/diagnose/investigationEvidence/types.ts +15 -0
  25. package/src/components/diagnose/toolCallLabel.test.ts +9 -0
  26. package/src/components/diagnose/toolCallLabel.ts +2 -0
  27. package/src/components/execution/BatchExecutionView.image-browse.test.tsx +46 -0
  28. package/src/components/execution/BatchExecutionView.tsx +6 -4
  29. package/src/components/gitops/GitOpsView.identity.test.tsx +113 -0
  30. package/src/components/gitops/GitOpsView.tsx +62 -40
  31. package/src/components/gitops/useDestinationCluster.ts +2 -1
  32. package/src/components/helm/ArtifactHubSourceSearch.test.tsx +124 -0
  33. package/src/components/helm/ArtifactHubSourceSearch.tsx +240 -0
  34. package/src/components/helm/ChartBrowser.tsx +5 -4
  35. package/src/components/helm/TrackChartSourceDialog.render.test.tsx +269 -96
  36. package/src/components/helm/TrackChartSourceDialog.tsx +607 -104
  37. package/src/components/home/mcpToolCatalog.ts +10 -0
  38. package/src/components/resource/PrometheusCharts.overlays.test.ts +45 -0
  39. package/src/components/resource/PrometheusCharts.tsx +2 -2
  40. package/src/components/resources/ResourcesView.tsx +29 -67
  41. package/src/components/resources/renderers/PodRenderer.tsx +4 -1
  42. package/src/components/settings/MyPermissionsDialog.tsx +12 -9
  43. package/src/components/traffic/TrafficSourcePill.test.tsx +110 -0
  44. package/src/components/traffic/TrafficSourcePill.tsx +111 -0
  45. package/src/components/traffic/TrafficView.tsx +9 -55
  46. package/src/components/ui/DiagnosticsOverlay.test.ts +25 -0
  47. package/src/components/ui/DiagnosticsOverlay.tsx +2 -1
  48. package/src/components/ui/Omnibar.note.test.tsx +141 -0
  49. package/src/components/ui/Omnibar.tsx +82 -18
  50. package/src/components/ui/RadarOmnibar.test.tsx +183 -0
  51. package/src/components/ui/RadarOmnibar.tsx +38 -4
  52. package/src/components/ui/UpdateNotification.manual.test.tsx +177 -0
  53. package/src/components/ui/UpdateNotification.test.tsx +2 -1
  54. package/src/components/ui/UpdateNotification.tsx +29 -5
  55. package/src/components/ui/omnibar-match.test.ts +15 -8
  56. package/src/components/ui/omnibar-match.ts +11 -6
  57. package/src/components/ui/searchCoverage.fixtures.ts +16 -0
  58. package/src/components/ui/searchCoverageNote.test.ts +245 -0
  59. package/src/components/ui/searchCoverageNote.ts +222 -0
  60. package/src/components/whats-new/WhatsNew.test.ts +10 -0
  61. package/src/components/whats-new/WhatsNew.tsx +5 -4
  62. package/src/components/whats-new/WhatsNewDialog.test.tsx +20 -0
  63. package/src/components/whats-new/releaseNotes.ts +57 -5
  64. package/src/components/workload/WorkloadView.tsx +8 -2
  65. package/src/hooks/useResourceCounts.ts +2 -0
  66. package/src/index.css +2 -4
  67. package/src/index.ts +7 -0
  68. package/src/utils/artifacthub.test.ts +18 -0
  69. package/src/utils/artifacthub.ts +9 -0
@@ -0,0 +1,183 @@
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, describe, expect, it, vi } from 'vitest'
6
+ import type { SearchCoverageEntry } from './searchCoverageNote'
7
+ import { coverageOf } from './searchCoverage.fixtures'
8
+
9
+ vi.mock('../../api/usage-data', () => ({ recordUsageEvent: vi.fn() }))
10
+ vi.mock('../../hooks/useRecentResources', () => ({ loadRecentResources: () => [], recordRecentResource: vi.fn() }))
11
+ vi.mock('../../api/apiResources', async (importOriginal) => ({ ...(await importOriginal<object>()), useAPIResources: () => ({ data: [] }) }))
12
+ vi.mock('./command-items', async (importOriginal) => ({ ...(await importOriginal<object>()), useCommandItems: () => [] }))
13
+ const caps = vi.hoisted(() => ({ data: undefined as undefined | { authEnabled?: boolean } }))
14
+ vi.mock('../../api/client', async (importOriginal) => ({
15
+ ...(await importOriginal<object>()),
16
+ useNamespaceScope: () => ({ data: undefined }),
17
+ useContexts: () => ({ data: [] }),
18
+ useCapabilities: () => caps,
19
+ }))
20
+
21
+ import { RadarOmnibar } from './RadarOmnibar'
22
+
23
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
24
+ let root: Root
25
+ let host: HTMLDivElement
26
+ let unsearched: SearchCoverageEntry[]
27
+ let searches = 0
28
+
29
+ const pending: SearchCoverageEntry[] = [{ kind: '*', group: '', reason: 'kind_sync_pending' }]
30
+ const failed: SearchCoverageEntry[] = [{ kind: 'SpStall', group: 'stall.sp-live.test', reason: 'kind_sync_timed_out' }]
31
+
32
+ beforeEach(() => {
33
+ vi.useFakeTimers()
34
+ caps.data = undefined
35
+ searches = 0
36
+ vi.stubGlobal('fetch', vi.fn(async (input: string) => {
37
+ const url = new URL(input, 'http://localhost')
38
+ if (!url.pathname.endsWith('/search')) throw new Error(`Unexpected request: ${input}`)
39
+ searches++
40
+ return new Response(JSON.stringify({ hits: [], total: 0, searched: 0, total_matched: 0, coverage: coverageOf(unsearched) }), { status: 200 })
41
+ }))
42
+ host = document.createElement('div')
43
+ document.body.appendChild(host)
44
+ root = createRoot(host)
45
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
46
+ const noop = vi.fn()
47
+ act(() => {
48
+ root.render(
49
+ <QueryClientProvider client={client}>
50
+ <RadarOmnibar onOpenResource={noop} onNavigateView={noop} onNavigateKind={noop} onSwitchContext={noop} onSetNamespaces={noop} onToggleTheme={noop} />
51
+ </QueryClientProvider>,
52
+ )
53
+ })
54
+ })
55
+
56
+ afterEach(() => {
57
+ act(() => root.unmount())
58
+ host.remove()
59
+ document.body.innerHTML = ''
60
+ vi.unstubAllGlobals()
61
+ vi.useRealTimers()
62
+ })
63
+
64
+ async function typeQuery(text: string) {
65
+ const input = host.querySelector('input')!
66
+ act(() => input.focus())
67
+ act(() => {
68
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, text)
69
+ input.dispatchEvent(new Event('input', { bubbles: true }))
70
+ })
71
+ await act(async () => { await vi.advanceTimersByTimeAsync(200) })
72
+ await act(async () => { await vi.advanceTimersByTimeAsync(100) })
73
+ }
74
+
75
+ const advance = (ms: number) => act(async () => { await vi.advanceTimersByTimeAsync(ms) })
76
+ const page = () => document.body.textContent ?? ''
77
+
78
+ describe('RadarOmnibar while results load', () => {
79
+ it('re-queries a loading search and ends on the failure once Radar gives up on the kind', async () => {
80
+ unsearched = pending
81
+ await typeQuery('sp-live')
82
+ expect(page()).toContain('Still loading — results may change.')
83
+
84
+ await advance(25_000)
85
+ expect(searches).toBeGreaterThanOrEqual(5)
86
+ expect(page()).toContain('Still loading — results may change.')
87
+
88
+ // Radar reports a kind that never synced as failed after about 30 s, so
89
+ // the omnibar must still be asking then.
90
+ await advance(6_000)
91
+ unsearched = failed
92
+ await advance(10_000)
93
+ expect(page()).toContain("Couldn't read SpStall; matches of that kind may be missing.")
94
+ expect(page()).not.toContain('Still loading')
95
+
96
+ const settled = searches
97
+ await advance(30_000)
98
+ expect(searches).toBe(settled)
99
+ })
100
+
101
+ it('still catches a kind that fails 30 s after a watch that started late in warm-up', async () => {
102
+ unsearched = pending
103
+ await typeQuery('sp-live')
104
+ await advance(48_000)
105
+ expect(page()).toContain('Still loading — results may change.')
106
+ unsearched = failed
107
+ await advance(6_000)
108
+ expect(page()).toContain("Couldn't read SpStall; matches of that kind may be missing.")
109
+ const settled = searches
110
+ await advance(30_000)
111
+ expect(searches).toBe(settled)
112
+ })
113
+
114
+ it('stops re-querying after its budget and says so', async () => {
115
+ unsearched = pending
116
+ await typeQuery('sp-live')
117
+ await advance(55_000)
118
+ expect(page()).toContain('Still loading — results may change.')
119
+ await advance(6_000)
120
+ expect(page()).toContain('Still loading — try again shortly.')
121
+ const settled = searches
122
+ await advance(30_000)
123
+ expect(searches).toBe(settled)
124
+ })
125
+ })
126
+
127
+ describe('RadarOmnibar namespace notes', () => {
128
+ // Radar decides whether a missing namespace may be named as absent: only a
129
+ // caller who can see every namespace is told it doesn't exist.
130
+ it('says a namespace does not exist when Radar says so, whatever the auth mode', async () => {
131
+ for (const data of [{}, { authEnabled: true }]) {
132
+ caps.data = data
133
+ unsearched = [{ kind: '*', group: '', reason: 'namespace_not_found', namespaces: ['payments-prd'] }]
134
+ await typeQuery(`ns:payments-prd web${'authEnabled' in data ? 's' : ''}`)
135
+ expect(page()).toContain("Namespace 'payments-prd' doesn't exist on this cluster.")
136
+ }
137
+ })
138
+
139
+ it('stays scoped to what the caller can see when Radar does not say', async () => {
140
+ for (const data of [{}, { authEnabled: true }]) {
141
+ caps.data = data
142
+ unsearched = [{ kind: '*', group: '', reason: 'user_namespace_not_visible', namespaces: ['payments-prd'] }]
143
+ await typeQuery(`ns:payments-prd web${'authEnabled' in data ? 's' : ''}`)
144
+ expect(page()).toContain("Namespace 'payments-prd' wasn't found in what you can see.")
145
+ }
146
+ })
147
+ })
148
+
149
+ describe('RadarOmnibar read recovery', () => {
150
+ it.each([
151
+ ['alone', []],
152
+ ['followed by a namespace note', [{ kind: '*', group: '', reason: 'radar_namespace_not_collected', namespaces: ['rel-owner'] }]],
153
+ ['preceded by a loading note', pending],
154
+ ] as [string, SearchCoverageEntry[]][])('adds the suggested kind %s, preserves modifiers and terms, and re-checks while open', async (_, siblings) => {
155
+ unsearched = [{ kind: 'Certificate', group: 'cert-manager.io', reason: 'read_error' }, ...siblings]
156
+ await typeQuery('ns:prod')
157
+ act(() => host.querySelector('input')!.dispatchEvent(new KeyboardEvent('keydown', { key: ' ', bubbles: true })))
158
+ await typeQuery('label:app=web image:nginx renewal')
159
+ expect(page()).toContain("Couldn't read Certificate; matches of that kind may be missing. Search kind:Certificate to re-check.")
160
+ const button = [...document.body.querySelectorAll('button')].find((b) => b.textContent === 'kind:Certificate')!
161
+ expect(button).toBeDefined()
162
+ const recoveryText = "Couldn't read Certificate; matches of that kind may be missing. Search kind:Certificate to re-check."
163
+ const siblingText = siblings === pending ? 'Still loading — results may change.' : siblings.length ? "Namespace 'rel-owner' wasn't searched: Radar here watches only some namespaces." : ''
164
+ expect(button.parentElement!.textContent?.trim()).toBe(recoveryText)
165
+ expect(button.parentElement!.parentElement!.textContent).toBe(siblings === pending ? `${siblingText} ${recoveryText}` : `${recoveryText}${siblingText ? ` ${siblingText}` : ''}`)
166
+ act(() => button.click())
167
+ await advance(300)
168
+ await advance(100)
169
+ const requests = vi.mocked(fetch).mock.calls.map(([input]) => new URL(String(input), 'http://localhost').searchParams.get('q'))
170
+ expect(requests.at(-1)).toBe('ns:prod kind:Certificate label:app=web image:nginx renewal')
171
+ expect(host.querySelector('input')!.value).toContain('renewal')
172
+ expect(page()).toContain("Couldn't read Certificate; matches of that kind may be missing.")
173
+ expect([...document.body.querySelectorAll('button')].some((b) => b.textContent === 'kind:Certificate')).toBe(false)
174
+ expect(page()).not.toContain('to re-check.')
175
+ })
176
+
177
+ it.each(['kind:Certificate renewal', 'k:certificates renewal'])('keeps an explicit failed search honest: %s', async (query) => {
178
+ unsearched = [{ kind: 'Certificate', group: 'cert-manager.io', reason: 'read_error' }]
179
+ await typeQuery(query)
180
+ expect(page()).toContain("Couldn't read Certificate; matches of that kind may be missing.")
181
+ expect(page()).not.toContain('to re-check.')
182
+ })
183
+ })
@@ -1,14 +1,17 @@
1
- import { forwardRef, useMemo, useState } from 'react'
1
+ import { forwardRef, useEffect, useMemo, useState, useRef, useImperativeHandle } from 'react'
2
2
  import { Omnibar, type OmnibarHandle } from './Omnibar'
3
- import { useSearch, useNamespaceScope, useContexts, type SearchHit } from '../../api/client'
3
+ import { useSearch, useNamespaceScope, useContexts, type SearchHit, type SearchResult } from '../../api/client'
4
4
  import { useAPIResources } from '../../api/apiResources'
5
5
  import { loadRecentResources, recordRecentResource } from '../../hooks/useRecentResources'
6
6
  import { useCommandItems, type CommandItemCallbacks } from './command-items'
7
+ import { PENDING_RETRY_BUDGET_MS, PENDING_RETRY_MS, searchCoverageNote } from './searchCoverageNote'
7
8
 
8
9
  interface RadarOmnibarProps extends CommandItemCallbacks {
9
10
  onOpenResource: (hit: SearchHit) => void
10
11
  }
11
12
 
13
+ const stillLoading = (data: SearchResult | undefined) => !!data?.coverage?.gaps.some((gap) => gap.code === 'kind_sync_pending')
14
+
12
15
  // Radar standalone's omnibar: wires the injectable Omnibar to Radar's own hooks
13
16
  // (cluster /api/search, kubeconfig contexts, API discovery, recents). Radar Hub
14
17
  // provides a parallel wrapper over fleet search.
@@ -16,11 +19,30 @@ export const RadarOmnibar = forwardRef<OmnibarHandle, RadarOmnibarProps>(functio
16
19
  { onOpenResource, ...callbacks },
17
20
  ref,
18
21
  ) {
22
+ const omnibarRef = useRef<OmnibarHandle>(null)
23
+ useImperativeHandle(ref, () => ({
24
+ focus: () => omnibarRef.current?.focus(),
25
+ addModifier: (modifier) => omnibarRef.current?.addModifier(modifier),
26
+ }), [])
19
27
  // The omnibar debounces internally and emits the query to search here.
20
28
  const [query, setQuery] = useState('')
21
29
  const [open, setOpen] = useState(false)
30
+ // The query whose still-loading re-queries ran out of budget while open.
31
+ const [exhaustedQuery, setExhaustedQuery] = useState<string | null>(null)
32
+
33
+ const { data: searchData, isFetching, isPlaceholderData, isError } = useSearch(query, {
34
+ enabled: open,
35
+ globalNs: true,
36
+ refetchInterval: (data) => (open && stillLoading(data) && exhaustedQuery !== query ? PENDING_RETRY_MS : false),
37
+ })
38
+ const pending = !isPlaceholderData && stillLoading(searchData)
39
+ useEffect(() => {
40
+ if (!open || !pending) return
41
+ const timer = setTimeout(() => setExhaustedQuery(query), PENDING_RETRY_BUDGET_MS)
42
+ return () => clearTimeout(timer)
43
+ }, [open, pending, query])
44
+ useEffect(() => { if (!open) setExhaustedQuery(null) }, [open])
22
45
 
23
- const { data: searchData, isFetching, isPlaceholderData, isError } = useSearch(query, { enabled: open, globalNs: true })
24
46
  const { data: nsScope } = useNamespaceScope()
25
47
  const { data: apiResources } = useAPIResources()
26
48
  const { data: contexts } = useContexts()
@@ -32,10 +54,21 @@ export const RadarOmnibar = forwardRef<OmnibarHandle, RadarOmnibarProps>(functio
32
54
  }), [nsScope, apiResources])
33
55
 
34
56
  const commandItems = useCommandItems(callbacks)
57
+ const { onNavigateKind } = callbacks
58
+ const note = searchCoverageNote(searchData?.coverage, {
59
+ hits: searchData?.hits,
60
+ query,
61
+ recheckKind: (kind) => omnibarRef.current?.addModifier({ key: 'kind', value: kind }),
62
+ pendingExhausted: exhaustedQuery === query,
63
+ openKindList: (kind, group) => {
64
+ const resource = apiResources?.find((r) => r.kind === kind && r.group === group)
65
+ return resource ? () => onNavigateKind(resource.name, resource.group) : undefined
66
+ },
67
+ })
35
68
 
36
69
  return (
37
70
  <Omnibar
38
- ref={ref}
71
+ ref={omnibarRef}
39
72
  onOpenResource={onOpenResource}
40
73
  commandItems={commandItems}
41
74
  onQueryChange={(q, o) => { setQuery(q); setOpen(o) }}
@@ -43,6 +76,7 @@ export const RadarOmnibar = forwardRef<OmnibarHandle, RadarOmnibarProps>(functio
43
76
  isFetching={isFetching}
44
77
  isError={isError}
45
78
  isPlaceholderData={isPlaceholderData}
79
+ note={note}
46
80
  modifierOptions={modifierOptions}
47
81
  seedNamespaces={nsScope?.actives}
48
82
  loadRecents={() => loadRecentResources(contextKey)}
@@ -0,0 +1,177 @@
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, describe, expect, it, vi } from 'vitest'
6
+ import type { VersionInfo } from '../../api/client'
7
+
8
+ vi.mock('../../api/client', () => ({
9
+ useCapabilities: () => ({ data: { deployment: { mode: 'local' } } }),
10
+ useVersionCheck: () => ({ data: { currentVersion: '1.2.3', updateAvailable: false, installMethod: 'desktop' } }),
11
+ useStartDesktopUpdate: () => ({ mutate: vi.fn(), isPending: false }),
12
+ useDesktopUpdateStatus: () => ({ data: undefined }),
13
+ useApplyDesktopUpdate: () => ({ mutate: vi.fn() }),
14
+ }))
15
+
16
+ import { UpdateNotification } from './UpdateNotification'
17
+ import { ToastProvider, showApiNotice } from './Toast'
18
+ import { DURATION_TOAST_EXIT } from '../../utils/animation'
19
+ import { setApiBase } from '../../api/config'
20
+
21
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
22
+
23
+ let root: Root
24
+ let container: HTMLDivElement
25
+ let client: QueryClient
26
+ const current: VersionInfo = { currentVersion: '1.2.3', updateAvailable: false, installMethod: 'desktop' }
27
+
28
+ beforeEach(() => {
29
+ vi.clearAllMocks()
30
+ vi.useFakeTimers()
31
+ setApiBase('/desktop/api')
32
+ client = new QueryClient()
33
+ client.setQueryData(['version-check', '/desktop/api'], current)
34
+ container = document.createElement('div')
35
+ document.body.appendChild(container)
36
+ root = createRoot(container)
37
+ act(() => root.render(
38
+ <QueryClientProvider client={client}>
39
+ <ToastProvider>
40
+ <UpdateNotification />
41
+ <UpdateNotification placement="settings" />
42
+ </ToastProvider>
43
+ </QueryClientProvider>,
44
+ ))
45
+ })
46
+
47
+ afterEach(() => {
48
+ act(() => root.unmount())
49
+ container.remove()
50
+ client.clear()
51
+ setApiBase('/api')
52
+ vi.useRealTimers()
53
+ })
54
+
55
+ describe('manual Desktop version checks', () => {
56
+ it('acknowledges one check even when Settings is also mounted', () => {
57
+ act(() => { window.dispatchEvent(new Event('radar:check-for-updates')) })
58
+ expect(container.querySelectorAll('[role="status"]')).toHaveLength(1)
59
+ expect(container.textContent).toContain('Checking for updates…')
60
+ })
61
+
62
+ it('reports an up-to-date result once', () => {
63
+ act(() => { window.dispatchEvent(new CustomEvent('radar:update-check-result', { detail: current })) })
64
+ expect(container.querySelectorAll('[role="status"]')).toHaveLength(1)
65
+ expect(container.textContent).toContain("You're up to date")
66
+ expect(container.textContent).toContain('Radar 1.2.3')
67
+ })
68
+
69
+ it('publishes a fresh available update and clears its dismissal', () => {
70
+ localStorage.setItem('radar-update-dismissed', '1.3.0')
71
+ const info = { ...current, updateAvailable: true, latestVersion: '1.3.0' }
72
+ act(() => { window.dispatchEvent(new CustomEvent('radar:update-check-result', { detail: info })) })
73
+ expect(client.getQueryData(['version-check', '/desktop/api'])).toEqual(info)
74
+ expect(localStorage.getItem('radar-update-dismissed')).toBeNull()
75
+ expect(container.textContent).toContain('Radar 1.3.0 is available')
76
+ })
77
+
78
+ it('reports failure without replacing known version data', () => {
79
+ act(() => { window.dispatchEvent(new CustomEvent('radar:update-check-result', { detail: { ...current, error: 'offline' } })) })
80
+ expect(container.querySelector('[role="status"]')?.textContent).toContain('Could not check for updates')
81
+ expect(container.textContent).toContain('offline')
82
+ expect(container.textContent).not.toContain("You're up to date")
83
+ expect(client.getQueryData(['version-check', '/desktop/api'])).toEqual(current)
84
+ })
85
+
86
+ it('does not claim a development build is up to date', () => {
87
+ act(() => { window.dispatchEvent(new CustomEvent('radar:update-check-result', { detail: { ...current, currentVersion: '1.3.0-37-g8b325b372', buildChannel: 'development', latestVersion: '1.3.0' } })) })
88
+ expect(container.textContent).not.toContain("You're up to date")
89
+ expect(container.textContent).toContain('Latest Radar release: 1.3.0')
90
+ expect(container.textContent).toContain('You are running a development build.')
91
+ })
92
+
93
+ it('discards an automatic response that races with the manual result', async () => {
94
+ let resolveAutomatic!: (value: VersionInfo) => void
95
+ const pending = client.fetchQuery({
96
+ queryKey: ['version-check', '/desktop/api'],
97
+ queryFn: () => new Promise<VersionInfo>(resolve => { resolveAutomatic = resolve }),
98
+ staleTime: 0,
99
+ }).catch(() => undefined)
100
+ const info = { ...current, updateAvailable: true, latestVersion: '1.3.0' }
101
+ act(() => { window.dispatchEvent(new CustomEvent('radar:update-check-result', { detail: info })) })
102
+ resolveAutomatic(current)
103
+ await pending
104
+ expect(client.getQueryData(['version-check', '/desktop/api'])).toEqual(info)
105
+ })
106
+
107
+ it('lets the initial automatic fetch finish when a manual check fails', async () => {
108
+ client.removeQueries({ queryKey: ['version-check', '/desktop/api'], exact: true })
109
+ let resolveAutomatic!: (value: VersionInfo) => void
110
+ const pending = client.fetchQuery({
111
+ queryKey: ['version-check', '/desktop/api'],
112
+ queryFn: () => new Promise<VersionInfo>(resolve => { resolveAutomatic = resolve }),
113
+ })
114
+ act(() => {
115
+ window.dispatchEvent(new Event('radar:check-for-updates'))
116
+ window.dispatchEvent(new CustomEvent('radar:update-check-result', { detail: { ...current, error: 'offline' } }))
117
+ })
118
+ resolveAutomatic(current)
119
+ await pending
120
+ expect(client.getQueryData(['version-check', '/desktop/api'])).toEqual(current)
121
+ })
122
+ })
123
+
124
+
125
+ describe('manual check toast lifecycle', () => {
126
+ it('updates the same toast element after a slow check and starts the result timer then', () => {
127
+ act(() => { window.dispatchEvent(new Event('radar:check-for-updates')) })
128
+ const toast = container.querySelector('[role="status"]')
129
+ act(() => { vi.advanceTimersByTime(9000) })
130
+ expect(container.querySelector('[role="status"]')).toBe(toast)
131
+ expect(toast?.textContent).toContain('Checking for updates…')
132
+
133
+ act(() => { window.dispatchEvent(new CustomEvent('radar:update-check-result', { detail: current })) })
134
+ expect(container.querySelector('[role="status"]')).toBe(toast)
135
+ expect(toast?.textContent).toContain("You're up to date")
136
+ expect(container.textContent).not.toContain('Checking for updates…')
137
+ expect(container.querySelectorAll('[role="status"]')).toHaveLength(1)
138
+ act(() => { vi.advanceTimersByTime(6999) })
139
+ expect(container.querySelector('[role="status"]')).toBe(toast)
140
+ act(() => { vi.advanceTimersByTime(1 + DURATION_TOAST_EXIT) })
141
+ expect(container.querySelector('[role="status"]')).toBeNull()
142
+ })
143
+
144
+ it('replaces progress with an error in the same toast', () => {
145
+ act(() => { window.dispatchEvent(new Event('radar:check-for-updates')) })
146
+ const toast = container.querySelector('[role="status"]')
147
+ act(() => { window.dispatchEvent(new CustomEvent('radar:update-check-result', { detail: { ...current, error: 'offline' } })) })
148
+ expect(container.querySelector('[role="status"]')).toBe(toast)
149
+ expect(container.textContent).not.toContain('Checking for updates…')
150
+ expect(container.querySelectorAll('[role="status"], [role="alert"]')).toHaveLength(1)
151
+ act(() => { vi.advanceTimersByTime(9999) })
152
+ expect(container.querySelector('[role="status"]')).toBe(toast)
153
+ act(() => { vi.advanceTimersByTime(1 + DURATION_TOAST_EXIT) })
154
+ expect(container.querySelector('[role="status"]')).toBeNull()
155
+ })
156
+
157
+ it('does not let a previous result timer dismiss the next check', () => {
158
+ act(() => { window.dispatchEvent(new CustomEvent('radar:update-check-result', { detail: current })) })
159
+ act(() => { vi.advanceTimersByTime(7100) })
160
+ act(() => { window.dispatchEvent(new Event('radar:check-for-updates')) })
161
+ const toast = container.querySelector('[role="status"]')
162
+ act(() => { vi.advanceTimersByTime(9000) })
163
+ expect(container.querySelector('[role="status"]')).toBe(toast)
164
+ expect(toast?.textContent).toContain('Checking for updates…')
165
+ expect(toast?.classList.contains('animate-out')).toBe(false)
166
+ })
167
+
168
+ it('keeps ordinary toasts independent and auto-dismisses them', () => {
169
+ act(() => {
170
+ showApiNotice('First notice', undefined, 'info')
171
+ showApiNotice('Second notice', undefined, 'info')
172
+ })
173
+ expect(container.querySelectorAll('[role="status"]')).toHaveLength(2)
174
+ act(() => { vi.advanceTimersByTime(7000 + DURATION_TOAST_EXIT) })
175
+ expect(container.querySelectorAll('[role="status"]')).toHaveLength(0)
176
+ })
177
+ })
@@ -21,12 +21,13 @@ vi.mock('../../api/client', () => ({
21
21
  }))
22
22
 
23
23
  import { UpdateNotification } from './UpdateNotification'
24
+ import { ToastProvider } from './Toast'
24
25
 
25
26
  function renderNotification() {
26
27
  const client = new QueryClient()
27
28
  return renderToString(
28
29
  <QueryClientProvider client={client}>
29
- <UpdateNotification />
30
+ <ToastProvider><UpdateNotification /></ToastProvider>
30
31
  </QueryClientProvider>,
31
32
  )
32
33
  }
@@ -9,7 +9,9 @@ import {
9
9
  useDesktopUpdateStatus,
10
10
  useApplyDesktopUpdate,
11
11
  } from '../../api/client'
12
- import type { DesktopUpdateState } from '../../api/client'
12
+ import type { DesktopUpdateState, VersionInfo } from '../../api/client'
13
+ import { getApiBase } from '../../api/config'
14
+ import { useToast } from './Toast'
13
15
  import { WithTooltip } from './Tooltip'
14
16
  import { TRANSITION_MENU, overlayExitMs, overlayTransitionStyle } from '../../utils/animation'
15
17
  import { useAnimatedUnmount } from '../../hooks/useAnimatedUnmount'
@@ -35,6 +37,7 @@ export function UpdateNotification({ placement = 'floating' }: { placement?: 'fl
35
37
  const triggerRef = useRef<HTMLButtonElement>(null)
36
38
  const panelId = useId()
37
39
  const queryClient = useQueryClient()
40
+ const { showToast } = useToast()
38
41
  const { data: capabilities } = useCapabilities()
39
42
  const deploymentMode = capabilities ? (capabilities.deployment?.mode ?? 'local') : undefined
40
43
  const { data: versionInfo } = useVersionCheck()
@@ -58,17 +61,38 @@ export function UpdateNotification({ placement = 'floating' }: { placement?: 'fl
58
61
  return () => document.removeEventListener('pointerdown', closeOutside)
59
62
  }, [expanded])
60
63
 
61
- // Listen for "Check for Updates" menu item in desktop app.
62
64
  useEffect(() => {
65
+ if (inSettings) return
66
+ const id = 'radar-manual-update-check'
63
67
  const handler = () => {
68
+ showToast('Checking for updates…', { id, type: 'info', duration: 0 })
69
+ }
70
+ const resultHandler = (event: Event) => {
71
+ const info = (event as CustomEvent<VersionInfo>).detail
72
+ if (info.error) {
73
+ showToast('Could not check for updates', { id, type: 'error', detail: info.error })
74
+ return
75
+ }
76
+ void queryClient.cancelQueries({ queryKey: ['version-check', getApiBase()], exact: true })
64
77
  setDismissed(false)
65
78
  try { localStorage.removeItem(DISMISSED_KEY) } catch { /* ignore */ }
66
- queryClient.invalidateQueries({ queryKey: ['version-check'] })
79
+ queryClient.setQueryData(['version-check', getApiBase()], info)
80
+ if (info.updateAvailable) {
81
+ showToast(`Radar ${info.latestVersion} is available`, { id, type: 'info' })
82
+ } else if (info.buildChannel === 'development') {
83
+ showToast(`Latest Radar release: ${info.latestVersion}`, { id, type: 'info', detail: 'You are running a development build.' })
84
+ } else {
85
+ showToast("You're up to date", { id, type: 'success', detail: `Radar ${info.currentVersion}` })
86
+ }
67
87
  }
68
88
 
69
89
  window.addEventListener('radar:check-for-updates', handler)
70
- return () => window.removeEventListener('radar:check-for-updates', handler)
71
- }, [queryClient])
90
+ window.addEventListener('radar:update-check-result', resultHandler)
91
+ return () => {
92
+ window.removeEventListener('radar:check-for-updates', handler)
93
+ window.removeEventListener('radar:update-check-result', resultHandler)
94
+ }
95
+ }, [queryClient, inSettings, showToast])
72
96
 
73
97
  // Log version check errors for debugging
74
98
  useEffect(() => {
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from 'vitest'
2
- import { contentMatchLabel, partialSearchNotice } from './omnibar-match'
2
+ import { contentMatchLabel, partialSearchNotices } from './omnibar-match'
3
3
 
4
4
  const site = (s: string) => ({ token: 't', site: s, score: 12 })
5
5
 
@@ -18,13 +18,20 @@ describe('contentMatchLabel', () => {
18
18
  })
19
19
  })
20
20
 
21
- describe('partialSearchNotice', () => {
22
- it('flags partly searched findings and unchecked namespaces', () => {
23
- expect(partialSearchNotice({ incomplete_findings: 'time_limit' })).toMatch(/not fully searched/)
24
- expect(partialSearchNotice({ access_incomplete: true })).toMatch(/not fully searched/)
21
+ describe('partialSearchNotices', () => {
22
+ it('says why each part of the search is missing', () => {
23
+ expect(partialSearchNotices({ access_incomplete: true })).toEqual([
24
+ "Couldn't confirm your access to scan reports in some namespaces, so they were left out. Search again to check more.",
25
+ ])
26
+ expect(partialSearchNotices({ incomplete_findings: 'time_limit' })).toEqual([
27
+ "Search ran out of time before checking every scan report's findings. Narrow with ns: to cover the rest.",
28
+ ])
25
29
  })
26
- it('is null for a whole result or an older Radar', () => {
27
- expect(partialSearchNotice({})).toBeNull()
28
- expect(partialSearchNotice(undefined)).toBeNull()
30
+ it('shows both causes when both happened', () => {
31
+ expect(partialSearchNotices({ access_incomplete: true, incomplete_findings: 'time_limit' })).toHaveLength(2)
32
+ })
33
+ it('is empty for a whole result or an older Radar', () => {
34
+ expect(partialSearchNotices({})).toEqual([])
35
+ expect(partialSearchNotices(undefined)).toEqual([])
29
36
  })
30
37
  })
@@ -8,11 +8,16 @@ export function contentMatchLabel(matched: SearchMatchedField[] | undefined): st
8
8
  return matched.every((m) => m.site.startsWith('content:report.')) ? 'in findings' : 'in spec'
9
9
  }
10
10
 
11
- // partialSearchNotice explains a result the server says is incomplete, so a
12
- // missing CVE doesn't read as "not affected". Null when the search was whole.
13
- export function partialSearchNotice(data: { incomplete_findings?: string; access_incomplete?: boolean } | undefined): string | null {
14
- if (data?.incomplete_findings || data?.access_incomplete) {
15
- return 'Some scan reports were not fully searched. Try again, or narrow with ns:.'
11
+ // partialSearchNotices explain a result the server says is incomplete, so a
12
+ // missing CVE doesn't read as "not affected". One line per cause; empty when
13
+ // the search was whole.
14
+ export function partialSearchNotices(data: { incomplete_findings?: string; access_incomplete?: boolean } | undefined): string[] {
15
+ const out: string[] = []
16
+ if (data?.access_incomplete) {
17
+ out.push("Couldn't confirm your access to scan reports in some namespaces, so they were left out. Search again to check more.")
16
18
  }
17
- return null
19
+ if (data?.incomplete_findings) {
20
+ out.push("Search ran out of time before checking every scan report's findings. Narrow with ns: to cover the rest.")
21
+ }
22
+ return out
18
23
  }
@@ -0,0 +1,16 @@
1
+ import type { SearchCoverage } from '@skyhook-io/k8s-ui/types/read-coverage'
2
+ import type { SearchCoverageEntry } from './searchCoverageNote'
3
+
4
+ /** The wire coverage that flattens back to entries, for tests: each gap lists
5
+ * one axis and gives the other as an extent, as Radar sends it. */
6
+ export function coverageOf(entries: SearchCoverageEntry[]): SearchCoverage {
7
+ return {
8
+ status: entries.length ? 'partial' : 'complete',
9
+ gaps: entries.map((e) => {
10
+ if (e.kind !== '*') return { code: e.reason, kinds: { count: 1, names: [{ kind: e.kind, group: e.group || undefined }] }, namespaces: { extent: 'all' } }
11
+ if (e.namespaces) return { code: e.reason, kinds: { extent: 'all' }, namespaces: { count: e.namespaces.length, names: e.namespaces } }
12
+ if (e.count) return { code: e.reason, kinds: { count: e.count }, namespaces: { extent: 'all' } }
13
+ return { code: e.reason, kinds: { extent: 'unknown' }, namespaces: { extent: 'all' } }
14
+ }),
15
+ }
16
+ }