@skyhook-io/radar-app 1.21.6 → 1.21.7

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 (107) hide show
  1. package/README.md +1 -1
  2. package/package.json +7 -7
  3. package/src/App.tsx +19 -1
  4. package/src/RadarApp.tsx +8 -2
  5. package/src/api/client.discoverMetrics.test.tsx +69 -0
  6. package/src/api/client.issueCorrelation.test.tsx +244 -0
  7. package/src/api/client.issueRowChanges.test.tsx +129 -0
  8. package/src/api/client.pendingOwnership.test.tsx +197 -0
  9. package/src/api/client.prometheusStatus.test.ts +4 -0
  10. package/src/api/client.restartError.test.ts +36 -1
  11. package/src/api/client.stopWorkflow.test.tsx +133 -0
  12. package/src/api/client.submitWorkflowTemplate.test.tsx +127 -0
  13. package/src/api/client.ts +572 -111
  14. package/src/api/connectionBinding.test.tsx +3 -1
  15. package/src/api/connectionBinding.ts +14 -2
  16. package/src/api/gitOpsPermissions.render.test.tsx +155 -0
  17. package/src/api/gitOpsPermissions.test.ts +90 -0
  18. package/src/api/gitOpsPermissions.ts +51 -0
  19. package/src/api/httpErrors.test.ts +30 -1
  20. package/src/api/httpErrors.ts +17 -0
  21. package/src/api/openobserveSetup.ts +85 -0
  22. package/src/api/podDebug.test.tsx +137 -0
  23. package/src/api/podDebug.ts +82 -0
  24. package/src/api/prometheusCharts.test.ts +23 -0
  25. package/src/api/prometheusCharts.ts +25 -0
  26. package/src/api/radarFeatures.render.test.tsx +43 -2
  27. package/src/api/radarFeatures.test.ts +18 -1
  28. package/src/api/radarFeatures.ts +17 -4
  29. package/src/api/reviewedActionMutation.ts +9 -2
  30. package/src/api/workloadMetrics.ts +2 -0
  31. package/src/components/applications/ApplicationsView.openResource.test.tsx +137 -11
  32. package/src/components/applications/ApplicationsView.tsx +56 -31
  33. package/src/components/cnpg/host.test.tsx +1 -1
  34. package/src/components/cnpg/host.tsx +0 -2
  35. package/src/components/dock/BottomDock.tsx +7 -3
  36. package/src/components/dock/MissingShellDebug.test.tsx +193 -0
  37. package/src/components/dock/MissingShellDebug.tsx +114 -0
  38. package/src/components/dock/PodDebugSession.test.tsx +60 -0
  39. package/src/components/dock/PodDebugSession.tsx +96 -0
  40. package/src/components/dock/TerminalTab.test.tsx +48 -4
  41. package/src/components/dock/TerminalTab.tsx +47 -25
  42. package/src/components/dock/WorkloadLogsTab.test.tsx +24 -1
  43. package/src/components/dock/WorkloadLogsTab.tsx +16 -0
  44. package/src/components/execution/BatchExecutionView.command.test.tsx +69 -0
  45. package/src/components/execution/BatchExecutionView.tsx +88 -5
  46. package/src/components/execution/BatchExecutionView.workflow-stop.test.tsx +69 -0
  47. package/src/components/execution/WorkflowRunStopAction.tsx +8 -0
  48. package/src/components/gitops/GitOpsPermissionRowActions.test.tsx +100 -0
  49. package/src/components/gitops/GitOpsPermissionRowActions.tsx +27 -0
  50. package/src/components/gitops/GitOpsView.identity.test.tsx +1 -0
  51. package/src/components/gitops/GitOpsView.permissions.test.tsx +102 -0
  52. package/src/components/gitops/GitOpsView.syncRequest.test.tsx +95 -7
  53. package/src/components/gitops/GitOpsView.tsx +93 -32
  54. package/src/components/helm/OwnedResources.tsx +1 -0
  55. package/src/components/home/mcpToolCatalog.ts +1 -0
  56. package/src/components/issues/IssuesPane.render.test.tsx +1 -1
  57. package/src/components/issues/IssuesPane.tsx +11 -0
  58. package/src/components/issues/useIssueExpansion.ts +91 -0
  59. package/src/components/resource/MetricsNotConnected.test.tsx +50 -0
  60. package/src/components/resource/MetricsNotConnected.tsx +114 -0
  61. package/src/components/resource/PVCUsageBar.tsx +2 -1
  62. package/src/components/resource/PrometheusCharts.render.test.tsx +47 -0
  63. package/src/components/resource/PrometheusCharts.tsx +14 -2
  64. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +91 -1
  65. package/src/components/resource/PrometheusChartsGrid.tsx +28 -52
  66. package/src/components/resource/RestartChart.tsx +4 -3
  67. package/src/components/resource/RightsizingPanel.source.test.tsx +34 -0
  68. package/src/components/resource/RightsizingStrip.tsx +5 -3
  69. package/src/components/resource/WorkloadMetricsSection.render.test.tsx +6 -0
  70. package/src/components/resource/WorkloadMetricsSection.tsx +14 -11
  71. package/src/components/resource/nameMatchedScope.ts +9 -3
  72. package/src/components/resources/EmptyNamespaceHint.tsx +42 -0
  73. package/src/components/resources/PodDebugAction.test.tsx +157 -0
  74. package/src/components/resources/PodDebugAction.tsx +207 -0
  75. package/src/components/resources/PodDebugPermission.tsx +21 -0
  76. package/src/components/resources/ResourcesView.empty-hint.test.tsx +132 -0
  77. package/src/components/resources/ResourcesView.tsx +39 -5
  78. package/src/components/resources/namespaceHint.test.ts +34 -0
  79. package/src/components/resources/namespaceHint.ts +19 -0
  80. package/src/components/resources/renderers/AdmissionPolicyRenderers.tsx +135 -0
  81. package/src/components/resources/renderers/NodeRenderer.tsx +2 -1
  82. package/src/components/resources/renderers/PodRenderer.tsx +12 -5
  83. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.test.tsx +24 -1
  84. package/src/components/settings/LocalIntegrationStatus.tsx +14 -3
  85. package/src/components/settings/MetricsBackendSwitch.tsx +167 -0
  86. package/src/components/settings/OpenObserveSetup.test.tsx +343 -0
  87. package/src/components/settings/OpenObserveSetup.tsx +358 -0
  88. package/src/components/settings/SettingsDialog.tsx +21 -7
  89. package/src/components/settings/openobserveStatus.test.ts +34 -0
  90. package/src/components/settings/openobserveStatus.ts +55 -0
  91. package/src/components/timeline/TimelineList.selection.test.tsx +40 -0
  92. package/src/components/timeline/TimelineList.test.ts +18 -0
  93. package/src/components/timeline/TimelineList.tsx +19 -5
  94. package/src/components/timeline/TimelineView.tsx +2 -0
  95. package/src/components/workload/WorkloadView.pendingOwnership.test.tsx +34 -0
  96. package/src/components/workload/WorkloadView.tabUrl.test.tsx +44 -0
  97. package/src/components/workload/WorkloadView.tsx +95 -10
  98. package/src/context/TimelineNavigation.test.ts +59 -0
  99. package/src/context/TimelineNavigation.tsx +86 -0
  100. package/src/contexts/CapabilitiesContext.tsx +3 -1
  101. package/src/hooks/useResourceCounts.ts +2 -1
  102. package/src/hooks/useWorkflowStopAction.ts +31 -0
  103. package/src/index.css +1 -0
  104. package/src/integrations/resourceHosts.test.tsx +2 -2
  105. package/src/integrations/resourceHosts.tsx +4 -2
  106. package/src/k8s-ui-exports.test.ts +10 -0
  107. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.tsx +0 -128
@@ -0,0 +1,8 @@
1
+ import { WorkflowStopAction } from '@skyhook-io/k8s-ui'
2
+ import { useWorkflowStopAction } from '../../hooks/useWorkflowStopAction'
3
+
4
+ /** Stop / Terminate for a child Workflow selected in a scheduled parent's run view. */
5
+ export function WorkflowRunStopAction({ workflow, namespace, name }: { workflow: unknown; namespace: string; name: string }) {
6
+ const stop = useWorkflowStopAction('workflows', 'argoproj.io', namespace)
7
+ return <WorkflowStopAction data={workflow} namespace={namespace} name={name} {...stop} />
8
+ }
@@ -0,0 +1,100 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { RefreshCw } from 'lucide-react'
6
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
7
+ import type { GitOpsRow } from '@skyhook-io/k8s-ui'
8
+ import { GitOpsPermissionRowActions } from './GitOpsPermissionRowActions'
9
+
10
+ vi.mock('../../context/RadarUpgradeHost', () => ({ useRadarUpgradeHost: () => ({}) }))
11
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
12
+ const row = { kindName: 'applications', group: 'argoproj.io', namespace: 'argocd', name: 'demo' } as GitOpsRow
13
+ const note = "Couldn't check your permissions. You can still try."
14
+ const sync = vi.fn()
15
+ let client: QueryClient
16
+ let host: HTMLDivElement
17
+ let root: ReturnType<typeof createRoot>
18
+ let answer: () => Promise<Response>
19
+ const requests = vi.fn((input: RequestInfo | URL) => String(input).includes('/gitops/capabilities/') ? answer() : new Promise<Response>(() => {}))
20
+
21
+ beforeEach(async () => {
22
+ vi.useFakeTimers()
23
+ sync.mockClear()
24
+ requests.mockClear()
25
+ answer = () => new Promise<Response>(() => {})
26
+ vi.stubGlobal('fetch', requests)
27
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
28
+ client.setQueryData(['capabilities'], { features: { gitopsActionCapabilities: true } })
29
+ host = document.createElement('div')
30
+ document.body.append(host)
31
+ root = createRoot(host)
32
+ await act(async () => root.render(
33
+ <QueryClientProvider client={client}>
34
+ <GitOpsPermissionRowActions row={row} items={[{ key: 'sync', label: 'Sync', icon: RefreshCw, onClick: sync }]} />
35
+ </QueryClientProvider>,
36
+ ))
37
+ })
38
+ afterEach(async () => {
39
+ await act(async () => root.unmount())
40
+ client.clear()
41
+ host.remove()
42
+ vi.useRealTimers()
43
+ vi.unstubAllGlobals()
44
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
45
+ })
46
+ async function openMenu() {
47
+ await act(async () => host.querySelector<HTMLButtonElement>('[aria-label="Row actions"]')!.click())
48
+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })
49
+ }
50
+ const action = () => host.querySelector<HTMLButtonElement>('[role="menuitem"]')!
51
+
52
+ it('shows the unavailable note only in the open menu after a failed check and permits the action', async () => {
53
+ let reject: (error: Error) => void
54
+ answer = () => new Promise((_, fail) => { reject = fail })
55
+ expect(requests.mock.calls.some(([url]) => String(url).includes('/gitops/capabilities/'))).toBe(false)
56
+ expect(host.textContent).not.toContain(note)
57
+ await openMenu()
58
+ expect(host.textContent).not.toContain(note)
59
+ await act(async () => {
60
+ reject!(new Error('Permission check failed'))
61
+ await vi.advanceTimersByTimeAsync(1)
62
+ })
63
+ const menu = host.querySelector('[role="menu"]')!
64
+ expect(menu.querySelector('p')!.textContent).toBe(note)
65
+ expect(menu.querySelector('p')!.className).toContain('text-theme-text-secondary')
66
+ expect(menu.querySelectorAll('button')).toHaveLength(1)
67
+ expect(action().disabled).toBe(false)
68
+ expect(action().getAttribute('aria-disabled')).not.toBe('true')
69
+ await act(async () => action().click())
70
+ expect(sync).toHaveBeenCalledOnce()
71
+ await act(async () => { await vi.advanceTimersByTimeAsync(1000) })
72
+ expect(host.querySelector('[role="menu"]')).toBeNull()
73
+ expect(host.textContent).not.toContain(note)
74
+ })
75
+
76
+ it('shows the unavailable note and enables an expired denial while checks remain pending', async () => {
77
+ answer = async () => Response.json({ actions: { sync: { allowed: false, denied: [{ verb: 'patch', resource: 'applications', group: 'argoproj.io', namespace: 'argocd', name: 'demo' }] } } })
78
+ await openMenu()
79
+ expect(action().getAttribute('aria-disabled')).toBe('true')
80
+ expect(host.textContent).not.toContain(note)
81
+ answer = () => new Promise<Response>(() => {})
82
+ await act(async () => { await vi.advanceTimersByTimeAsync(119_998) })
83
+ expect(action().getAttribute('aria-disabled')).toBe('true')
84
+ await act(async () => { await vi.advanceTimersByTimeAsync(2) })
85
+ expect(host.querySelector('[role="menu"]')!.textContent).toContain(note)
86
+ expect(action().disabled).toBe(false)
87
+ expect(action().getAttribute('aria-disabled')).not.toBe('true')
88
+ await act(async () => action().click())
89
+ expect(sync).toHaveBeenCalledOnce()
90
+ })
91
+
92
+ it('keeps a denied action disabled while the row menu closes', async () => {
93
+ answer = async () => Response.json({ actions: { sync: { allowed: false, denied: [{ verb: 'patch', resource: 'applications', group: 'argoproj.io', namespace: 'argocd', name: 'demo' }] } } })
94
+ await openMenu()
95
+ expect(action().getAttribute('aria-disabled')).toBe('true')
96
+
97
+ await act(async () => host.querySelector<HTMLButtonElement>('[aria-label="Row actions"]')!.click())
98
+ expect(host.querySelector('[role="menu"]')?.hasAttribute('inert')).toBe(true)
99
+ expect(action().getAttribute('aria-disabled')).toBe('true')
100
+ })
@@ -0,0 +1,27 @@
1
+ import type { ReactNode } from 'react'
2
+ import { RowActionMenu, type RowActionItem } from '@skyhook-io/k8s-ui/components/ui/RowActionMenu'
3
+ import type { GitOpsRow } from '@skyhook-io/k8s-ui'
4
+ import { useGitOpsActionCapabilities } from '../../api/client'
5
+
6
+ export function GitOpsPermissionRowActions({ row, items }: { row: GitOpsRow; items: RowActionItem[] }) {
7
+ return (
8
+ <RowActionMenu items={items} renderOpenItems={(render, open) => (
9
+ <PermissionItems row={row} items={items} render={render} open={open} />
10
+ )} />
11
+ )
12
+ }
13
+
14
+ function PermissionItems({ row, items, render, open }: {
15
+ row: GitOpsRow
16
+ items: RowActionItem[]
17
+ render: (items: RowActionItem[], note?: string) => ReactNode
18
+ open: boolean
19
+ }) {
20
+ const { disabledReasons, permissionCheckUnavailable } = useGitOpsActionCapabilities(row.kindName, row.group, row.namespace, row.name, open)
21
+ const actions = items.map(item => {
22
+ const action = item.key === 'hard-refresh' ? 'refresh' : item.key
23
+ const reason = item.disabledReason || disabledReasons[action]
24
+ return { ...item, disabled: item.disabled || !!reason, disabledReason: reason }
25
+ })
26
+ return render(actions, permissionCheckUnavailable ? "Couldn't check your permissions. You can still try." : undefined)
27
+ }
@@ -19,6 +19,7 @@ vi.mock('../../api/client', async (importOriginal) => {
19
19
  }
20
20
  })
21
21
  vi.mock('../ui/Toast', () => ({ useToast: () => ({ showError: vi.fn(), showSuccess: vi.fn(), showToast: vi.fn() }) }))
22
+ vi.mock('../../context/ConnectionContext', () => ({ useConnection: () => ({ connection: { state: 'connected', context: 'test' } }) }))
22
23
  vi.mock('../useContextSwitchFlow', () => ({ useContextSwitchFlow: () => ({ confirmDialog: null }) }))
23
24
  vi.mock('./useDestinationCluster', () => ({ useDestinationCluster: (...args: unknown[]) => { destinationRequest(...args); return {} } }))
24
25
  vi.mock('../../hooks/useKeyboardShortcuts', () => ({ useRegisterShortcut: () => {} }))
@@ -0,0 +1,102 @@
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 { QueryClient, QueryClientProvider } from '@tanstack/react-query'
6
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
7
+ import type { GitOpsRow } from '@skyhook-io/k8s-ui'
8
+ import type { ArgoSyncOpts } from '@skyhook-io/k8s-ui/components/gitops/SyncOptionsDialog'
9
+ import { GitOpsView } from './GitOpsView'
10
+
11
+ const harness = vi.hoisted(() => ({ sync: vi.fn(), confirm: undefined as undefined | ((opts: ArgoSyncOpts) => void) }))
12
+ const row = { id: 'demo', kindName: 'applications', group: 'argoproj.io', namespace: 'argocd', name: 'demo', tool: 'argo' } as GitOpsRow
13
+
14
+ vi.mock('@skyhook-io/k8s-ui', async importOriginal => {
15
+ const actual = await importOriginal<typeof import('@skyhook-io/k8s-ui')>()
16
+ return {
17
+ ...actual,
18
+ GitOpsTableView: ({ onRowAction }: { onRowAction: (row: GitOpsRow, action: 'sync') => void }) => <button onClick={() => onRowAction(row, 'sync')}>Open sync</button>,
19
+ SyncOptionsDialog: (props: Parameters<typeof actual.SyncOptionsDialog>[0]) => {
20
+ harness.confirm = props.onConfirm
21
+ return <actual.SyncOptionsDialog {...props} />
22
+ },
23
+ }
24
+ })
25
+ vi.mock('../../api/client', async importOriginal => {
26
+ const actual = await importOriginal<typeof import('../../api/client')>()
27
+ const idle = () => ({ mutate: vi.fn(), isPending: false })
28
+ return {
29
+ ...actual,
30
+ useArgoSync: () => ({ mutate: harness.sync, reset: vi.fn(), isPending: false }),
31
+ useArgoRefresh: idle, useArgoTerminate: idle, useArgoSuspend: idle, useArgoResume: idle,
32
+ useFluxReconcile: idle, useFluxSyncWithSource: idle, useFluxSuspend: idle, useFluxResume: idle,
33
+ }
34
+ })
35
+ vi.mock('../../api/apiResources', async (importOriginal) => ({
36
+ ...(await importOriginal<typeof import('../../api/apiResources')>()),
37
+ useAPIResources: () => ({ data: [], isLoading: false }),
38
+ }))
39
+ vi.mock('../../context/ConnectionContext', () => ({ useConnection: () => ({ connection: { state: 'connected' } }) }))
40
+ vi.mock('../../context/RadarUpgradeHost', () => ({ useRadarUpgradeHost: () => ({}) }))
41
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
42
+ let client: QueryClient
43
+ let host: HTMLDivElement
44
+ let root: ReturnType<typeof createRoot>
45
+ let allowed: boolean
46
+ const requests = vi.fn(async (input: RequestInfo | URL) => {
47
+ if (String(input).includes('/gitops/capabilities/')) {
48
+ return Response.json({ actions: { sync: allowed ? { allowed } : { allowed, denied: [{ verb: 'patch', resource: 'applications', group: 'argoproj.io', namespace: 'argocd', kind: 'Application', name: 'demo' }] } } })
49
+ }
50
+ return Response.json({ counts: {} })
51
+ })
52
+ const flush = async () => { await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)) }) }
53
+ beforeEach(async () => {
54
+ allowed = true
55
+ harness.sync.mockClear()
56
+ requests.mockClear()
57
+ vi.stubGlobal('fetch', requests)
58
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
59
+ client.setQueryData(['capabilities'], { features: { gitopsActionCapabilities: true } })
60
+ client.setQueryData(['gitops-rows-main', [], 0], { coverageStatus: 'complete', rows: [row] })
61
+ host = document.createElement('div')
62
+ document.body.append(host)
63
+ root = createRoot(host)
64
+ await act(async () => root.render(<MemoryRouter><QueryClientProvider client={client}><GitOpsView namespaces={[]} onOpenResource={() => {}} /></QueryClientProvider></MemoryRouter>))
65
+ await flush()
66
+ })
67
+ afterEach(async () => {
68
+ await act(async () => root.unmount())
69
+ client.clear()
70
+ host.remove()
71
+ vi.unstubAllGlobals()
72
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
73
+ })
74
+ it('keeps capabilities active while table Sync is open and blocks a later denial at the button and callback', async () => {
75
+ const count = () => requests.mock.calls.filter(([url]) => String(url).includes('/gitops/capabilities/')).length
76
+ expect(count()).toBe(0)
77
+ await act(async () => host.querySelector<HTMLButtonElement>('button')!.click())
78
+ await flush()
79
+ expect(count()).toBe(1)
80
+ const confirm = () => [...document.querySelectorAll<HTMLButtonElement>('[role="dialog"] button')].find(button => button.textContent === 'Sync now')!
81
+ expect(confirm().disabled).toBe(false)
82
+ allowed = false
83
+ await act(async () => { await client.refetchQueries({ queryKey: ['gitops-action-capabilities'], type: 'active' }) })
84
+ await flush()
85
+ expect(count()).toBe(2)
86
+ expect(confirm().disabled).toBe(true)
87
+ expect(document.querySelector('[role="dialog"]')!.textContent).toContain("Kubernetes denied permission to patch Argo CD Application demo in argocd.")
88
+ await act(async () => harness.confirm!({ prune: false, dryRun: false, force: false, applyOnly: false, syncOptions: [] }))
89
+ expect(harness.sync).not.toHaveBeenCalled()
90
+ const cancel = [...document.querySelectorAll<HTMLButtonElement>('[role="dialog"] button')].find(button => button.textContent === 'Cancel')!
91
+ expect(cancel.disabled).toBe(false)
92
+ await act(async () => cancel.click())
93
+ await act(async () => { await client.refetchQueries({ queryKey: ['gitops-action-capabilities'], type: 'active' }) })
94
+ expect(count()).toBe(2)
95
+ })
96
+ it('submits an allowed table Sync with the selected object', async () => {
97
+ await act(async () => host.querySelector<HTMLButtonElement>('button')!.click())
98
+ await flush()
99
+ const confirm = [...document.querySelectorAll<HTMLButtonElement>('[role="dialog"] button')].find(button => button.textContent === 'Sync now')!
100
+ await act(async () => confirm.click())
101
+ expect(harness.sync).toHaveBeenCalledWith(expect.objectContaining({ namespace: 'argocd', name: 'demo' }), expect.any(Object))
102
+ })
@@ -1,12 +1,14 @@
1
1
  // @vitest-environment jsdom
2
2
  import { act } from 'react'
3
3
  import { createRoot } from 'react-dom/client'
4
- import { MemoryRouter } from 'react-router-dom'
4
+ import { MemoryRouter, useNavigate } from 'react-router-dom'
5
5
  import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
6
6
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
7
7
  import { normalizeArgoApplication } from '@skyhook-io/k8s-ui'
8
8
  import type { ArgoActionHandlers, GitOpsInsight, GitOpsInsightRef, GitOpsRow, GitOpsRowAction } from '@skyhook-io/k8s-ui'
9
9
  import { GitOpsView } from './GitOpsView'
10
+ import { isShownInline } from '../../api/httpErrors'
11
+ import { observeConnectionStatus, resetConnectionBindingForTest } from '../../api/connectionBinding'
10
12
 
11
13
  // The requests the Sync dialog builds, sent by the real useArgoSync and
12
14
  // useArgoResourceValidation: only a Radar advertising argoSyncInheritance is
@@ -29,23 +31,26 @@ vi.mock('@skyhook-io/k8s-ui', async (importOriginal) => {
29
31
  const actual = await importOriginal<typeof import('@skyhook-io/k8s-ui')>()
30
32
  return {
31
33
  ...actual,
32
- useToast: () => ({ showError: vi.fn(), showSuccess: vi.fn(), showToast: vi.fn() }),
34
+ useToast: () => ({ showError: toast.error, showSuccess: vi.fn(), showToast: vi.fn() }),
33
35
  GitOpsTableView: (props: { rows: GitOpsRow[]; onRowAction: (row: GitOpsRow, action: GitOpsRowAction) => void }) => (
34
36
  <button type="button" onClick={() => props.onRowAction(props.rows[0], 'sync')}>Open sync</button>
35
37
  ),
36
- GitOpsDetailLayout: (props: { argo?: ArgoActionHandlers; renderTabBody: (ctx: { tab: 'changes'; fullscreen: boolean }) => React.ReactNode; children?: React.ReactNode }) => (
37
- <div data-resume-settings={JSON.stringify(props.argo?.resumeSettings ?? null)}>
38
+ GitOpsDetailLayout: (props: { argo?: ArgoActionHandlers; onRemediate?: (remediation: { kind: 'create-namespace'; target: string }) => void; renderTabBody: (ctx: { tab: 'changes'; fullscreen: boolean }) => React.ReactNode; children?: React.ReactNode }) => {
39
+ const navigate = useNavigate()
40
+ return <div data-resume-settings={JSON.stringify(props.argo?.resumeSettings ?? null)}>
38
41
  <button type="button" onClick={() => props.argo?.onSyncRequested()}>Open sync</button>
42
+ <button type="button" onClick={() => navigate('/gitops/detail/applications/argocd/other?apiGroup=argoproj.io')}>Open other Application</button>
43
+ <button type="button" onClick={() => props.onRemediate?.({kind: 'create-namespace', target: 'sandbox'})}>Create namespace and retry</button>
39
44
  {props.renderTabBody({ tab: 'changes', fullscreen: false })}
40
45
  {props.children}
41
46
  </div>
42
- ),
47
+ },
43
48
  GitOpsChangesView: (props: { onSyncResource?: (ref: GitOpsInsightRef) => void }) => (
44
49
  <button type="button" onClick={() => props.onSyncResource?.(deployment)}>Open resource sync</button>
45
50
  ),
46
51
  }
47
52
  })
48
- const toast = vi.hoisted(() => ({ success: vi.fn() }))
53
+ const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }))
49
54
  vi.mock('../ui/Toast', async (importOriginal) => ({
50
55
  ...(await importOriginal<typeof import('../ui/Toast')>()),
51
56
  showApiSuccess: toast.success,
@@ -59,7 +64,7 @@ vi.mock('../../api/client', async (importOriginal) => {
59
64
  useGitOpsTree: () => ({ data: undefined, isLoading: false, error: null }),
60
65
  useGitOpsInsights: () => ({ data: insight, isLoading: false, error: null }),
61
66
  useArgoRollback: idle, useArgoRefresh: idle, useArgoTerminate: idle,
62
- useArgoSuspend: idle, useArgoResume: idle, useApplyResource: idle,
67
+ useArgoSuspend: idle, useArgoResume: idle,
63
68
  useFluxReconcile: idle, useFluxSyncWithSource: idle, useFluxSuspend: idle, useFluxResume: idle,
64
69
  }
65
70
  })
@@ -79,13 +84,28 @@ let client: QueryClient
79
84
  let host: HTMLDivElement
80
85
  let root: ReturnType<typeof createRoot>
81
86
  let requests: Array<{ path: string; body: Record<string, unknown> }>
87
+ let syncDenial: { error: string; error_code: string; summary: string } | undefined
88
+ let pendingSyncResponse: Promise<Response> | undefined
89
+ let pendingNamespaceResponse: Promise<Response> | undefined
82
90
 
83
91
  beforeEach(async () => {
84
92
  requests = []
93
+ syncDenial = undefined
94
+ pendingSyncResponse = undefined
95
+ pendingNamespaceResponse = undefined
96
+ toast.error.mockClear()
85
97
  vi.stubGlobal('fetch', vi.fn((input: RequestInfo | URL, init?: RequestInit) => {
86
98
  const path = String(input)
87
99
  if (init?.method === 'POST') {
100
+ if (path.includes('/resources/apply')) {
101
+ requests.push({ path, body: {} })
102
+ return pendingNamespaceResponse ?? Promise.resolve(Response.json([]))
103
+ }
88
104
  requests.push({ path, body: JSON.parse(String(init.body)) })
105
+ if (path.endsWith('/sync') && pendingSyncResponse) return pendingSyncResponse
106
+ if (path.endsWith('/sync') && syncDenial) {
107
+ return Promise.resolve(Response.json(syncDenial, { status: 403 }))
108
+ }
89
109
  const answer = path.endsWith('/validate-resource') ? { outcome: 'succeeded', message: 'ok' } : { message: 'Sync initiated' }
90
110
  return Promise.resolve(new Response(JSON.stringify(answer), { status: 200, headers: { 'Content-Type': 'application/json' } }))
91
111
  }
@@ -102,6 +122,7 @@ beforeEach(async () => {
102
122
  afterEach(async () => {
103
123
  await act(async () => root.unmount())
104
124
  client.clear()
125
+ resetConnectionBindingForTest()
105
126
  host.remove()
106
127
  document.body.innerHTML = ''
107
128
  app.spec.source = {}
@@ -367,3 +388,70 @@ it.each([
367
388
  const settings = document.querySelector('[data-resume-settings]')!.getAttribute('data-resume-settings')!
368
389
  expect(JSON.parse(settings)).toEqual(expected)
369
390
  })
391
+
392
+ it.each([
393
+ '/gitops',
394
+ '/gitops/detail/applications/argocd/guestbook?apiGroup=argoproj.io',
395
+ ])('keeps the failed sync and its original denial in the dialog from %s', async (path) => {
396
+ syncDenial = {
397
+ error: 'admission webhook "change-window" denied the request: frozen',
398
+ error_code: 'admission_denied',
399
+ summary: 'Rejected by admission webhook change-window: frozen',
400
+ }
401
+ await renderView(path)
402
+ await click(button('Open sync'))
403
+ await click(toggle('Prune'))
404
+ await click(button('Sync now'))
405
+ expect(toggle('Prune').checked).toBe(true)
406
+ expect(document.querySelector('[role="dialog"] [role="alert"]')?.textContent).toContain(syncDenial.summary)
407
+ expect(isShownInline(client.getMutationCache().getAll().at(-1)?.state.error)).toBe(true)
408
+ await click(button('Error details'))
409
+ expect(document.querySelector('[role="dialog"] pre')?.textContent).toBe(syncDenial.error)
410
+ await click(button('Cancel'))
411
+ await click(button('Open sync'))
412
+ expect(document.querySelector('[role="dialog"] [role="alert"]')).toBeNull()
413
+ })
414
+
415
+ it('closes a failed sync when the detail page changes Applications', async () => {
416
+ syncDenial = { error: 'denied', error_code: 'admission_denied', summary: 'Change window is closed' }
417
+ await click(button('Open sync'))
418
+ await click(button('Sync now'))
419
+ expect(document.querySelector('[role="dialog"] [role="alert"]')?.textContent).toContain(syncDenial.summary)
420
+ await click(button('Open other Application'))
421
+ const dialog = document.querySelector('[role="dialog"]')
422
+ expect(!dialog || dialog.closest('[inert]')).toBeTruthy()
423
+ await click(button('Open sync'))
424
+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain('argocd/other')
425
+ expect(document.querySelector('[role="dialog"] [role="alert"]')).toBeNull()
426
+ })
427
+
428
+ it('keeps global error reporting for a rejection after leaving the originating Application', async () => {
429
+ let respond!: (response: Response) => void
430
+ pendingSyncResponse = new Promise(resolve => { respond = resolve })
431
+ await click(button('Open sync'))
432
+ await click(button('Sync now'))
433
+ await click(button('Open other Application'))
434
+ await act(async () => respond(Response.json({
435
+ error: 'denied', error_code: 'admission_denied', summary: 'Change window is closed',
436
+ }, { status: 403 })))
437
+ await settle()
438
+ const mutation = client.getMutationCache().getAll().at(-1)
439
+ expect(mutation?.state.status).toBe('error')
440
+ expect(mutation?.options.meta?.errorMessage).toBe('Failed to trigger sync')
441
+ expect(isShownInline(mutation?.state.error)).toBe(false)
442
+ })
443
+
444
+ it('skips automatic Sync if the connection changes after namespace creation starts', async () => {
445
+ let applied!: (response: Response) => void
446
+ pendingNamespaceResponse = new Promise<Response>(resolve => { applied = resolve })
447
+ observeConnectionStatus({ connectionId: 'first-connection' })
448
+ await click(button('Create namespace and retry'))
449
+ expect(requests.map(({ path }) => path)).toEqual([expect.stringContaining('/resources/apply')])
450
+
451
+ observeConnectionStatus({ connectionId: 'next-connection' })
452
+ await act(async () => applied(Response.json([])))
453
+ await settle()
454
+
455
+ expect(requests).toHaveLength(1)
456
+ expect(toast.error).toHaveBeenCalledWith('Created namespace sandbox, but sync failed', expect.stringContaining('cluster connection changed'))
457
+ })