@skyhook-io/radar-app 1.20.0 → 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 (109) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +18 -11
  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 +287 -21
  9. package/src/api/helmInventory.test.tsx +108 -0
  10. package/src/api/networkAttachments.test.tsx +120 -0
  11. package/src/api/networkAttachments.ts +30 -0
  12. package/src/api/radarFeatures.test.ts +5 -0
  13. package/src/api/radarFeatures.ts +5 -0
  14. package/src/api/secretsStore.test.ts +33 -0
  15. package/src/api/secretsStore.ts +37 -0
  16. package/src/components/ConnectionErrorView.test.tsx +11 -0
  17. package/src/components/ConnectionErrorView.tsx +19 -0
  18. package/src/components/ContextSwitcher.tsx +9 -2
  19. package/src/components/applications/ApplicationsView.openResource.test.tsx +118 -0
  20. package/src/components/applications/ApplicationsView.tsx +8 -11
  21. package/src/components/cost/CostView.tsx +27 -9
  22. package/src/components/curl/ServiceCurlAvailability.test.tsx +32 -0
  23. package/src/components/curl/ServiceCurlButton.tsx +2 -2
  24. package/src/components/diagnose/InvestigationView.tsx +12 -3
  25. package/src/components/diagnose/investigationCase.test.tsx +41 -0
  26. package/src/components/diagnose/investigationEvidence/adapters/coverage.test.tsx +72 -0
  27. package/src/components/diagnose/investigationEvidence/adapters/helm.test.tsx +52 -0
  28. package/src/components/diagnose/investigationEvidence/adapters/helm.ts +61 -16
  29. package/src/components/diagnose/investigationEvidence/adapters/listings.ts +34 -4
  30. package/src/components/diagnose/investigationEvidence/adapters/resource.ts +3 -2
  31. package/src/components/diagnose/investigationEvidence/bodies/platform.tsx +82 -51
  32. package/src/components/diagnose/investigationEvidence/types.ts +5 -0
  33. package/src/components/dock/TerminalPreferences.query.test.tsx +57 -0
  34. package/src/components/dock/TerminalPreferences.test.tsx +68 -0
  35. package/src/components/dock/TerminalPreferences.tsx +73 -0
  36. package/src/components/gitops/GitOpsView.tsx +1 -9
  37. package/src/components/helm/HelmDrawerFrame.tsx +101 -0
  38. package/src/components/helm/HelmDrawerRouting.test.tsx +86 -0
  39. package/src/components/helm/HelmReleaseDrawer.tsx +47 -98
  40. package/src/components/helm/HelmView.tsx +215 -71
  41. package/src/components/helm/NotCheckedBadge.test.tsx +62 -0
  42. package/src/components/helm/NotCheckedBadge.tsx +39 -0
  43. package/src/components/helm/ObservedHelmNotice.tsx +146 -0
  44. package/src/components/helm/ObservedHelmRelease.test.tsx +261 -0
  45. package/src/components/helm/ObservedHelmReleaseDrawer.test.tsx +80 -0
  46. package/src/components/helm/ObservedHelmReleaseDrawer.tsx +228 -0
  47. package/src/components/helm/OwnedResources.test.tsx +86 -0
  48. package/src/components/helm/OwnedResources.tsx +69 -10
  49. package/src/components/home/ClusterHealthCard.heading.test.tsx +72 -0
  50. package/src/components/home/ClusterHealthCard.restricted.test.tsx +76 -0
  51. package/src/components/home/ClusterHealthCard.test.ts +44 -1
  52. package/src/components/home/ClusterHealthCard.tsx +49 -14
  53. package/src/components/home/HelmSummary.tsx +38 -19
  54. package/src/components/home/HelmSummary.unread.test.ts +16 -0
  55. package/src/components/home/HomeAgentBlock.tsx +7 -0
  56. package/src/components/home/MCPSetupDialog.test.tsx +38 -12
  57. package/src/components/home/MCPSetupDialog.tsx +5 -2
  58. package/src/components/home/mcpToolCatalog.ts +45 -5
  59. package/src/components/issues/uncheckedSources.test.ts +2 -0
  60. package/src/components/issues/uncheckedSources.ts +3 -0
  61. package/src/components/resource/RightsizingStrip.test.ts +57 -0
  62. package/src/components/resource/RightsizingStrip.tsx +53 -4
  63. package/src/components/resources/ImageFilesystemModal.test.tsx +74 -6
  64. package/src/components/resources/ImageFilesystemModal.tsx +98 -6
  65. package/src/components/resources/PodFileUploadPanel.tsx +150 -0
  66. package/src/components/resources/PodFilesystemModal.tsx +246 -3
  67. package/src/components/resources/pod-file-upload.test.tsx +223 -0
  68. package/src/components/resources/pod-file-upload.ts +266 -0
  69. package/src/components/resources/renderers/HTTPRouteRenderer.test.tsx +50 -0
  70. package/src/components/resources/renderers/HTTPRouteRenderer.tsx +27 -0
  71. package/src/components/resources/renderers/PodRenderer.tsx +26 -1
  72. package/src/components/resources/renderers/SecretProviderClassRenderer.tsx +25 -0
  73. package/src/components/resources/renderers/ServiceRenderer.test.tsx +15 -2
  74. package/src/components/resources/renderers/ServiceRenderer.tsx +1 -1
  75. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.test.tsx +160 -0
  76. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.tsx +128 -0
  77. package/src/components/rightsizing/RightsizingScanView.tsx +16 -1
  78. package/src/components/rightsizing/model.test.ts +11 -0
  79. package/src/components/rightsizing/model.ts +3 -1
  80. package/src/components/rightsizing/presentation.test.ts +46 -0
  81. package/src/components/rightsizing/presentation.ts +17 -2
  82. package/src/components/traffic/TrafficView.tsx +27 -27
  83. package/src/components/traffic/trafficFilters.test.ts +18 -1
  84. package/src/components/traffic/trafficFilters.ts +30 -1
  85. package/src/components/ui/Omnibar.tsx +4 -1
  86. package/src/components/ui/RadarOmnibar.test.tsx +55 -2
  87. package/src/components/ui/RadarOmnibar.tsx +7 -1
  88. package/src/components/ui/SearchSyntaxHelp.test.tsx +9 -2
  89. package/src/components/ui/SearchSyntaxHelp.tsx +3 -2
  90. package/src/components/ui/UpdateNotification.test.tsx +23 -1
  91. package/src/components/ui/UpdateNotification.tsx +26 -2
  92. package/src/components/ui/omnibar-match.test.ts +7 -0
  93. package/src/components/ui/omnibar-match.ts +1 -0
  94. package/src/components/ui/searchCoverageNote.test.ts +17 -0
  95. package/src/components/ui/searchCoverageNote.ts +31 -7
  96. package/src/components/useContextSwitchFlow.tsx +9 -1
  97. package/src/components/whats-new/releaseNotes.ts +1 -1
  98. package/src/components/workload/NodeCertificateEvidence.test.tsx +51 -0
  99. package/src/components/workload/NodeCertificateEvidence.tsx +44 -0
  100. package/src/components/workload/WorkloadView.tsx +51 -11
  101. package/src/context/ConnectionContext.test.ts +1 -0
  102. package/src/context/ConnectionContext.tsx +2 -2
  103. package/src/contexts/CapabilitiesContext.tsx +2 -0
  104. package/src/hooks/useResolvedGitOpsOwner.test.ts +22 -0
  105. package/src/hooks/useResolvedGitOpsOwner.ts +6 -3
  106. package/src/integrations/resourceHosts.test.tsx +2 -2
  107. package/src/integrations/resourceHosts.tsx +9 -0
  108. package/src/utils/namespacePick.test.ts +87 -0
  109. 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.0",
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'
@@ -821,7 +822,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
821
822
  navigate({ pathname: `/resources/${pluralKind}`, search: newParams.toString() })
822
823
  }, [searchParams, navigate])
823
824
 
824
- const navigateToHelmRelease = useCallback((namespace: string, name: string, storageNamespace?: string, investigationRunID?: string | null) => {
825
+ const navigateToHelmRelease = useCallback((namespace: string, name: string, storageNamespace?: string, investigationRunID?: string | null, observed?: boolean) => {
825
826
  const newParams = new URLSearchParams()
826
827
  const globalNamespaces = searchParams.get('namespaces')
827
828
  if (globalNamespaces) {
@@ -832,7 +833,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
832
833
  newParams.set('releaseStorage', storageNamespace)
833
834
  }
834
835
  if (investigationRunID) newParams.set('ai-run', investigationRunID)
835
- setSelectedHelmRelease({ namespace, name, storageNamespace })
836
+ setSelectedHelmRelease({ namespace, name, storageNamespace, observed })
836
837
  if (mainView === 'helm') {
837
838
  setSearchParams(newParams, { replace: true })
838
839
  return
@@ -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`.
@@ -1642,7 +1645,9 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1642
1645
  if (slashIdx > 0) {
1643
1646
  const ns = releaseParam.slice(0, slashIdx)
1644
1647
  const name = releaseParam.slice(slashIdx + 1)
1645
- setSelectedHelmRelease({ namespace: ns, name, storageNamespace: searchParams.get('releaseStorage') || undefined })
1648
+ const storageNamespace = searchParams.get('releaseStorage') || undefined
1649
+ // Keep what a row click knows about the release; the URL doesn't carry it.
1650
+ setSelectedHelmRelease(prev => (prev?.namespace === ns && prev.name === name && prev.storageNamespace === storageNamespace ? prev : { namespace: ns, name, storageNamespace }))
1646
1651
  }
1647
1652
  }
1648
1653
  // eslint-disable-next-line react-hooks/exhaustive-deps -- run only when searchParams change; namespacesKey/namespaceScope are read for that transition
@@ -2349,7 +2354,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2349
2354
  <HelmView
2350
2355
  namespaces={namespaces}
2351
2356
  selectedRelease={selectedHelmRelease}
2352
- onReleaseClick={navigateToHelmRelease}
2357
+ onReleaseClick={(namespace, name, storageNamespace, observed) => navigateToHelmRelease(namespace, name, storageNamespace, undefined, observed)}
2353
2358
  />
2354
2359
  )}
2355
2360
 
@@ -2659,6 +2664,7 @@ function DockSpacer() {
2659
2664
  // Main App component wrapped with providers
2660
2665
  function App({ manageDocumentTitle = false, documentTitleSuffix, onClusterLoadStateChange }: AppProps) {
2661
2666
  return (
2667
+ <TerminalPreferences>
2662
2668
  <ConnectionProvider>
2663
2669
  <CapabilitiesProvider>
2664
2670
  <RadarUpgradeProvider>
@@ -2676,6 +2682,7 @@ function App({ manageDocumentTitle = false, documentTitleSuffix, onClusterLoadSt
2676
2682
  </RadarUpgradeProvider>
2677
2683
  </CapabilitiesProvider>
2678
2684
  </ConnectionProvider>
2685
+ </TerminalPreferences>
2679
2686
  )
2680
2687
  }
2681
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
+ })