@skyhook-io/radar-app 1.22.2 → 1.23.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 (228) hide show
  1. package/package.json +8 -8
  2. package/src/App.tsx +49 -13
  3. package/src/RadarApp.basename.test.tsx +177 -0
  4. package/src/RadarApp.settings.test.tsx +33 -0
  5. package/src/api/agentSandbox.ts +259 -0
  6. package/src/api/client.autoPromConnect.test.tsx +43 -0
  7. package/src/api/client.metricsRelayCheck.test.tsx +134 -0
  8. package/src/api/client.ts +151 -27
  9. package/src/api/client.updateResource.secretExpiry.test.tsx +47 -0
  10. package/src/api/cloudInstallDiscover.test.tsx +76 -0
  11. package/src/api/diagnose.ts +4 -0
  12. package/src/api/kagent.test.ts +82 -0
  13. package/src/api/kagent.ts +230 -0
  14. package/src/api/poll.ts +78 -0
  15. package/src/api/prometheusCharts.ts +5 -0
  16. package/src/api/radarFeatures.test.ts +9 -0
  17. package/src/api/radarFeatures.ts +16 -0
  18. package/src/api/substrateWorkspace.test.ts +72 -0
  19. package/src/api/substrateWorkspace.ts +1394 -0
  20. package/src/api/vulnerabilities.ts +207 -9
  21. package/src/api/workloadSource.test.tsx +315 -0
  22. package/src/api/workloadSource.ts +128 -12
  23. package/src/components/CloudConnectFlow.tsx +46 -7
  24. package/src/components/CloudFunnelButton.test.tsx +193 -7
  25. package/src/components/CloudFunnelButton.tsx +128 -32
  26. package/src/components/SelfManagedStart.tsx +12 -2
  27. package/src/components/agentsandbox/AgentSandboxKindLists.tsx +41 -0
  28. package/src/components/agentsandbox/AgentSandboxLists.test.tsx +410 -0
  29. package/src/components/agentsandbox/AgentSandboxOverview.test.tsx +333 -0
  30. package/src/components/agentsandbox/AgentSandboxOverview.tsx +555 -0
  31. package/src/components/agentsandbox/AgentSandboxSidebar.test.tsx +97 -0
  32. package/src/components/agentsandbox/AgentSandboxSummary.test.tsx +439 -0
  33. package/src/components/agentsandbox/AgentSandboxSummary.tsx +956 -0
  34. package/src/components/agentsandbox/AgentSandboxTables.tsx +966 -0
  35. package/src/components/agentsandbox/AgentSandboxView.tsx +34 -0
  36. package/src/components/agentsandbox/agentsandbox.fixtures.ts +135 -0
  37. package/src/components/agentsandbox/data.ts +135 -0
  38. package/src/components/agentsandbox/host.test.ts +27 -0
  39. package/src/components/agentsandbox/host.tsx +85 -0
  40. package/src/components/agentsandbox/labels.test.ts +42 -0
  41. package/src/components/agentsandbox/labels.ts +146 -0
  42. package/src/components/agentsandbox/listFilters.ts +85 -0
  43. package/src/components/agentsandbox/lists.ts +52 -0
  44. package/src/components/agentsandbox/routes.ts +23 -0
  45. package/src/components/agentsandbox/shared.tsx +321 -0
  46. package/src/components/agentsandbox/useAgentSandboxSidebarWorkspace.ts +69 -0
  47. package/src/components/agentsandbox/workspace.fixtures.ts +125 -0
  48. package/src/components/agentsandbox/workspace.tsx +258 -0
  49. package/src/components/agentsandbox/workspaceRoute.ts +18 -0
  50. package/src/components/applications/ApplicationsView.openResource.test.tsx +248 -3
  51. package/src/components/applications/ApplicationsView.tsx +156 -3
  52. package/src/components/audit/VulnerabilitiesColumns.test.tsx +487 -0
  53. package/src/components/audit/VulnerabilitiesRisk.test.tsx +318 -0
  54. package/src/components/audit/VulnerabilitiesView.test.tsx +458 -13
  55. package/src/components/audit/VulnerabilitiesView.tsx +639 -199
  56. package/src/components/cloudHints/AgentSetupCloudRow.tsx +28 -0
  57. package/src/components/cloudHints/CloudHintLink.tsx +29 -0
  58. package/src/components/cloudHints/SharedInstallAiLine.tsx +36 -0
  59. package/src/components/cloudHints/cloudHints.test.ts +126 -0
  60. package/src/components/cloudHints/cloudHints.ts +131 -0
  61. package/src/components/cloudHints/cloudHintsGate.test.tsx +70 -0
  62. package/src/components/cloudHints/cloudLinks.test.ts +52 -0
  63. package/src/components/cloudHints/cloudLinks.ts +31 -0
  64. package/src/components/cloudHints/hintStorage.ts +28 -0
  65. package/src/components/cnpg/CNPGView.tsx +4 -7
  66. package/src/components/diagnose/AgentSetupNotice.tsx +5 -0
  67. package/src/components/diagnose/DiagnoseContext.tsx +7 -0
  68. package/src/components/diagnose/DiagnoseSurface.escape.test.tsx +215 -0
  69. package/src/components/diagnose/DiagnoseSurface.tsx +57 -1
  70. package/src/components/gitops/RemoteDestinationCloudHint.tsx +6 -14
  71. package/src/components/helm/HelmDrawerRouting.test.tsx +34 -1
  72. package/src/components/helm/HelmReleaseDrawer.tsx +6 -4
  73. package/src/components/helm/HelmView.tsx +4 -3
  74. package/src/components/helm/ObservedHelmNotice.tsx +39 -17
  75. package/src/components/helm/ObservedHelmRelease.test.tsx +62 -3
  76. package/src/components/helm/ObservedHelmReleaseDrawer.test.tsx +18 -0
  77. package/src/components/helm/ObservedHelmReleaseDrawer.tsx +4 -2
  78. package/src/components/home/HomeAgentBlock.tsx +2 -0
  79. package/src/components/home/HomeView.tsx +3 -3
  80. package/src/components/home/MCPSetupDialog.test.tsx +9 -0
  81. package/src/components/home/MCPSetupDialog.tsx +6 -2
  82. package/src/components/home/McpCloudLine.test.tsx +162 -0
  83. package/src/components/home/McpCloudLine.tsx +95 -0
  84. package/src/components/home/ProblemsPanel.investigate.test.tsx +2 -2
  85. package/src/components/home/mcpToolCatalog.test.ts +10 -0
  86. package/src/components/home/mcpToolCatalog.ts +4 -4
  87. package/src/components/issues/ClusterSchedulingBlockerRow.tsx +35 -0
  88. package/src/components/issues/IssuesPane.render.test.tsx +36 -1
  89. package/src/components/issues/IssuesPane.tsx +181 -23
  90. package/src/components/issues/SinceLastVisitRow.render.test.tsx +302 -0
  91. package/src/components/issues/SinceLastVisitRow.tsx +71 -0
  92. package/src/components/issues/sinceLastVisit.test.ts +266 -0
  93. package/src/components/issues/sinceLastVisit.ts +439 -0
  94. package/src/components/issues/uncheckedSources.test.ts +8 -0
  95. package/src/components/issues/uncheckedSources.ts +3 -0
  96. package/src/components/kagent/KagentAgentRenderer.test.ts +32 -0
  97. package/src/components/kagent/KagentAgentRenderer.tsx +87 -0
  98. package/src/components/kagent/KagentAgentSessions.test.tsx +166 -0
  99. package/src/components/kagent/KagentAgentSessions.tsx +124 -0
  100. package/src/components/kagent/KagentDetailPage.tsx +106 -0
  101. package/src/components/kagent/KagentLists.tsx +412 -0
  102. package/src/components/kagent/KagentOverview.tsx +234 -0
  103. package/src/components/kagent/KagentPages.tsx +690 -0
  104. package/src/components/kagent/KagentRuntimeTabs.test.tsx +219 -0
  105. package/src/components/kagent/KagentRuntimeTabs.tsx +283 -0
  106. package/src/components/kagent/KagentSidebar.test.tsx +112 -0
  107. package/src/components/kagent/KagentView.tsx +109 -0
  108. package/src/components/kagent/KagentWorkspace.test.tsx +876 -0
  109. package/src/components/kagent/host.tsx +144 -0
  110. package/src/components/kagent/routes.ts +31 -0
  111. package/src/components/kagent/shared.tsx +336 -0
  112. package/src/components/kagent/useKagentRuntime.test.tsx +77 -0
  113. package/src/components/kagent/useKagentSidebarWorkspace.ts +67 -0
  114. package/src/components/kagent/workspace.fixtures.ts +108 -0
  115. package/src/components/kagent/workspaceRoute.ts +18 -0
  116. package/src/components/nudges/activeNudges.test.ts +39 -0
  117. package/src/components/nudges/activeNudges.ts +76 -0
  118. package/src/components/poll/OssPoll.tsx +871 -0
  119. package/src/components/poll/mount.test.ts +12 -0
  120. package/src/components/poll/pollCloud.test.ts +23 -0
  121. package/src/components/poll/pollCloud.ts +6 -0
  122. package/src/components/poll/pollDefinition.ts +93 -0
  123. package/src/components/poll/pollFlow.test.ts +140 -0
  124. package/src/components/poll/pollFlow.ts +137 -0
  125. package/src/components/poll/pollSender.test.ts +137 -0
  126. package/src/components/poll/pollSender.ts +76 -0
  127. package/src/components/poll/pollStorage.test.ts +53 -0
  128. package/src/components/poll/pollStorage.ts +77 -0
  129. package/src/components/poll/round.json +350 -0
  130. package/src/components/product-hunt/ProductHuntNotice.tsx +2 -0
  131. package/src/components/resource/MetricsNotConnected.test.tsx +28 -0
  132. package/src/components/resource/MetricsNotConnected.tsx +10 -7
  133. package/src/components/resource/PrometheusCharts.tsx +10 -1
  134. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +9 -0
  135. package/src/components/resource/PrometheusChartsGrid.tsx +3 -3
  136. package/src/components/resource/SubstrateHealthCharts.test.tsx +13 -1
  137. package/src/components/resource/SubstrateHealthCharts.tsx +9 -15
  138. package/src/components/resources/ImageFilesystemModal.test.tsx +21 -1
  139. package/src/components/resources/ImageFilesystemModal.tsx +42 -3
  140. package/src/components/resources/ResourceDetailDrawer.tsx +1 -0
  141. package/src/components/resources/ResourcesView.tsx +24 -11
  142. package/src/components/resources/renderers/PodRenderer.tsx +8 -2
  143. package/src/components/settings/LocalIntegrationStatus.test.tsx +1 -0
  144. package/src/components/settings/LocalIntegrationStatus.tsx +3 -2
  145. package/src/components/settings/SettingsDialog.tsx +84 -16
  146. package/src/components/settings/SubstrateSettings.lifecycle.test.tsx +210 -0
  147. package/src/components/settings/SubstrateSettings.test.tsx +131 -0
  148. package/src/components/settings/SubstrateSettings.tsx +544 -0
  149. package/src/components/settings/settings-state.test.ts +21 -3
  150. package/src/components/settings/settings-state.ts +13 -3
  151. package/src/components/share/ShareLinkButton.test.tsx +360 -0
  152. package/src/components/share/ShareLinkButton.tsx +391 -0
  153. package/src/components/share/openShareInCloud.test.ts +29 -0
  154. package/src/components/share/openShareInCloud.ts +10 -0
  155. package/src/components/share/shareLink.test.ts +129 -0
  156. package/src/components/share/shareLink.ts +175 -0
  157. package/src/components/substrate/SubstrateActorDrawer.tsx +87 -0
  158. package/src/components/substrate/SubstrateActorOverview.tsx +489 -0
  159. package/src/components/substrate/SubstrateActorPage.tsx +384 -0
  160. package/src/components/substrate/SubstrateActors.test.tsx +1094 -0
  161. package/src/components/substrate/SubstrateActors.tsx +612 -0
  162. package/src/components/substrate/SubstrateAttentionList.tsx +441 -0
  163. package/src/components/substrate/SubstrateConnect.tsx +88 -0
  164. package/src/components/substrate/SubstrateOverview.test.tsx +396 -0
  165. package/src/components/substrate/SubstrateOverview.tsx +575 -0
  166. package/src/components/substrate/SubstratePages.test.tsx +478 -0
  167. package/src/components/substrate/SubstratePool.test.tsx +462 -0
  168. package/src/components/substrate/SubstratePoolPage.tsx +95 -0
  169. package/src/components/substrate/SubstratePoolSummary.tsx +485 -0
  170. package/src/components/substrate/SubstrateSidebar.test.tsx +101 -0
  171. package/src/components/substrate/SubstrateStateBar.tsx +63 -0
  172. package/src/components/substrate/SubstrateTemplates.tsx +376 -0
  173. package/src/components/substrate/SubstrateView.tsx +173 -0
  174. package/src/components/substrate/SubstrateWorkerPodContext.tsx +73 -0
  175. package/src/components/substrate/SubstrateWorkers.tsx +389 -0
  176. package/src/components/substrate/attention.ts +81 -0
  177. package/src/components/substrate/contextPin.tsx +69 -0
  178. package/src/components/substrate/host.tsx +83 -0
  179. package/src/components/substrate/kubectlTarget.test.tsx +77 -0
  180. package/src/components/substrate/readings.test.ts +484 -0
  181. package/src/components/substrate/readings.ts +997 -0
  182. package/src/components/substrate/routes.ts +103 -0
  183. package/src/components/substrate/shared.tsx +426 -0
  184. package/src/components/substrate/substrate.fixtures.ts +325 -0
  185. package/src/components/substrate/useSubstrateSidebarWorkspace.ts +87 -0
  186. package/src/components/substrate/workspaceRoute.ts +23 -0
  187. package/src/components/traffic/TrafficConnectionsTable.test.tsx +9 -0
  188. package/src/components/traffic/TrafficConnectionsTable.tsx +4 -2
  189. package/src/components/traffic/TrafficFilterSidebar.tsx +19 -14
  190. package/src/components/traffic/TrafficFlowList.test.tsx +63 -0
  191. package/src/components/traffic/TrafficFlowList.tsx +9 -5
  192. package/src/components/traffic/TrafficGraph.test.tsx +26 -0
  193. package/src/components/traffic/TrafficGraph.tsx +17 -14
  194. package/src/components/traffic/TrafficGraphTooLarge.tsx +2 -0
  195. package/src/components/traffic/TrafficGraphUnavailable.tsx +3 -1
  196. package/src/components/traffic/TrafficView.tsx +26 -56
  197. package/src/components/traffic/trafficFilters.test.ts +61 -1
  198. package/src/components/traffic/trafficFilters.ts +68 -8
  199. package/src/components/ui/UpdateNotification.tsx +2 -0
  200. package/src/components/usage-data/UsageDataPrompt.tsx +2 -0
  201. package/src/components/velero/VeleroOverview.tsx +2 -2
  202. package/src/components/velero/VeleroView.tsx +3 -6
  203. package/src/components/vulnerabilities/columns.tsx +132 -0
  204. package/src/components/vulnerabilities/filters.tsx +317 -0
  205. package/src/components/vulnerabilities/owner.test.ts +54 -0
  206. package/src/components/vulnerabilities/owner.tsx +163 -0
  207. package/src/components/vulnerabilities/parts.test.ts +126 -12
  208. package/src/components/vulnerabilities/parts.tsx +612 -52
  209. package/src/components/vulnerabilities/traffic.test.tsx +65 -0
  210. package/src/components/vulnerabilities/traffic.tsx +40 -0
  211. package/src/components/whats-new/WhatsNew.tsx +2 -0
  212. package/src/components/whats-new/releaseNotes.ts +75 -1
  213. package/src/components/workload/WorkloadView.substrateVersion.test.tsx +88 -0
  214. package/src/components/workload/WorkloadView.tsx +52 -13
  215. package/src/components/workspace/layout.tsx +13 -7
  216. package/src/components/workspace/sidebar.test.ts +48 -0
  217. package/src/components/workspace/sidebar.ts +73 -3
  218. package/src/components/workspace/table.ts +2 -1
  219. package/src/contexts/RegistryAccessMode.test.tsx +51 -0
  220. package/src/contexts/RegistryAccessMode.tsx +25 -0
  221. package/src/integrations/resourceHost.ts +12 -6
  222. package/src/integrations/resourceHosts.test.tsx +27 -1
  223. package/src/integrations/resourceHosts.tsx +15 -7
  224. package/src/integrations/sidebarWorkspaces.test.tsx +63 -0
  225. package/src/integrations/sidebarWorkspaces.ts +41 -0
  226. package/src/integrations/workspaceRoute.ts +1 -1
  227. package/src/integrations/workspaceRoutes.ts +7 -1
  228. package/src/integrations/workspaceScreens.tsx +6 -0
@@ -0,0 +1,439 @@
1
+ import { useEffect, useMemo, useState, useSyncExternalStore } from "react";
2
+ import type { Issue } from "@skyhook-io/k8s-ui";
3
+ import { getApiBase } from "../../api/config";
4
+ import { useAuthMe, useClusterInfo, useRadarVersion } from "../../api/client";
5
+
6
+ // "Started since you last checked": which issues on the list began after the
7
+ // last time this person looked at the Issues list on this cluster, in this
8
+ // browser.
9
+ //
10
+ // first_seen reads "active at least since": some anchors, such as an Event's
11
+ // first timestamp, restart while a problem goes on. So an issue is called new
12
+ // only when all of these hold:
13
+ // - its namespace (or, cluster-scoped, every namespace) was shown in a
14
+ // complete list during the last visit: not capped, no unchecked source,
15
+ // and read with the same visibility as now, so widened permissions can't
16
+ // make an issue that was there all along look new,
17
+ // - it wasn't on the lists of that visit,
18
+ // - its onset is known for every signal it groups, and is after the latest
19
+ // of those looks that covered it.
20
+ //
21
+ // A visit is a stretch of time with the Issues list on screen. It ends once the
22
+ // list has been away (another page, a hidden tab, Radar closed) for
23
+ // VISIT_GAP_MS; its lists then become the ones the next visit compares
24
+ // against. The record lives in this browser, per Radar address,
25
+ // kubeconfig context, signed-in user and Radar version: people sharing an
26
+ // in-cluster Radar never share it, and an upgrade starts over, since new
27
+ // detectors can list problems that were already there. Where storage is blocked
28
+ // it lives in memory, so a reload starts again and nothing is called new.
29
+
30
+ export const VISIT_GAP_MS = 30 * 60_000;
31
+ export const HEARTBEAT_MS = 60_000;
32
+ // The anchor is the browser's clock and first_seen the cluster's. An issue
33
+ // that started this close to the anchor isn't called new, so a skewed clock
34
+ // can't mark an issue the person was already looking at.
35
+ export const ONSET_MARGIN_MS = 5 * 60_000;
36
+ // Hashed ids listed during one visit. Past this, further ids aren't kept and
37
+ // the lists stop counting as complete.
38
+ export const MAX_LISTED_IDS = 2000;
39
+
40
+ /** When complete lists last showed every namespace, and each single namespace, read with visibility `vis`. */
41
+ export interface ListCover {
42
+ vis?: string;
43
+ allAt?: number;
44
+ nsAt?: Record<string, number>;
45
+ }
46
+
47
+ /** What the person's permissions let the list show, as one comparable value. */
48
+ export function visibilityKey(visibility: { state?: string; impact?: string } | undefined): string {
49
+ return visibility ? JSON.stringify([visibility.state ?? "", visibility.impact ?? ""]) : "";
50
+ }
51
+
52
+ export interface VisitRecord {
53
+ /** Last time Radar was seen visible on this cluster, ms since epoch. */
54
+ lastActiveAt: number;
55
+ /** When the person last saw the list, in the last visit that showed it. */
56
+ anchor?: number;
57
+ /** Hashed ids of the issues that visit listed, and what its lists covered. */
58
+ prev?: string[];
59
+ prevCover?: ListCover;
60
+ /** The same for this visit, so far. */
61
+ cur?: string[];
62
+ curCover?: ListCover;
63
+ curListedAt?: number;
64
+ /** The anchor whose row the person closed. */
65
+ closedAnchor?: number;
66
+ }
67
+
68
+ /** Moves the record to `now`: the same visit, or a new one after a gap. */
69
+ export function advanceVisit(record: VisitRecord | undefined, now: number): VisitRecord {
70
+ if (!record) return { lastActiveAt: now };
71
+ if (now - record.lastActiveAt <= VISIT_GAP_MS) {
72
+ return { ...record, lastActiveAt: Math.max(record.lastActiveAt, now) };
73
+ }
74
+ if (record.curListedAt === undefined) {
75
+ // No list loaded during that visit: compare against the last one that did.
76
+ const { anchor, prev, prevCover, closedAnchor } = record;
77
+ return { lastActiveAt: now, anchor, prev, prevCover, closedAnchor };
78
+ }
79
+ return { lastActiveAt: now, anchor: record.curListedAt, prev: record.cur ?? [], prevCover: record.curCover };
80
+ }
81
+
82
+ /**
83
+ * Records one list the person was shown: its issue ids, and, when it was
84
+ * complete, the namespaces it covered (`namespaces` empty means all of them).
85
+ * `at` is when the list was fetched, which is the cluster state it shows: a
86
+ * cached list shown again, or kept through failed refreshes, is no newer look.
87
+ */
88
+ export function noteListed(
89
+ record: VisitRecord,
90
+ ids: readonly string[],
91
+ at: number,
92
+ list: { namespaces: readonly string[]; complete: boolean; visibility: string },
93
+ ): VisitRecord {
94
+ const cur = record.cur ?? [];
95
+ const seen = new Set(cur);
96
+ const added: string[] = [];
97
+ let overflow = false;
98
+ for (const id of ids) {
99
+ const h = hashId(id);
100
+ if (seen.has(h)) continue;
101
+ if (seen.size >= MAX_LISTED_IDS) {
102
+ overflow = true;
103
+ break;
104
+ }
105
+ seen.add(h);
106
+ added.push(h);
107
+ }
108
+ // Coverage read with other permissions isn't comparable: start it again.
109
+ let curCover = record.curCover && (record.curCover.vis ?? "") === list.visibility ? record.curCover : undefined;
110
+ const later = (t: number | undefined) => Math.max(t ?? 0, at);
111
+ if (list.complete && !overflow) {
112
+ curCover = { ...curCover, vis: list.visibility };
113
+ if (list.namespaces.length === 0) curCover = { ...curCover, allAt: later(curCover.allAt) };
114
+ else curCover = { ...curCover, nsAt: { ...curCover.nsAt, ...Object.fromEntries(list.namespaces.map((ns) => [ns, later(curCover?.nsAt?.[ns])])) } };
115
+ }
116
+ return { ...record, cur: added.length ? [...cur, ...added] : cur, curCover, curListedAt: later(record.curListedAt) };
117
+ }
118
+
119
+ export interface LastLook {
120
+ listed: ReadonlySet<string>;
121
+ cover: ListCover | undefined;
122
+ /** visibilityKey of the list shown now. */
123
+ visibility: string;
124
+ }
125
+
126
+ /** The last time a complete list, read with the same visibility, could have shown this issue, if any. */
127
+ export function lastLookAt(
128
+ issue: Pick<Issue, "namespace">,
129
+ cover: ListCover | undefined,
130
+ visibility: string,
131
+ ): number | undefined {
132
+ if ((cover?.vis ?? "") !== visibility) return undefined;
133
+ const times = [cover?.allAt, issue.namespace ? cover?.nsAt?.[issue.namespace] : undefined].filter(
134
+ (t): t is number => typeof t === "number",
135
+ );
136
+ return times.length ? Math.max(...times) : undefined;
137
+ }
138
+
139
+ /** Whether an issue started after the last look that could have shown it, as far as Radar can tell. */
140
+ export function startedSince(
141
+ issue: Pick<Issue, "id" | "namespace" | "first_seen" | "onset_unknown" | "onset_coverage">,
142
+ last: LastLook,
143
+ ): boolean {
144
+ const lookedAt = lastLookAt(issue, last.cover, last.visibility);
145
+ if (lookedAt === undefined) return false;
146
+ if (last.listed.has(hashId(issue.id))) return false;
147
+ if (!issue.first_seen || issue.onset_unknown) return false;
148
+ if ((issue.onset_coverage?.unknown ?? 0) > 0) return false;
149
+ const onset = Date.parse(issue.first_seen);
150
+ return Number.isFinite(onset) && onset > lookedAt + ONSET_MARGIN_MS;
151
+ }
152
+
153
+ // FNV-1a, 32-bit. A collision only hides an issue from the count.
154
+ export function hashId(id: string): string {
155
+ let h = 0x811c9dc5;
156
+ for (let i = 0; i < id.length; i++) {
157
+ h ^= id.charCodeAt(i);
158
+ h = Math.imul(h, 0x01000193);
159
+ }
160
+ return (h >>> 0).toString(36);
161
+ }
162
+
163
+ /** "today 14:05", "Fri 18:40" within the week, "Nov 3, 18:40" before that (in the reader's locale). */
164
+ export function formatVisitTime(anchor: number, now: number, locale?: string): string {
165
+ const at = new Date(anchor);
166
+ const time = at.toLocaleTimeString(locale, { hour: "numeric", minute: "2-digit" });
167
+ const today = new Date(now);
168
+ if (at.toDateString() === today.toDateString()) return `today ${time}`;
169
+ if (now - anchor < 6 * 24 * 3600_000) {
170
+ return `${at.toLocaleDateString(locale, { weekday: "short" })} ${time}`;
171
+ }
172
+ return `${at.toLocaleDateString(locale, { month: "short", day: "numeric" })}, ${time}`;
173
+ }
174
+
175
+ // ---- Storage ----------------------------------------------------------------
176
+
177
+ const RECORD_PREFIX = "radar:since-last-visit:";
178
+ const OFF_PREFIX = "radar:since-last-visit:off:";
179
+ const CLOUD_PREFIX = "radar:since-last-visit:cloud:";
180
+ // Records for a cluster, person or Radar version not seen in this long are
181
+ // dropped: every upgrade and every context starts a record of its own.
182
+ export const RECORD_MAX_AGE_MS = 30 * 24 * 60 * 60_000;
183
+ // The Radar Cloud sentence is shown on this many visits, then not again.
184
+ export const CLOUD_SENTENCE_VISITS = 3;
185
+
186
+ function readStorage(): Storage | undefined {
187
+ try {
188
+ const s = window.localStorage;
189
+ s.getItem("");
190
+ return s;
191
+ } catch {
192
+ return undefined;
193
+ }
194
+ }
195
+
196
+ const listeners = new Set<() => void>();
197
+ const parsed = new Map<string, { raw: string | undefined; value: VisitRecord | undefined }>();
198
+
199
+ // Values whose write didn't reach storage: blocked storage, or a full one.
200
+ // They win for the life of the page; storage answers everything else, so
201
+ // another tab's writes show up here.
202
+ const memory = new Map<string, string>();
203
+
204
+ function getRaw(key: string): string | undefined {
205
+ const unsaved = memory.get(key);
206
+ if (unsaved !== undefined) return unsaved;
207
+ try {
208
+ return readStorage()?.getItem(key) ?? undefined;
209
+ } catch {
210
+ return undefined;
211
+ }
212
+ }
213
+
214
+ function setRaw(key: string, value: string) {
215
+ const s = readStorage();
216
+ try {
217
+ if (!s) throw new Error("no storage");
218
+ s.setItem(key, value);
219
+ memory.delete(key);
220
+ } catch {
221
+ memory.set(key, value);
222
+ // Don't leave an older value behind for the next page load to trust.
223
+ try {
224
+ s?.removeItem(key);
225
+ } catch { /* nothing more to do */ }
226
+ }
227
+ }
228
+
229
+ function emit() {
230
+ for (const l of listeners) l();
231
+ }
232
+
233
+ function parseRecord(raw: string | undefined): VisitRecord | undefined {
234
+ if (!raw) return undefined;
235
+ try {
236
+ const v: unknown = JSON.parse(raw);
237
+ if (!v || typeof v !== "object") return undefined;
238
+ const r = v as Record<string, unknown>;
239
+ if (typeof r.lastActiveAt !== "number") return undefined;
240
+ const ids = (x: unknown) => (Array.isArray(x) ? x.filter((s): s is string => typeof s === "string") : undefined);
241
+ const num = (x: unknown) => (typeof x === "number" ? x : undefined);
242
+ const cover = (x: unknown): ListCover | undefined => {
243
+ if (!x || typeof x !== "object") return undefined;
244
+ const c = x as Record<string, unknown>;
245
+ const nsAt =
246
+ c.nsAt && typeof c.nsAt === "object"
247
+ ? Object.fromEntries(Object.entries(c.nsAt).filter((e): e is [string, number] => typeof e[1] === "number"))
248
+ : undefined;
249
+ return { vis: typeof c.vis === "string" ? c.vis : undefined, allAt: num(c.allAt), nsAt };
250
+ };
251
+ return {
252
+ lastActiveAt: r.lastActiveAt,
253
+ anchor: num(r.anchor),
254
+ prev: ids(r.prev),
255
+ prevCover: cover(r.prevCover),
256
+ cur: ids(r.cur),
257
+ curCover: cover(r.curCover),
258
+ curListedAt: num(r.curListedAt),
259
+ closedAnchor: num(r.closedAnchor),
260
+ };
261
+ } catch {
262
+ return undefined;
263
+ }
264
+ }
265
+
266
+ export function readVisit(key: string): VisitRecord | undefined {
267
+ const raw = getRaw(RECORD_PREFIX + key);
268
+ const cached = parsed.get(key);
269
+ if (cached && cached.raw === raw) return cached.value;
270
+ const value = parseRecord(raw);
271
+ parsed.set(key, { raw, value });
272
+ return value;
273
+ }
274
+
275
+ export function updateVisit(key: string, change: (r: VisitRecord | undefined) => VisitRecord | undefined) {
276
+ const before = readVisit(key);
277
+ const after = change(before);
278
+ if (!after || after === before) return;
279
+ setRaw(RECORD_PREFIX + key, JSON.stringify(after));
280
+ emit();
281
+ }
282
+
283
+ /** Drops visit records last active more than RECORD_MAX_AGE_MS before now. */
284
+ export function pruneVisitRecords(now: number) {
285
+ const s = readStorage();
286
+ if (!s) return;
287
+ const stale: string[] = [];
288
+ try {
289
+ for (let i = 0; i < s.length; i++) {
290
+ const key = s.key(i);
291
+ if (!key?.startsWith(RECORD_PREFIX) || key.startsWith(OFF_PREFIX) || key.startsWith(CLOUD_PREFIX)) continue;
292
+ const record = parseRecord(s.getItem(key) ?? undefined);
293
+ if (!record || now - record.lastActiveAt > RECORD_MAX_AGE_MS) stale.push(key);
294
+ }
295
+ for (const key of stale) s.removeItem(key);
296
+ } catch { /* nothing to prune */ }
297
+ for (const key of stale) parsed.delete(key.slice(RECORD_PREFIX.length));
298
+ }
299
+
300
+ function cloudVisits(user: string): number[] {
301
+ try {
302
+ const v: unknown = JSON.parse(getRaw(CLOUD_PREFIX + user) ?? "[]");
303
+ return Array.isArray(v) ? v.filter((x): x is number => typeof x === "number") : [];
304
+ } catch {
305
+ return [];
306
+ }
307
+ }
308
+
309
+ /** Whether the row's Radar Cloud sentence may show on the visit since `anchor`: one of the first few, or one it already showed on. */
310
+ export function cloudSentenceAllowed(user: string, anchor: number): boolean {
311
+ const seen = cloudVisits(user);
312
+ return seen.includes(anchor) || seen.length < CLOUD_SENTENCE_VISITS;
313
+ }
314
+
315
+ /** Counts the visit since `anchor` as one the Radar Cloud sentence showed on. */
316
+ export function noteCloudSentence(user: string, anchor: number) {
317
+ const seen = cloudVisits(user);
318
+ if (seen.includes(anchor) || seen.length >= CLOUD_SENTENCE_VISITS) return;
319
+ setRaw(CLOUD_PREFIX + user, JSON.stringify([...seen, anchor]));
320
+ }
321
+
322
+ // "Don't show again" belongs to the person, on every cluster.
323
+ export function sinceRowTurnedOff(user: string): boolean {
324
+ return getRaw(OFF_PREFIX + user) === "1";
325
+ }
326
+
327
+ export function turnSinceRowOff(user: string) {
328
+ setRaw(OFF_PREFIX + user, "1");
329
+ emit();
330
+ }
331
+
332
+ /** Test seam: forget the in-memory fallback and cached parses. */
333
+ export function resetVisitMemory() {
334
+ memory.clear();
335
+ parsed.clear();
336
+ pruned = false;
337
+ }
338
+
339
+ function subscribe(listener: () => void) {
340
+ listeners.add(listener);
341
+ const onStorage = (e: StorageEvent) => {
342
+ if (e.key?.startsWith(RECORD_PREFIX) || e.key?.startsWith(OFF_PREFIX)) listener();
343
+ };
344
+ window.addEventListener("storage", onStorage);
345
+ return () => {
346
+ listeners.delete(listener);
347
+ window.removeEventListener("storage", onStorage);
348
+ };
349
+ }
350
+
351
+ // ---- Hooks ------------------------------------------------------------------
352
+
353
+ interface VisitIdentity {
354
+ /** This browser's key for the cluster, person and Radar version; null until all are known. */
355
+ key: string | null;
356
+ user: string;
357
+ }
358
+
359
+ function useVisitIdentity(): VisitIdentity {
360
+ const context = useClusterInfo().data?.context;
361
+ const auth = useAuthMe();
362
+ const version = useRadarVersion();
363
+ const user = auth.data?.username ?? "";
364
+ // Without a version an upgrade can't be told apart, and without the identity
365
+ // (still loading, or /auth/me failed) users can't be told apart: either way
366
+ // nothing is compared.
367
+ const key = !context || !auth.data || !version ? null : JSON.stringify([getApiBase(), context, user, version]);
368
+ return { key, user };
369
+ }
370
+
371
+ /** Keeps the visit going while the Issues list is on screen. */
372
+ let pruned = false;
373
+
374
+ export function useTrackVisit(key: string | null) {
375
+ useEffect(() => {
376
+ if (!key) return;
377
+ if (!pruned) {
378
+ pruned = true;
379
+ pruneVisitRecords(Date.now());
380
+ }
381
+ const tick = () => {
382
+ if (document.visibilityState === "visible") updateVisit(key, (r) => advanceVisit(r, Date.now()));
383
+ };
384
+ const onVisibility = () => {
385
+ // Hiding counts as the last moment on screen; coming back may start a visit.
386
+ if (document.visibilityState === "hidden") updateVisit(key, (r) => advanceVisit(r, Date.now()));
387
+ else tick();
388
+ };
389
+ tick();
390
+ const id = window.setInterval(tick, HEARTBEAT_MS);
391
+ document.addEventListener("visibilitychange", onVisibility);
392
+ window.addEventListener("pagehide", onVisibility);
393
+ return () => {
394
+ window.clearInterval(id);
395
+ document.removeEventListener("visibilitychange", onVisibility);
396
+ window.removeEventListener("pagehide", onVisibility);
397
+ };
398
+ }, [key]);
399
+ }
400
+
401
+ export interface SinceLastVisit extends VisitIdentity {
402
+ record: VisitRecord | undefined;
403
+ turnedOff: boolean;
404
+ /** The time the record is read at; moves with the heartbeat. */
405
+ now: number;
406
+ }
407
+
408
+ function useNow(): number {
409
+ const [now, setNow] = useState(() => Date.now());
410
+ useEffect(() => {
411
+ const tick = () => setNow(Date.now());
412
+ const id = window.setInterval(tick, HEARTBEAT_MS);
413
+ document.addEventListener("visibilitychange", tick);
414
+ return () => {
415
+ window.clearInterval(id);
416
+ document.removeEventListener("visibilitychange", tick);
417
+ };
418
+ }, []);
419
+ return now;
420
+ }
421
+
422
+ export function useSinceLastVisit(): SinceLastVisit {
423
+ const identity = useVisitIdentity();
424
+ const { key, user } = identity;
425
+ const getRecord = () => (key ? readVisit(key) : undefined);
426
+ const stored = useSyncExternalStore(subscribe, getRecord, getRecord);
427
+ const getOff = () => sinceRowTurnedOff(user);
428
+ const turnedOff = useSyncExternalStore(subscribe, getOff, getOff);
429
+ const now = useNow();
430
+ // Read as of now: after a gap the stored record still describes the last
431
+ // visit until the tracker's next write, and a page's effects run first.
432
+ const record = useMemo(() => (stored ? advanceVisit(stored, now) : undefined), [stored, now]);
433
+ return { ...identity, record, turnedOff, now };
434
+ }
435
+
436
+ /** Whether the row's Radar Cloud sentence is on screen, so no other Cloud line shows on the Issues page. */
437
+ export function sinceRowShowsCloudLine(state: { rowVisible: boolean; cloudEnabled: boolean }): boolean {
438
+ return state.rowVisible && state.cloudEnabled;
439
+ }
@@ -34,6 +34,14 @@ describe('uncheckedSourceLines', () => {
34
34
  .toEqual(["Helm releases couldn't be checked because Radar's service account isn't allowed to impersonate users, so failed or stuck releases may be missing."])
35
35
  })
36
36
 
37
+ it('says Secret collection is off by policy, not that someone lacks access', () => {
38
+ const lines = uncheckedSourceLines([{ source: 'helm', reason: 'collection_disabled_by_policy' }])
39
+ expect(lines).toEqual([
40
+ "Helm releases weren't checked because Secrets aren't collected on this cluster (rbac.secretAccess: none), so failed or stuck releases may be missing.",
41
+ ])
42
+ expect(uncheckedSourceLines([{ source: 'helm', reason: 'caller_access_denied' }])[0]).not.toContain("aren't collected")
43
+ })
44
+
37
45
  it('says a Kueue queue check was skipped because the caller cannot read ClusterQueues', () => {
38
46
  expect(uncheckedSourceLines([{
39
47
  source: 'kueue', reason: 'caller_access_denied', kinds: [{ group: 'kueue.x-k8s.io', kind: 'ClusterQueue' }],
@@ -34,6 +34,9 @@ function helmLine({ reason, namespaces }: UncheckedSource): string {
34
34
  if (reason === "collector_access_denied") {
35
35
  return `Helm releases ${where}couldn't be checked because Radar's service account isn't allowed to impersonate users, so ${missing}.`;
36
36
  }
37
+ if (reason === "collection_disabled_by_policy") {
38
+ return `Helm releases ${where}weren't checked because Secrets aren't collected on this cluster (rbac.secretAccess: none), so ${missing}.`;
39
+ }
37
40
  if (reason === "caller_access_denied") {
38
41
  return `Radar can't read Helm's release Secrets ${where ? where.trim() : "here"}, so ${missing}.`;
39
42
  }
@@ -0,0 +1,32 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { ApiError } from '../../api/client'
3
+ import { kagentModelsToRead, kagentServersToRead, toRelatedRead } from './KagentAgentRenderer'
4
+
5
+ describe('toRelatedRead', () => {
6
+ it('names why a referenced object was not read, never treating it as absent', () => {
7
+ expect(toRelatedRead({ error: null, isLoading: false }, false)).toBeUndefined()
8
+ expect(toRelatedRead({ data: { spec: {} }, error: null, isLoading: false }, true)).toEqual({ state: 'read', object: { spec: {} } })
9
+ expect(toRelatedRead({ error: new ApiError('gone', 404), isLoading: false }, true)).toEqual({ state: 'notFound' })
10
+ expect(toRelatedRead({ error: new ApiError('no', 403), isLoading: false }, true)).toEqual({ state: 'denied' })
11
+ expect(toRelatedRead({ data: { spec: {} }, error: new ApiError('no', 403), isLoading: false }, true)).toEqual({ state: 'denied' })
12
+ expect(toRelatedRead({ data: { spec: {} }, error: new ApiError('gone', 404), isLoading: false }, true)).toEqual({ state: 'notFound' })
13
+ expect(toRelatedRead({ data: { spec: {} }, error: new ApiError('boom', 500), isLoading: false }, true)).toEqual({ state: 'read', object: { spec: {} } })
14
+ expect(toRelatedRead({ error: new ApiError('boom', 500), isLoading: false }, true)).toMatchObject({ state: 'failed', message: 'boom' })
15
+ expect(toRelatedRead({ error: null, isLoading: true }, true)).toEqual({ state: 'loading' })
16
+ })
17
+ })
18
+
19
+ describe('kagentServersToRead', () => {
20
+ it('reads each kagent RemoteMCPServer once, skips other kinds, and stops at the drawer’s cap', () => {
21
+ const ref = (name: string, kind = 'RemoteMCPServer', group = 'api.kagent.dev') => ({ kind, group, namespace: 'agents', name })
22
+ expect(kagentServersToRead([ref('a'), ref('a'), ref('b', 'Server', 'example.com'), undefined]).map(r => r.name)).toEqual(['a'])
23
+ expect(kagentServersToRead(Array.from({ length: 12 }, (_, i) => ref(`s${i}`)))).toHaveLength(8)
24
+ })
25
+ })
26
+
27
+ describe('kagentModelsToRead', () => {
28
+ it('reads each kagent ModelConfig once and skips other groups', () => {
29
+ const ref = (name: string, group = 'api.kagent.dev') => ({ kind: 'ModelConfig', group, namespace: 'agents', name })
30
+ expect(kagentModelsToRead([ref('gpt'), ref('gpt'), ref('embed'), ref('x', 'models.example.com'), undefined]).map(r => r.name)).toEqual(['gpt', 'embed'])
31
+ })
32
+ })
@@ -0,0 +1,87 @@
1
+ import { useQueries } from '@tanstack/react-query'
2
+ import { KAGENT_AGENT_LIST_CAP, KagentAgentRenderer as BaseKagentAgentRenderer, type KagentRelatedRead } from '@skyhook-io/k8s-ui/components/resources/renderers/KagentAgentRenderer'
3
+ import { getKagentAgentHarness, getKagentAgentTemplateRef, getKagentHarnessDeclarations, getKagentTemplateDeclarations, isKagentModelRef, isKagentServerRef, kagentRefKey, type KagentRef } from '@skyhook-io/k8s-ui/components/resources/resource-utils-kagent'
4
+ import type { ResourceRef } from '@skyhook-io/k8s-ui'
5
+ import type { ResourceWithRelationships } from '@skyhook-io/k8s-ui/types/core'
6
+ import { isForbiddenError, isNotFoundError, resourceQueryOptions, useResource } from '../../api/client'
7
+ import { KAGENT_GROUP } from './routes'
8
+ import { KagentAgentSessions } from './KagentAgentSessions'
9
+
10
+ /** How a read of one referenced object came out, as the drawer shows it. */
11
+ export function toRelatedRead(query: { data?: unknown; error: unknown; isLoading: boolean }, requested: boolean): KagentRelatedRead | undefined {
12
+ if (!requested) return undefined
13
+ if (isForbiddenError(query.error)) return { state: 'denied' }
14
+ if (isNotFoundError(query.error)) return { state: 'notFound' }
15
+ if (query.data) return { state: 'read', object: query.data }
16
+ if (query.error) return { state: 'failed', message: query.error instanceof Error ? query.error.message : undefined }
17
+ return { state: 'loading' }
18
+ }
19
+
20
+ /** The distinct references of one kagent kind to read, as many as the drawer lists. */
21
+ function distinctRefs(refs: (KagentRef | undefined)[], isKind: (ref: KagentRef) => boolean): KagentRef[] {
22
+ const seen = new Set<string>()
23
+ const out: KagentRef[] = []
24
+ for (const ref of refs) {
25
+ if (!ref || !isKind(ref) || seen.has(kagentRefKey(ref))) continue
26
+ seen.add(kagentRefKey(ref))
27
+ out.push(ref)
28
+ if (out.length === KAGENT_AGENT_LIST_CAP) break
29
+ }
30
+ return out
31
+ }
32
+
33
+ /** The distinct kagent RemoteMCPServers a template binds, as many as the drawer lists. */
34
+ export function kagentServersToRead(refs: (KagentRef | undefined)[]): KagentRef[] {
35
+ return distinctRefs(refs, isKagentServerRef)
36
+ }
37
+
38
+ /** The distinct kagent ModelConfigs a template and Harness name. */
39
+ export function kagentModelsToRead(refs: (KagentRef | undefined)[]): KagentRef[] {
40
+ return distinctRefs(refs, isKagentModelRef)
41
+ }
42
+
43
+ function useRelatedReads(kind: string, refs: KagentRef[]): Record<string, KagentRelatedRead> {
44
+ const reads = useQueries({
45
+ queries: refs.map(ref => resourceQueryOptions<any>(kind, ref.namespace, ref.name, KAGENT_GROUP)),
46
+ })
47
+ return Object.fromEntries(refs.map((ref, i) => {
48
+ const q = reads[i]
49
+ const data = (q.data as ResourceWithRelationships<any> | undefined)?.resource
50
+ return [kagentRefKey(ref), toRelatedRead({ data, error: q.error, isLoading: q.isLoading }, true)!]
51
+ }))
52
+ }
53
+
54
+ /**
55
+ * Host wrapper: reads, as the caller, the AgentTemplate and Harness a kagent
56
+ * Agent references, so the drawer can show the models, MCP servers and worker
57
+ * pool they declare, the ModelConfigs named there, and the RemoteMCPServers
58
+ * it binds tools from, whose discovery can fail while the Agent reads Ready.
59
+ * Each is an ordinary resource read, gated as the caller.
60
+ */
61
+ export function KagentAgentRenderer({ data, onNavigate }: { data: any; onNavigate?: (ref: ResourceRef) => void }) {
62
+ const namespace: string = data?.metadata?.namespace ?? ''
63
+ const templateName = data?.spec?.template?.inline ? undefined : getKagentAgentTemplateRef(data)
64
+ const harnessName = getKagentAgentHarness(data)
65
+ const template = useResource<any>('agenttemplates', namespace, templateName ?? '', KAGENT_GROUP, { enabled: !!templateName })
66
+ const harness = useResource<any>('harnesses', namespace, harnessName ?? '', KAGENT_GROUP, { enabled: !!harnessName })
67
+ const templateRead = toRelatedRead(template, !!templateName)
68
+ const templateSpec = data?.spec?.template?.inline ?? (templateRead?.state === 'read' ? templateRead.object.spec : undefined)
69
+ const declared = templateSpec ? getKagentTemplateDeclarations(templateSpec, namespace) : undefined
70
+ const harnessRead = toRelatedRead(harness, !!harnessName)
71
+ const harnessModels = harnessRead?.state === 'read' ? getKagentHarnessDeclarations(harnessRead.object) : undefined
72
+ const mcpServers = useRelatedReads('remotemcpservers', kagentServersToRead(declared?.tools.flatMap(t => (t.kind === 'mcp' ? [t.server] : [])) ?? []))
73
+ const modelConfigs = useRelatedReads('modelconfigs', kagentModelsToRead([declared?.model, harnessModels?.summarizerModel, harnessModels?.memoryModel]))
74
+ return (
75
+ <BaseKagentAgentRenderer
76
+ data={data}
77
+ onNavigate={onNavigate}
78
+ related={{
79
+ template: templateRead,
80
+ harness: harnessRead,
81
+ mcpServers,
82
+ modelConfigs,
83
+ }}
84
+ sessions={namespace && data?.metadata?.name ? <KagentAgentSessions agent={{ namespace, name: data.metadata.name }} /> : undefined}
85
+ />
86
+ )
87
+ }