@skyhook-io/radar-app 1.20.1 → 1.20.3

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 (81) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +12 -7
  3. package/src/api/client.namespaceSwitch.hook.test.tsx +170 -1
  4. package/src/api/client.pauseDeployment.test.tsx +77 -0
  5. package/src/api/client.restartError.test.ts +14 -0
  6. package/src/api/client.revisionRefresh.test.tsx +44 -0
  7. package/src/api/client.rollbackError.test.ts +14 -0
  8. package/src/api/client.ts +218 -11
  9. package/src/api/networkAttachments.test.tsx +120 -0
  10. package/src/api/networkAttachments.ts +30 -0
  11. package/src/api/radarFeatures.test.ts +5 -0
  12. package/src/api/radarFeatures.ts +3 -0
  13. package/src/api/secretsStore.test.ts +33 -0
  14. package/src/api/secretsStore.ts +37 -0
  15. package/src/components/ConnectionErrorView.test.tsx +11 -0
  16. package/src/components/ConnectionErrorView.tsx +19 -0
  17. package/src/components/ContextSwitcher.tsx +9 -2
  18. package/src/components/applications/ApplicationsView.openResource.test.tsx +118 -0
  19. package/src/components/applications/ApplicationsView.tsx +8 -11
  20. package/src/components/cost/CostView.tsx +27 -9
  21. package/src/components/diagnose/InvestigationView.tsx +12 -3
  22. package/src/components/diagnose/investigationEvidence/adapters/helm.test.tsx +52 -0
  23. package/src/components/diagnose/investigationEvidence/adapters/helm.ts +10 -0
  24. package/src/components/diagnose/investigationEvidence/bodies/platform.tsx +82 -51
  25. package/src/components/diagnose/investigationEvidence/types.ts +5 -0
  26. package/src/components/dock/TerminalPreferences.query.test.tsx +57 -0
  27. package/src/components/dock/TerminalPreferences.test.tsx +68 -0
  28. package/src/components/dock/TerminalPreferences.tsx +73 -0
  29. package/src/components/gitops/GitOpsView.tsx +1 -9
  30. package/src/components/helm/HelmReleaseDrawer.tsx +24 -12
  31. package/src/components/helm/HelmView.tsx +5 -3
  32. package/src/components/helm/NotCheckedBadge.test.tsx +62 -0
  33. package/src/components/helm/NotCheckedBadge.tsx +39 -0
  34. package/src/components/helm/OwnedResources.test.tsx +86 -0
  35. package/src/components/helm/OwnedResources.tsx +65 -8
  36. package/src/components/home/ClusterHealthCard.heading.test.tsx +72 -0
  37. package/src/components/home/ClusterHealthCard.test.ts +44 -1
  38. package/src/components/home/ClusterHealthCard.tsx +22 -10
  39. package/src/components/home/HelmSummary.tsx +15 -15
  40. package/src/components/home/mcpToolCatalog.ts +2 -2
  41. package/src/components/resource/RightsizingStrip.test.ts +57 -0
  42. package/src/components/resource/RightsizingStrip.tsx +53 -4
  43. package/src/components/resources/ImageFilesystemModal.test.tsx +74 -6
  44. package/src/components/resources/ImageFilesystemModal.tsx +98 -6
  45. package/src/components/resources/PodFileUploadPanel.tsx +150 -0
  46. package/src/components/resources/PodFilesystemModal.tsx +246 -3
  47. package/src/components/resources/pod-file-upload.test.tsx +223 -0
  48. package/src/components/resources/pod-file-upload.ts +266 -0
  49. package/src/components/resources/renderers/HTTPRouteRenderer.test.tsx +50 -0
  50. package/src/components/resources/renderers/HTTPRouteRenderer.tsx +27 -0
  51. package/src/components/resources/renderers/PodRenderer.tsx +26 -1
  52. package/src/components/resources/renderers/SecretProviderClassRenderer.tsx +25 -0
  53. package/src/components/rightsizing/RightsizingScanView.tsx +16 -1
  54. package/src/components/rightsizing/model.test.ts +11 -0
  55. package/src/components/rightsizing/model.ts +3 -1
  56. package/src/components/rightsizing/presentation.test.ts +46 -0
  57. package/src/components/rightsizing/presentation.ts +17 -2
  58. package/src/components/traffic/TrafficView.tsx +27 -27
  59. package/src/components/traffic/trafficFilters.test.ts +18 -1
  60. package/src/components/traffic/trafficFilters.ts +30 -1
  61. package/src/components/ui/Omnibar.tsx +4 -1
  62. package/src/components/ui/RadarOmnibar.test.tsx +55 -2
  63. package/src/components/ui/RadarOmnibar.tsx +7 -1
  64. package/src/components/ui/SearchSyntaxHelp.test.tsx +9 -2
  65. package/src/components/ui/SearchSyntaxHelp.tsx +3 -2
  66. package/src/components/ui/UpdateNotification.test.tsx +23 -1
  67. package/src/components/ui/UpdateNotification.tsx +26 -2
  68. package/src/components/ui/omnibar-match.test.ts +7 -0
  69. package/src/components/ui/omnibar-match.ts +1 -0
  70. package/src/components/ui/searchCoverageNote.test.ts +17 -0
  71. package/src/components/ui/searchCoverageNote.ts +31 -7
  72. package/src/components/useContextSwitchFlow.tsx +9 -1
  73. package/src/components/workload/NodeCertificateEvidence.test.tsx +51 -0
  74. package/src/components/workload/NodeCertificateEvidence.tsx +44 -0
  75. package/src/components/workload/WorkloadView.tsx +51 -11
  76. package/src/context/ConnectionContext.test.ts +1 -0
  77. package/src/context/ConnectionContext.tsx +2 -2
  78. package/src/integrations/resourceHosts.test.tsx +2 -2
  79. package/src/integrations/resourceHosts.tsx +4 -0
  80. package/src/utils/namespacePick.test.ts +87 -0
  81. package/src/utils/namespacePick.ts +88 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skyhook-io/radar-app",
3
- "version": "1.20.1",
3
+ "version": "1.20.3",
4
4
  "description": "Radar's full web UI as a reusable React component. Used by Radar's own binary and by external consumers like Radar Cloud.",
5
5
  "repository": {
6
6
  "type": "git",
package/src/App.tsx CHANGED
@@ -30,6 +30,7 @@ import { ApplicationsView } from './components/applications/ApplicationsView'
30
30
  import { HelmReleaseDrawer } from './components/helm/HelmReleaseDrawer'
31
31
  import { PortForwardProvider, PortForwardIndicator, PortForwardPanel } from './components/portforward/PortForwardManager'
32
32
  import { DockProvider, BottomDock, useDock, useDockReservedHeight, useOpenLocalTerminal } from './components/dock'
33
+ import { TerminalPreferences } from './components/dock/TerminalPreferences'
33
34
  import { DURATION_DOCK, overlayExitMs } from '@skyhook-io/k8s-ui/utils/animation'
34
35
  import { ContextSwitcher } from './components/ContextSwitcher'
35
36
  import { NamespaceSwitcher, type NamespaceSwitcherHandle } from './components/NamespaceSwitcher'
@@ -62,7 +63,7 @@ import { useProductHuntRailEntry } from './components/product-hunt/useProductHun
62
63
  import { ShortcutHelpOverlay } from './components/ui/ShortcutHelpOverlay'
63
64
  import { DiagnosticsOverlay, type DiagnosticsFocus } from './components/ui/DiagnosticsOverlay'
64
65
  import { useEventSource } from './hooks/useEventSource'
65
- import { debugNamespaceLog, refetchOnResourceEvents, resourceEventKey, useNamespaces, useNamespaceScope, useSetActiveNamespace, useSwitchContext, useAuthMe, useAudit, useClusterInfo } from './api/client'
66
+ import { debugNamespaceLog, refetchOnResourceEvents, resourceEventKey, useNamespaces, useNamespaceScope, useSetActiveNamespace, isAppliedNamespaceSwitch, useSwitchContext, useAuthMe, useAudit, useClusterInfo } from './api/client'
66
67
  import { buildAuditSeverityMap } from './utils/auditBadges'
67
68
  import { isInNamespaceScope, scopeNodesToNamespaces } from './utils/topology-namespace'
68
69
  import { routePath, apiUrl, getApiBase, getAuthHeaders, getCredentialsMode, stripBasename } from './api/config'
@@ -1036,9 +1037,9 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1036
1037
  // Fetch available namespaces
1037
1038
  const { data: availableNamespaces } = useNamespaces()
1038
1039
 
1039
- // Per-user view filter served by the backend. Loaded eagerly so the
1040
- // picker can render its current state without showing the multi-select
1041
- // fallback during the initial scope fetch.
1040
+ // This tab's namespace pick plus the picker's source list (see
1041
+ // utils/namespacePick). Loaded eagerly so the picker can render its current
1042
+ // state without showing the multi-select fallback during the initial fetch.
1042
1043
  const { data: namespaceScope } = useNamespaceScope()
1043
1044
 
1044
1045
  // Context switch state
@@ -1381,8 +1382,9 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1381
1382
  showClusterWarmupLabel ? clusterLoadState.message :
1382
1383
  crdDiscoveryStatus === 'discovering' ? 'Discovering Custom Resources…' :
1383
1384
  ''
1385
+ // A settings error (ConnectionErrorView) clears only on restart.
1384
1386
  const showHeaderReconnect =
1385
- clusterConnectionState === 'disconnected' ||
1387
+ (clusterConnectionState === 'disconnected' && connection.errorType !== 'settings') ||
1386
1388
  liveUpdatesDisconnected
1387
1389
  const headerReconnect = clusterConnectionState === 'disconnected' ? retryConnection : reconnectEventStream
1388
1390
  const headerReconnectPending = clusterConnectionState === 'disconnected' ? isRetrying : false
@@ -1451,7 +1453,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1451
1453
  // Serialize namespaces for stable dependency tracking
1452
1454
  const namespacesKey = namespaces.join(',')
1453
1455
 
1454
- // The server is canonical for the per-user namespace pick. Mirror its
1456
+ // The scope query holds this tab's namespace pick. Mirror its
1455
1457
  // `actives` into App.tsx state so consumer hooks (SSE, dashboard, resource
1456
1458
  // lists) stay in lockstep with the picker. The dedicated URL-write effect
1457
1459
  // below propagates the mirrored state to `?namespaces=`.
@@ -1475,7 +1477,8 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1475
1477
  if (namespaces.length === 0) return
1476
1478
  setActiveNamespace.mutate(
1477
1479
  { namespaces: [] },
1478
- { onSuccess: () => setNamespaces([]) },
1480
+ // A clear answered after a newer switch landed must not override it.
1481
+ { onSuccess: (_scope, _vars, start) => { if (isAppliedNamespaceSwitch(start)) setNamespaces([]) } },
1479
1482
  )
1480
1483
  }, [namespaceScope?.cacheScoped, namespaces.length, setActiveNamespace])
1481
1484
  // Same write as the header picker, which then mirrors it into `namespaces`.
@@ -2661,6 +2664,7 @@ function DockSpacer() {
2661
2664
  // Main App component wrapped with providers
2662
2665
  function App({ manageDocumentTitle = false, documentTitleSuffix, onClusterLoadStateChange }: AppProps) {
2663
2666
  return (
2667
+ <TerminalPreferences>
2664
2668
  <ConnectionProvider>
2665
2669
  <CapabilitiesProvider>
2666
2670
  <RadarUpgradeProvider>
@@ -2678,6 +2682,7 @@ function App({ manageDocumentTitle = false, documentTitleSuffix, onClusterLoadSt
2678
2682
  </RadarUpgradeProvider>
2679
2683
  </CapabilitiesProvider>
2680
2684
  </ConnectionProvider>
2685
+ </TerminalPreferences>
2681
2686
  )
2682
2687
  }
2683
2688
 
@@ -3,7 +3,8 @@ import { act } from "react";
3
3
  import { createRoot } from "react-dom/client";
4
4
  import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
5
5
  import { afterEach, expect, it, vi } from "vitest";
6
- import { useSetActiveNamespace } from "./client";
6
+ import { useNamespaceScope, useSetActiveNamespace } from "./client";
7
+ import { readTabPick, writeTabPick } from "../utils/namespacePick";
7
8
 
8
9
  (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
9
10
 
@@ -52,3 +53,171 @@ it("keeps a timed-out rescope an error even when the scope already names its tar
52
53
  expect(outcome).toMatch(/rescope timed out/);
53
54
  expect(calls).not.toContain("GET /api/cluster/namespace-scope");
54
55
  });
56
+
57
+ const tabScope = { actives: [] as string[], context: "ctx-a", kubeconfigNamespace: "", mode: "cluster-wide", accessibleNamespaces: ["team-a", "team-b"], deniedNamespaces: [], authoritative: true, canClearNamespace: true, cacheScoped: false, namespaceRescope: false };
58
+
59
+ // Each POST answers when its gate opens, with the server's stored pick after
60
+ // the write, which another tab may already have changed.
61
+ function serveSwitches(serverActives: () => string[]) {
62
+ const gates: Array<() => void> = [];
63
+ vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => {
64
+ const body = () => new Response(JSON.stringify({ ...tabScope, actives: serverActives() }), { status: 200, headers: { "Content-Type": "application/json" } });
65
+ if (init?.method !== "POST") return Promise.resolve(body());
66
+ return new Promise<Response>(resolve => gates.push(() => resolve(body())));
67
+ }));
68
+ return gates;
69
+ }
70
+
71
+ function mountSwitcher(client: QueryClient) {
72
+ let mutate!: ReturnType<typeof useSetActiveNamespace>["mutateAsync"];
73
+ function Probe() {
74
+ mutate = useSetActiveNamespace().mutateAsync;
75
+ return null;
76
+ }
77
+ const root = createRoot(document.createElement("div"));
78
+ act(() => root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>));
79
+ return { mutate: (namespaces: string[]) => mutate({ namespaces }), unmount: () => act(() => root.unmount()) };
80
+ }
81
+
82
+ it("records the pick this tab asked for, not the one another tab stored meanwhile", async () => {
83
+ sessionStorage.clear();
84
+ const gates = serveSwitches(() => ["team-b"]);
85
+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
86
+ client.setQueryData(["namespace-scope"], tabScope);
87
+ const { mutate, unmount } = mountSwitcher(client);
88
+ const done = mutate(["team-a", "team-a", ""]);
89
+ await vi.waitFor(() => expect(gates).toHaveLength(1));
90
+ gates[0]();
91
+ await done;
92
+ expect(client.getQueryData<{ actives: string[] }>(["namespace-scope"])?.actives).toEqual(["team-a"]);
93
+ expect(readTabPick("/api", "ctx-a")).toEqual(["team-a"]);
94
+ unmount();
95
+ });
96
+
97
+ it("ignores a switch that answers after a newer one", async () => {
98
+ sessionStorage.clear();
99
+ const gates = serveSwitches(() => []);
100
+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
101
+ client.setQueryData(["namespace-scope"], tabScope);
102
+ const { mutate, unmount } = mountSwitcher(client);
103
+ const older = mutate(["team-b"]);
104
+ const newer = mutate([]);
105
+ await vi.waitFor(() => expect(gates).toHaveLength(2));
106
+ gates[1]();
107
+ await newer;
108
+ gates[0]();
109
+ await older;
110
+ expect(client.getQueryData<{ actives: string[] }>(["namespace-scope"])?.actives).toEqual([]);
111
+ expect(readTabPick("/api", "ctx-a")).toEqual([]);
112
+ unmount();
113
+ });
114
+
115
+ it("doesn't record a pick whose answer lands after a context switch", async () => {
116
+ sessionStorage.clear();
117
+ const gates = serveSwitches(() => []);
118
+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
119
+ client.setQueryData(["namespace-scope"], tabScope);
120
+ const { mutate, unmount } = mountSwitcher(client);
121
+ const done = mutate(["team-a"]);
122
+ await vi.waitFor(() => expect(gates).toHaveLength(1));
123
+ client.setQueryData(["namespace-scope"], { ...tabScope, context: "ctx-b" });
124
+ gates[0]();
125
+ await done;
126
+ expect(client.getQueryData<{ context: string }>(["namespace-scope"])?.context).toBe("ctx-b");
127
+ expect(readTabPick("/api", "ctx-a")).toBeUndefined();
128
+ unmount();
129
+ });
130
+
131
+ it("drops a requested namespace the answer shows is gone", async () => {
132
+ sessionStorage.clear();
133
+ const gates = serveSwitches(() => ["team-a"]);
134
+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
135
+ client.setQueryData(["namespace-scope"], tabScope);
136
+ const { mutate, unmount } = mountSwitcher(client);
137
+ const done = mutate(["team-a", "deleted-meanwhile"]);
138
+ await vi.waitFor(() => expect(gates).toHaveLength(1));
139
+ gates[0]();
140
+ await done;
141
+ expect(client.getQueryData<{ actives: string[] }>(["namespace-scope"])?.actives).toEqual(["team-a"]);
142
+ expect(readTabPick("/api", "ctx-a")).toEqual(["team-a"]);
143
+ unmount();
144
+ });
145
+
146
+ // A tab with the scope query mounted, as App has it, so an error refetches.
147
+ function mountTab(client: QueryClient) {
148
+ let mutate!: ReturnType<typeof useSetActiveNamespace>["mutateAsync"];
149
+ function Probe() {
150
+ useNamespaceScope();
151
+ mutate = useSetActiveNamespace().mutateAsync;
152
+ return null;
153
+ }
154
+ const root = createRoot(document.createElement("div"));
155
+ act(() => root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>));
156
+ return { mutate: (namespaces: string[]) => mutate({ namespaces }), unmount: () => act(() => root.unmount()) };
157
+ }
158
+
159
+ const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
160
+
161
+ it("keeps an accepted clear when a newer pick is refused", async () => {
162
+ sessionStorage.clear();
163
+ writeTabPick("/api", "ctx-a", ["team-a"]);
164
+ let server = ["team-a"];
165
+ let releaseClear!: () => void;
166
+ vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => {
167
+ if (init?.method !== "POST") return Promise.resolve(json({ ...tabScope, actives: server }));
168
+ const { namespaces } = JSON.parse(String(init.body)) as { namespaces: string[] };
169
+ if (namespaces.includes("secret-ns")) return Promise.resolve(json({ error: "no access to namespace secret-ns" }, 403));
170
+ return new Promise<Response>(resolve => { releaseClear = () => { server = namespaces; resolve(json({ ...tabScope, actives: server })); }; });
171
+ }));
172
+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
173
+ const { mutate, unmount } = mountTab(client);
174
+ await vi.waitFor(() => expect(client.getQueryData<{ actives: string[] }>(["namespace-scope"])?.actives).toEqual(["team-a"]));
175
+ const clear = mutate([]);
176
+ await vi.waitFor(() => expect(releaseClear).toBeDefined());
177
+ await mutate(["secret-ns"]).catch(() => undefined);
178
+ releaseClear();
179
+ await clear;
180
+ await vi.waitFor(() => expect(client.isFetching()).toBe(0));
181
+ expect(client.getQueryData<{ actives: string[] }>(["namespace-scope"])?.actives).toEqual([]);
182
+ expect(readTabPick("/api", "ctx-a")).toEqual([]);
183
+ unmount();
184
+ });
185
+
186
+ it("keeps a switch the server applied when its answer is lost", async () => {
187
+ sessionStorage.clear();
188
+ writeTabPick("/api", "ctx-a", ["team-a"]);
189
+ let server = ["team-a"];
190
+ vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => {
191
+ if (init?.method !== "POST") return Promise.resolve(json({ ...tabScope, actives: server }));
192
+ server = (JSON.parse(String(init.body)) as { namespaces: string[] }).namespaces;
193
+ return Promise.reject(new TypeError("Failed to fetch"));
194
+ }));
195
+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
196
+ const { mutate, unmount } = mountTab(client);
197
+ await vi.waitFor(() => expect(client.getQueryData<{ actives: string[] }>(["namespace-scope"])?.actives).toEqual(["team-a"]));
198
+ await mutate(["team-b"]).catch(() => undefined);
199
+ await vi.waitFor(() => expect(client.isFetching()).toBe(0));
200
+ expect(client.getQueryData<{ actives: string[] }>(["namespace-scope"])?.actives).toEqual(["team-b"]);
201
+ expect(readTabPick("/api", "ctx-a")).toEqual(["team-b"]);
202
+ unmount();
203
+ });
204
+
205
+ it("keeps a switch the server applied when its answer's body is lost", async () => {
206
+ sessionStorage.clear();
207
+ writeTabPick("/api", "ctx-a", ["team-a"]);
208
+ let server = ["team-a"];
209
+ vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => {
210
+ if (init?.method !== "POST") return Promise.resolve(json({ ...tabScope, actives: server }));
211
+ server = (JSON.parse(String(init.body)) as { namespaces: string[] }).namespaces;
212
+ const body = new ReadableStream({ start(controller) { controller.error(new TypeError("network error")); } });
213
+ return Promise.resolve(new Response(body, { status: 200, headers: { "Content-Type": "application/json" } }));
214
+ }));
215
+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
216
+ const { mutate, unmount } = mountTab(client);
217
+ await vi.waitFor(() => expect(client.getQueryData<{ actives: string[] }>(["namespace-scope"])?.actives).toEqual(["team-a"]));
218
+ await mutate(["team-b"]).catch(() => undefined);
219
+ await vi.waitFor(() => expect(client.isFetching()).toBe(0));
220
+ expect(client.getQueryData<{ actives: string[] }>(["namespace-scope"])?.actives).toEqual(["team-b"]);
221
+ expect(readTabPick("/api", "ctx-a")).toEqual(["team-b"]);
222
+ unmount();
223
+ });
@@ -0,0 +1,77 @@
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 { afterEach, beforeEach, expect, it, vi } from 'vitest'
6
+ import { usePauseDeployment, useRadarFeature, useResumeDeployment } from './client'
7
+ import { isRadarFeatureUnsupported } from './radarFeatures'
8
+
9
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
10
+ beforeEach(() => {
11
+ vi.spyOn(console, 'log').mockImplementation(() => {})
12
+ })
13
+ afterEach(() => {
14
+ vi.unstubAllGlobals()
15
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
16
+ vi.restoreAllMocks()
17
+ })
18
+
19
+ const target = { kind: 'deployments', namespace: 'prod', name: 'web' }
20
+
21
+ async function run(action: 'pause' | 'resume', features: Record<string, boolean>, response = new Response('{"message":"ok"}', { status: 200 })) {
22
+ const posts: string[] = []
23
+ vi.stubGlobal('fetch', vi.fn<typeof fetch>(async (input, init) => {
24
+ const url = String(input)
25
+ if (init?.method === 'POST') {
26
+ posts.push(url)
27
+ return response
28
+ }
29
+ if (url.includes('/capabilities')) return new Response(JSON.stringify({ features }), { status: 200 })
30
+ return new Response('{}', { status: 200 })
31
+ }))
32
+
33
+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false }, queries: { retry: false } } })
34
+ const invalidate = vi.spyOn(client, 'invalidateQueries')
35
+ let mutate: (() => Promise<unknown>) | undefined
36
+ let support = ''
37
+ function Probe() {
38
+ const pause = usePauseDeployment()
39
+ const resume = useResumeDeployment()
40
+ support = useRadarFeature('deploymentPause').support
41
+ mutate = () => (action === 'pause' ? pause : resume).mutateAsync(target)
42
+ return null
43
+ }
44
+ const root = createRoot(document.createElement('div'))
45
+ await act(async () => { root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>) })
46
+ await vi.waitFor(() => expect(support).not.toBe('unknown'))
47
+
48
+ let failure: unknown
49
+ await act(async () => { try { await mutate!() } catch (err) { failure = err } })
50
+ const invalidated = invalidate.mock.calls.map(([filters]) => JSON.stringify(filters?.queryKey))
51
+ act(() => root.unmount())
52
+ client.clear()
53
+ return { posts, failure, invalidated }
54
+ }
55
+
56
+ it.each(['pause', 'resume'] as const)('%s posts to its route and refreshes the open Deployment', async (action) => {
57
+ const { posts, failure, invalidated } = await run(action, { deploymentPause: true })
58
+
59
+ expect(failure).toBeUndefined()
60
+ expect(posts).toHaveLength(1)
61
+ expect(posts[0]).toContain(`/api/workloads/deployments/prod/web/${action}`)
62
+ expect(invalidated).toContain(JSON.stringify(['resource', 'deployments', 'prod', 'web']))
63
+ expect(invalidated).toContain(JSON.stringify(['resources', 'deployments']))
64
+ })
65
+
66
+ it('surfaces the server error', async () => {
67
+ const { failure } = await run('pause', { deploymentPause: true }, new Response('{"error":"nope"}', { status: 403 }))
68
+
69
+ expect((failure as Error).message).toBe('nope')
70
+ })
71
+
72
+ it('sends nothing to a Radar that predates the routes', async () => {
73
+ const { posts, failure } = await run('pause', { workloadImages: true })
74
+
75
+ expect(posts).toHaveLength(0)
76
+ expect(isRadarFeatureUnsupported(failure, 'deploymentPause')).toBe(true)
77
+ })
@@ -0,0 +1,14 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { restartErrorMessage } from './client'
3
+
4
+ describe('restartErrorMessage', () => {
5
+ it('points a paused refusal at the Resume rollout button instead of the server text', () => {
6
+ const msg = restartErrorMessage({ error: 'Deployment ns/web: the Deployment is paused, so a restart would not roll out; resume it, then restart', error_code: 'workload_paused' }, 409)
7
+ expect(msg).toContain('Resume rollout')
8
+ expect(msg).not.toContain('ns/web')
9
+ })
10
+ it('keeps the server text for every other failure', () => {
11
+ expect(restartErrorMessage({ error: 'deployments.apps "web" not found' }, 404)).toBe('deployments.apps "web" not found')
12
+ expect(restartErrorMessage({}, 500)).toBe('HTTP 500')
13
+ })
14
+ })
@@ -0,0 +1,44 @@
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 { expect, it, vi } from 'vitest'
6
+ import { useRefreshRevisionsOnNewRollout } from './client'
7
+
8
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
9
+
10
+ async function observe(revisions: (string | undefined)[]) {
11
+ const client = new QueryClient()
12
+ const invalidate = vi.spyOn(client, 'invalidateQueries')
13
+ function Probe({ revision }: { revision?: string }) {
14
+ useRefreshRevisionsOnNewRollout('deployments', 'prod', 'web', revision)
15
+ return null
16
+ }
17
+ const root = createRoot(document.createElement('div'))
18
+ for (const revision of revisions) {
19
+ await act(async () => {
20
+ root.render(<QueryClientProvider client={client}><Probe revision={revision} /></QueryClientProvider>)
21
+ })
22
+ }
23
+ act(() => root.unmount())
24
+ client.clear()
25
+ return invalidate
26
+ }
27
+
28
+ it('refreshes the revision list when the Deployment records a new revision', async () => {
29
+ const invalidate = await observe(['1', '2'])
30
+
31
+ expect(invalidate).toHaveBeenCalledExactlyOnceWith({ queryKey: ['workload-revisions', 'deployments', 'prod', 'web'] })
32
+ })
33
+
34
+ it('refreshes when a Deployment created paused records its first revision', async () => {
35
+ expect(await observe(['', '2'])).toHaveBeenCalledTimes(1)
36
+ })
37
+
38
+ it('leaves the list alone while the revision stays the same', async () => {
39
+ expect(await observe(['1', '1', '1'])).not.toHaveBeenCalled()
40
+ })
41
+
42
+ it('leaves the list alone when the resource first loads', async () => {
43
+ expect(await observe([undefined, '2'])).not.toHaveBeenCalled()
44
+ })
@@ -0,0 +1,14 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { rollbackErrorMessage } from './client'
3
+
4
+ describe('rollbackErrorMessage', () => {
5
+ it('points a paused refusal at the Resume rollout button instead of the server text', () => {
6
+ const msg = rollbackErrorMessage({ error: 'Deployment ns/web: the Deployment is paused, so a rollback would not roll out; resume it, then roll back', error_code: 'workload_paused' }, 409)
7
+ expect(msg).toContain('Resume rollout')
8
+ expect(msg).not.toContain('ns/web')
9
+ })
10
+ it('keeps the server text for every other failure', () => {
11
+ expect(rollbackErrorMessage({ error: 'revision 9 not found' }, 404)).toBe('revision 9 not found')
12
+ expect(rollbackErrorMessage({}, 500)).toBe('HTTP 500')
13
+ })
14
+ })