@skyhook-io/radar-app 1.22.1 → 1.23.0

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 (234) hide show
  1. package/package.json +8 -8
  2. package/src/App.tsx +131 -38
  3. package/src/RadarApp.basename.test.tsx +177 -0
  4. package/src/RadarApp.settings.test.tsx +33 -0
  5. package/src/RadarApp.tsx +5 -0
  6. package/src/api/agentSandbox.ts +259 -0
  7. package/src/api/client.autoPromConnect.test.tsx +43 -0
  8. package/src/api/client.metricsRelayCheck.test.tsx +134 -0
  9. package/src/api/client.ts +128 -25
  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/prometheusCharts.ts +5 -0
  15. package/src/api/radarFeatures.test.ts +9 -0
  16. package/src/api/radarFeatures.ts +13 -0
  17. package/src/api/substrateWorkspace.test.ts +72 -0
  18. package/src/api/substrateWorkspace.ts +1394 -0
  19. package/src/api/vulnerabilities.ts +207 -9
  20. package/src/api/workloadSource.test.tsx +1172 -0
  21. package/src/api/workloadSource.ts +408 -0
  22. package/src/components/APIUnreachableBanner.test.tsx +19 -0
  23. package/src/components/APIUnreachableBanner.tsx +20 -0
  24. package/src/components/CloudConnectFlow.tsx +46 -7
  25. package/src/components/CloudFunnelButton.test.tsx +193 -7
  26. package/src/components/CloudFunnelButton.tsx +127 -32
  27. package/src/components/ConnectionErrorView.test.tsx +63 -2
  28. package/src/components/ConnectionErrorView.tsx +88 -68
  29. package/src/components/SelfManagedStart.tsx +12 -2
  30. package/src/components/agentsandbox/AgentSandboxKindLists.tsx +41 -0
  31. package/src/components/agentsandbox/AgentSandboxLists.test.tsx +410 -0
  32. package/src/components/agentsandbox/AgentSandboxOverview.test.tsx +333 -0
  33. package/src/components/agentsandbox/AgentSandboxOverview.tsx +555 -0
  34. package/src/components/agentsandbox/AgentSandboxSidebar.test.tsx +97 -0
  35. package/src/components/agentsandbox/AgentSandboxSummary.test.tsx +439 -0
  36. package/src/components/agentsandbox/AgentSandboxSummary.tsx +956 -0
  37. package/src/components/agentsandbox/AgentSandboxTables.tsx +966 -0
  38. package/src/components/agentsandbox/AgentSandboxView.tsx +34 -0
  39. package/src/components/agentsandbox/agentsandbox.fixtures.ts +135 -0
  40. package/src/components/agentsandbox/data.ts +135 -0
  41. package/src/components/agentsandbox/host.test.ts +27 -0
  42. package/src/components/agentsandbox/host.tsx +85 -0
  43. package/src/components/agentsandbox/labels.test.ts +42 -0
  44. package/src/components/agentsandbox/labels.ts +146 -0
  45. package/src/components/agentsandbox/listFilters.ts +85 -0
  46. package/src/components/agentsandbox/lists.ts +52 -0
  47. package/src/components/agentsandbox/routes.ts +23 -0
  48. package/src/components/agentsandbox/shared.tsx +321 -0
  49. package/src/components/agentsandbox/useAgentSandboxSidebarWorkspace.ts +69 -0
  50. package/src/components/agentsandbox/workspace.fixtures.ts +125 -0
  51. package/src/components/agentsandbox/workspace.tsx +258 -0
  52. package/src/components/agentsandbox/workspaceRoute.ts +18 -0
  53. package/src/components/applications/ApplicationsView.openResource.test.tsx +248 -3
  54. package/src/components/applications/ApplicationsView.tsx +156 -3
  55. package/src/components/audit/VulnerabilitiesColumns.test.tsx +487 -0
  56. package/src/components/audit/VulnerabilitiesRisk.test.tsx +318 -0
  57. package/src/components/audit/VulnerabilitiesView.test.tsx +458 -13
  58. package/src/components/audit/VulnerabilitiesView.tsx +639 -199
  59. package/src/components/cloudHints/AgentSetupCloudRow.tsx +28 -0
  60. package/src/components/cloudHints/CloudHintLink.tsx +29 -0
  61. package/src/components/cloudHints/SharedInstallAiLine.tsx +36 -0
  62. package/src/components/cloudHints/cloudHints.test.ts +126 -0
  63. package/src/components/cloudHints/cloudHints.ts +131 -0
  64. package/src/components/cloudHints/cloudHintsGate.test.tsx +70 -0
  65. package/src/components/cloudHints/cloudLinks.test.ts +52 -0
  66. package/src/components/cloudHints/cloudLinks.ts +31 -0
  67. package/src/components/cloudHints/hintStorage.ts +28 -0
  68. package/src/components/cnpg/CNPGView.tsx +4 -7
  69. package/src/components/diagnose/ActivityTurn.tsx +6 -4
  70. package/src/components/diagnose/AgentSetupNotice.tsx +5 -0
  71. package/src/components/diagnose/AssessmentCard.tsx +1 -2
  72. package/src/components/diagnose/ContinueInAgentButton.test.tsx +7 -0
  73. package/src/components/diagnose/DiagnoseContext.tsx +7 -0
  74. package/src/components/diagnose/DiagnoseSurface.escape.test.tsx +215 -0
  75. package/src/components/diagnose/DiagnoseSurface.tsx +57 -1
  76. package/src/components/diagnose/Home.test.tsx +6 -0
  77. package/src/components/diagnose/Home.tsx +10 -3
  78. package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +1 -1
  79. package/src/components/diagnose/InvestigationEvidencePane.tsx +19 -2
  80. package/src/components/diagnose/InvestigationFindingsFooter.test.tsx +413 -0
  81. package/src/components/diagnose/InvestigationView.tsx +120 -23
  82. package/src/components/diagnose/investigationEvidence/identity.test.ts +1 -1
  83. package/src/components/diagnose/investigationEvidence/projection.test.ts +1 -1
  84. package/src/components/diagnose/investigationState.ts +9 -0
  85. package/src/components/diagnose/parts.test.tsx +11 -3
  86. package/src/components/diagnose/toolCallLabel.ts +3 -0
  87. package/src/components/gitops/RemoteDestinationCloudHint.tsx +6 -14
  88. package/src/components/home/ActivitySummary.tsx +3 -8
  89. package/src/components/home/ClusterHealthCard.tsx +91 -17
  90. package/src/components/home/ClusterHealthCard.utilization.test.tsx +187 -0
  91. package/src/components/home/HomeAgentBlock.tsx +2 -0
  92. package/src/components/home/HomeView.tsx +9 -29
  93. package/src/components/home/MCPSetupDialog.test.tsx +9 -0
  94. package/src/components/home/MCPSetupDialog.tsx +6 -2
  95. package/src/components/home/McpCloudLine.test.tsx +162 -0
  96. package/src/components/home/McpCloudLine.tsx +95 -0
  97. package/src/components/home/ProblemsPanel.investigate.test.tsx +2 -2
  98. package/src/components/home/TopologyPreview.test.tsx +31 -30
  99. package/src/components/home/TopologyPreview.tsx +19 -28
  100. package/src/components/home/mcpToolCatalog.test.ts +10 -0
  101. package/src/components/home/mcpToolCatalog.ts +7 -7
  102. package/src/components/issues/ClusterSchedulingBlockerRow.tsx +35 -0
  103. package/src/components/issues/IssuesPane.render.test.tsx +36 -1
  104. package/src/components/issues/IssuesPane.tsx +181 -23
  105. package/src/components/issues/SinceLastVisitRow.render.test.tsx +302 -0
  106. package/src/components/issues/SinceLastVisitRow.tsx +71 -0
  107. package/src/components/issues/sinceLastVisit.test.ts +266 -0
  108. package/src/components/issues/sinceLastVisit.ts +439 -0
  109. package/src/components/kagent/KagentAgentRenderer.test.ts +32 -0
  110. package/src/components/kagent/KagentAgentRenderer.tsx +87 -0
  111. package/src/components/kagent/KagentAgentSessions.test.tsx +166 -0
  112. package/src/components/kagent/KagentAgentSessions.tsx +124 -0
  113. package/src/components/kagent/KagentDetailPage.tsx +106 -0
  114. package/src/components/kagent/KagentLists.tsx +412 -0
  115. package/src/components/kagent/KagentOverview.tsx +234 -0
  116. package/src/components/kagent/KagentPages.tsx +690 -0
  117. package/src/components/kagent/KagentRuntimeTabs.test.tsx +219 -0
  118. package/src/components/kagent/KagentRuntimeTabs.tsx +283 -0
  119. package/src/components/kagent/KagentSidebar.test.tsx +112 -0
  120. package/src/components/kagent/KagentView.tsx +109 -0
  121. package/src/components/kagent/KagentWorkspace.test.tsx +876 -0
  122. package/src/components/kagent/host.tsx +144 -0
  123. package/src/components/kagent/routes.ts +31 -0
  124. package/src/components/kagent/shared.tsx +336 -0
  125. package/src/components/kagent/useKagentRuntime.test.tsx +77 -0
  126. package/src/components/kagent/useKagentSidebarWorkspace.ts +67 -0
  127. package/src/components/kagent/workspace.fixtures.ts +108 -0
  128. package/src/components/kagent/workspaceRoute.ts +18 -0
  129. package/src/components/resource/MetricsNotConnected.test.tsx +28 -0
  130. package/src/components/resource/MetricsNotConnected.tsx +10 -7
  131. package/src/components/resource/PrometheusCharts.tsx +10 -1
  132. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +9 -0
  133. package/src/components/resource/PrometheusChartsGrid.tsx +3 -3
  134. package/src/components/resource/SubstrateHealthCharts.test.tsx +13 -1
  135. package/src/components/resource/SubstrateHealthCharts.tsx +9 -15
  136. package/src/components/resources/ResourceDetailDrawer.tsx +1 -0
  137. package/src/components/resources/ResourcesView.tsx +2 -6
  138. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +5 -4
  139. package/src/components/resources/renderers/PodRenderer.tsx +8 -2
  140. package/src/components/resources/renderers/RolloutRenderer.tsx +4 -1
  141. package/src/components/resources/renderers/WorkloadRenderer.tsx +4 -1
  142. package/src/components/settings/LocalIntegrationStatus.test.tsx +1 -0
  143. package/src/components/settings/LocalIntegrationStatus.tsx +3 -2
  144. package/src/components/settings/SettingsDialog.tsx +84 -16
  145. package/src/components/settings/SubstrateSettings.lifecycle.test.tsx +210 -0
  146. package/src/components/settings/SubstrateSettings.test.tsx +131 -0
  147. package/src/components/settings/SubstrateSettings.tsx +544 -0
  148. package/src/components/settings/settings-state.test.ts +21 -3
  149. package/src/components/settings/settings-state.ts +13 -3
  150. package/src/components/share/ShareLinkButton.test.tsx +360 -0
  151. package/src/components/share/ShareLinkButton.tsx +391 -0
  152. package/src/components/share/openShareInCloud.test.ts +29 -0
  153. package/src/components/share/openShareInCloud.ts +10 -0
  154. package/src/components/share/shareLink.test.ts +129 -0
  155. package/src/components/share/shareLink.ts +175 -0
  156. package/src/components/substrate/SubstrateActorDrawer.tsx +87 -0
  157. package/src/components/substrate/SubstrateActorOverview.tsx +489 -0
  158. package/src/components/substrate/SubstrateActorPage.tsx +384 -0
  159. package/src/components/substrate/SubstrateActors.test.tsx +1094 -0
  160. package/src/components/substrate/SubstrateActors.tsx +612 -0
  161. package/src/components/substrate/SubstrateAttentionList.tsx +441 -0
  162. package/src/components/substrate/SubstrateConnect.tsx +88 -0
  163. package/src/components/substrate/SubstrateOverview.test.tsx +396 -0
  164. package/src/components/substrate/SubstrateOverview.tsx +575 -0
  165. package/src/components/substrate/SubstratePages.test.tsx +478 -0
  166. package/src/components/substrate/SubstratePool.test.tsx +462 -0
  167. package/src/components/substrate/SubstratePoolPage.tsx +95 -0
  168. package/src/components/substrate/SubstratePoolSummary.tsx +485 -0
  169. package/src/components/substrate/SubstrateSidebar.test.tsx +101 -0
  170. package/src/components/substrate/SubstrateStateBar.tsx +63 -0
  171. package/src/components/substrate/SubstrateTemplates.tsx +376 -0
  172. package/src/components/substrate/SubstrateView.tsx +173 -0
  173. package/src/components/substrate/SubstrateWorkerPodContext.tsx +73 -0
  174. package/src/components/substrate/SubstrateWorkers.tsx +389 -0
  175. package/src/components/substrate/attention.ts +81 -0
  176. package/src/components/substrate/contextPin.tsx +69 -0
  177. package/src/components/substrate/host.tsx +83 -0
  178. package/src/components/substrate/kubectlTarget.test.tsx +77 -0
  179. package/src/components/substrate/readings.test.ts +484 -0
  180. package/src/components/substrate/readings.ts +997 -0
  181. package/src/components/substrate/routes.ts +103 -0
  182. package/src/components/substrate/shared.tsx +426 -0
  183. package/src/components/substrate/substrate.fixtures.ts +325 -0
  184. package/src/components/substrate/useSubstrateSidebarWorkspace.ts +87 -0
  185. package/src/components/substrate/workspaceRoute.ts +23 -0
  186. package/src/components/traffic/TrafficConnectionsTable.test.tsx +9 -0
  187. package/src/components/traffic/TrafficConnectionsTable.tsx +4 -2
  188. package/src/components/traffic/TrafficFilterSidebar.tsx +19 -14
  189. package/src/components/traffic/TrafficFlowList.test.tsx +63 -0
  190. package/src/components/traffic/TrafficFlowList.tsx +9 -5
  191. package/src/components/traffic/TrafficGraph.test.tsx +26 -0
  192. package/src/components/traffic/TrafficGraph.tsx +17 -14
  193. package/src/components/traffic/TrafficGraphTooLarge.tsx +2 -0
  194. package/src/components/traffic/TrafficGraphUnavailable.tsx +3 -1
  195. package/src/components/traffic/TrafficView.tsx +26 -56
  196. package/src/components/traffic/trafficFilters.test.ts +61 -1
  197. package/src/components/traffic/trafficFilters.ts +68 -8
  198. package/src/components/velero/VeleroOverview.tsx +2 -2
  199. package/src/components/velero/VeleroView.tsx +3 -6
  200. package/src/components/vulnerabilities/columns.tsx +132 -0
  201. package/src/components/vulnerabilities/filters.tsx +317 -0
  202. package/src/components/vulnerabilities/owner.test.ts +54 -0
  203. package/src/components/vulnerabilities/owner.tsx +163 -0
  204. package/src/components/vulnerabilities/parts.test.ts +126 -12
  205. package/src/components/vulnerabilities/parts.tsx +612 -52
  206. package/src/components/vulnerabilities/traffic.test.tsx +65 -0
  207. package/src/components/vulnerabilities/traffic.tsx +40 -0
  208. package/src/components/workload/WorkloadView.substrateVersion.test.tsx +88 -0
  209. package/src/components/workload/WorkloadView.tsx +119 -14
  210. package/src/components/workload/WorkloadView.workloadSource.test.tsx +121 -0
  211. package/src/components/workspace/layout.tsx +13 -7
  212. package/src/components/workspace/sidebar.test.ts +48 -0
  213. package/src/components/workspace/sidebar.ts +73 -3
  214. package/src/components/workspace/table.ts +2 -1
  215. package/src/context/ConnectionContext.tsx +24 -5
  216. package/src/context/ConnectionProvider.connectionId.test.tsx +14 -0
  217. package/src/context/ConnectionProvider.handover.test.tsx +94 -0
  218. package/src/context/DiagnoseCustomization.tsx +20 -2
  219. package/src/contexts/RegistryAccessMode.test.tsx +51 -0
  220. package/src/contexts/RegistryAccessMode.tsx +25 -0
  221. package/src/hooks/useEventSource.test.tsx +275 -4
  222. package/src/hooks/useEventSource.ts +278 -51
  223. package/src/index.ts +1 -0
  224. package/src/integrations/resourceHost.ts +12 -6
  225. package/src/integrations/resourceHosts.test.tsx +27 -1
  226. package/src/integrations/resourceHosts.tsx +15 -7
  227. package/src/integrations/sidebarWorkspaces.test.tsx +63 -0
  228. package/src/integrations/sidebarWorkspaces.ts +41 -0
  229. package/src/integrations/workspaceRoute.ts +1 -1
  230. package/src/integrations/workspaceRoutes.ts +7 -1
  231. package/src/integrations/workspaceScreens.tsx +6 -0
  232. package/src/utils/navigation.test.ts +1 -6
  233. package/src/utils/navigation.ts +9 -44
  234. package/src/utils/network-policy-navigation.test.ts +21 -36
@@ -0,0 +1,997 @@
1
+ import { formatDuration, toneFillClass, type BadgeSeverity, type StatusTone } from '@skyhook-io/k8s-ui'
2
+ import { isForbiddenError } from '../../api/client'
3
+ import { substrateErrorCode } from '../../api/substrateWorkspace'
4
+ import type {
5
+ KagentActor,
6
+ KagentAgentRef,
7
+ KagentAttribution,
8
+ KagentUnattributed,
9
+ SubstrateAPITier,
10
+ SubstrateActorState,
11
+ SubstrateAttention,
12
+ SubstrateCode,
13
+ SubstrateCoverage,
14
+ SubstrateRef,
15
+ SubstrateResumesWith,
16
+ SubstrateSnapshot,
17
+ SubstrateStateCounts,
18
+ SubstrateSubject,
19
+ SubstrateTemplateRow,
20
+ SubstratePoolRow,
21
+ SubstrateK8sPool,
22
+ SubstratePoolsCoverage,
23
+ SubstrateLacking,
24
+ SubstrateWorkerImpact,
25
+ SubstrateWorkerRow,
26
+ } from '../../api/substrateWorkspace'
27
+
28
+ // Radar's reading of Substrate values for the screens: labels, tones and the
29
+ // sentences that explain them. Pure, so the screens and tests share them.
30
+
31
+ export const ACTOR_STATE_LABEL: Record<SubstrateActorState, string> = {
32
+ running: 'Running',
33
+ suspended: 'Suspended',
34
+ resuming: 'Resuming',
35
+ suspending: 'Suspending',
36
+ reverting: 'Reverting',
37
+ crashed: 'Crashed',
38
+ deleting: 'Deleting',
39
+ unknown: 'Unknown',
40
+ }
41
+
42
+ /** The states an actor passes through on its way between running and suspended. */
43
+ export const IN_PROGRESS_STATES: readonly SubstrateActorState[] = ['resuming', 'suspending', 'reverting', 'deleting']
44
+
45
+ /** Display order, the state bar's and the legend's. */
46
+ export const ACTOR_STATE_ORDER: readonly SubstrateActorState[] = ['crashed', 'resuming', 'suspending', 'reverting', 'deleting', 'running', 'suspended', 'unknown']
47
+
48
+ // One tone per state, the same on badges, state bars and the placement grid.
49
+ // Suspended is where most actors rest, so it reads quietest. A resume,
50
+ // suspend, revert or delete in flight is routine: one quiet in-flight tone.
51
+ // Amber is kept for a transition that is stuck (actorStateReading), a crash
52
+ // reads as a failure.
53
+ const STATE_TONE: Record<SubstrateActorState, StatusTone> = {
54
+ running: 'healthy',
55
+ suspended: 'unknown',
56
+ resuming: 'neutral',
57
+ suspending: 'neutral',
58
+ reverting: 'neutral',
59
+ deleting: 'neutral',
60
+ crashed: 'unhealthy',
61
+ unknown: 'unknown',
62
+ }
63
+
64
+ export function actorStateTone(state: SubstrateActorState): StatusTone {
65
+ return STATE_TONE[state] ?? 'unknown'
66
+ }
67
+
68
+ /**
69
+ * A state's fill on a bar or a legend dot. Suspended and Unknown share a grey
70
+ * chip, whose word tells them apart; a bar has no words, so Suspended, a
71
+ * settled state, takes the quiet resting fill, and Unknown keeps Radar's
72
+ * unknown slate: an actor Radar can't place must never read as one at rest.
73
+ */
74
+ export function actorStateFill(state: SubstrateActorState): string {
75
+ return state === 'suspended' ? 'bg-theme-border-light' : toneFillClass(actorStateTone(state))
76
+ }
77
+
78
+ /**
79
+ * The tone of an actor whose worker is in trouble: a lost sandbox is lost; an
80
+ * unavailable worker puts it at risk, as the worker's own chip and row say; a
81
+ * draining one is a warning.
82
+ */
83
+ export function workerImpactTone(kind: SubstrateWorkerImpact['kind']): StatusTone {
84
+ return kind === 'restarted' ? 'unhealthy' : kind === 'unavailable' ? 'alert' : 'degraded'
85
+ }
86
+
87
+ const TONE_SEVERITY: Record<StatusTone, BadgeSeverity> = {
88
+ healthy: 'success',
89
+ neutral: 'info',
90
+ degraded: 'warning',
91
+ alert: 'alert',
92
+ unhealthy: 'error',
93
+ unknown: 'neutral',
94
+ }
95
+
96
+ export function toneSeverity(tone: StatusTone): BadgeSeverity {
97
+ return TONE_SEVERITY[tone]
98
+ }
99
+
100
+ export interface ActorStateReading {
101
+ label: string
102
+ severity: BadgeSeverity
103
+ /** Why the chip reads as it does, when the state alone doesn't say. */
104
+ title?: string
105
+ }
106
+
107
+ /**
108
+ * An actor's state chip: Substrate's state, qualified when its worker is in
109
+ * trouble ("Running · worker unavailable") or when a transition has held past
110
+ * the stuck threshold ("Resuming · stuck"). Only a stuck transition is amber;
111
+ * one in flight reads in the quiet in-flight tone.
112
+ */
113
+ export function actorStateReading(
114
+ state: SubstrateActorState,
115
+ opts: { impact?: Pick<SubstrateWorkerImpact, 'kind' | 'reading'>; updateTime?: string; now?: number } = {},
116
+ ): ActorStateReading {
117
+ const label = ACTOR_STATE_LABEL[state] ?? state
118
+ if (state === 'crashed') return { label, severity: 'error' }
119
+ if (opts.impact) return { label: `${label} · ${IMPACT_LABEL[opts.impact.kind]}`, severity: toneSeverity(workerImpactTone(opts.impact.kind)), title: opts.impact.reading }
120
+ if (stuckInTransition(state, opts.updateTime, opts.now)) {
121
+ return { label: `${label} · stuck`, severity: 'warning', title: `${label} for longer than ${formatDuration(STUCK_AFTER_MS)}, past Radar’s stuck threshold.` }
122
+ }
123
+ return { label, severity: toneSeverity(actorStateTone(state)) }
124
+ }
125
+
126
+ export const IMPACT_LABEL: Record<SubstrateWorkerImpact['kind'], string> = {
127
+ unavailable: 'worker unavailable',
128
+ draining: 'worker draining',
129
+ restarted: 'sandbox lost',
130
+ }
131
+
132
+ /** The Actors screen's segments: one per state an operator acts on, with the transitions together. */
133
+ export type ActorSegment = 'all' | 'crashed' | 'inProgress' | 'suspended' | 'running'
134
+
135
+ export const ACTOR_SEGMENTS: readonly { id: ActorSegment; label: string; states: readonly SubstrateActorState[] }[] = [
136
+ { id: 'all', label: 'All', states: [] },
137
+ { id: 'crashed', label: 'Crashed', states: ['crashed'] },
138
+ { id: 'inProgress', label: 'In progress', states: IN_PROGRESS_STATES },
139
+ { id: 'suspended', label: 'Suspended', states: ['suspended'] },
140
+ { id: 'running', label: 'Running', states: ['running'] },
141
+ ]
142
+
143
+ export function segmentCount(counts: SubstrateStateCounts | undefined, segment: ActorSegment): number | undefined {
144
+ if (!counts) return undefined
145
+ if (segment === 'all') return counts.total
146
+ return ACTOR_SEGMENTS.find((s) => s.id === segment)!.states.reduce((n, s) => n + (counts.byState[s] ?? 0), 0)
147
+ }
148
+
149
+ /** The segment a state filter from a link (`?state=`) falls under. */
150
+ export function segmentOfState(state: string | null): ActorSegment {
151
+ if (!state) return 'all'
152
+ if (state === 'inProgress') return 'inProgress'
153
+ const seg = ACTOR_SEGMENTS.find((s) => s.id !== 'all' && s.states.includes(state as SubstrateActorState))
154
+ return seg?.id ?? 'all'
155
+ }
156
+
157
+ const FIDELITY_LABEL: Record<NonNullable<SubstrateSnapshot['fidelity']>, string> = {
158
+ memory: 'memory',
159
+ rootfs: 'root filesystem',
160
+ volumes: 'volumes',
161
+ }
162
+
163
+ /** What a snapshot holds, in a word or two. */
164
+ export function fidelityLabel(fidelity: SubstrateSnapshot['fidelity']): string {
165
+ return fidelity ? FIDELITY_LABEL[fidelity] : 'unspecified'
166
+ }
167
+
168
+ /** Which generation a resume starts from, and what it gives back: "resumes where it left off", "resumes from gen 6: …". */
169
+ export type ResumeCondition = 'compatibleRuntime' | 'runtimeMismatch'
170
+
171
+ interface ResumeReading {
172
+ newestSnapshot?: SubstrateSnapshot
173
+ resumeGeneration?: number
174
+ resumesWith: SubstrateResumesWith
175
+ resumeCondition?: ResumeCondition
176
+ }
177
+
178
+ export function resumeText(row: ResumeReading): string {
179
+ if (row.resumeGeneration === undefined) return resumesWithText('cold')
180
+ const older = row.newestSnapshot && row.resumeGeneration !== row.newestSnapshot.generation
181
+ const what = row.resumeCondition === 'compatibleRuntime' ? 'resumes where it left off on a compatible runtime' : resumesWithText(row.resumesWith)
182
+ return older ? `resumes from gen ${row.resumeGeneration}: ${what}` : what
183
+ }
184
+
185
+ const RESUME_SENTENCE: Record<SubstrateResumesWith, string> = {
186
+ memory: 'Resumes where it left off: the snapshot holds its memory.',
187
+ filesystem: 'Resumes by restarting the agent on its saved files: the snapshot holds its root filesystem, not its memory.',
188
+ volumes: 'Resumes by restarting the agent with only its saved volumes.',
189
+ cold: 'Boots fresh: there is no snapshot to resume from.',
190
+ unknown: 'What a resume restores is unknown: Substrate names no fidelity for the snapshot.',
191
+ }
192
+
193
+ /**
194
+ * What a resume restores, in a sentence. Memory holds only on a compatible
195
+ * runtime; a known mismatch restarts from the saved files.
196
+ */
197
+ export function resumeConditionSentence(resumesWith: SubstrateResumesWith, condition?: ResumeCondition): string {
198
+ if (condition === 'compatibleRuntime') return 'Snapshot holds memory: resumes where it left off on a compatible runtime, otherwise restarts from its saved files.'
199
+ if (condition === 'runtimeMismatch') return 'Restarts from its saved files: no worker of its class can restore its memory.'
200
+ return RESUME_SENTENCE[resumesWith]
201
+ }
202
+
203
+ /** What the next resume does, as a sentence, naming the generation when it is not the newest. */
204
+ export function resumeSentence(row: ResumeReading): string {
205
+ if (row.resumeGeneration === undefined) return RESUME_SENTENCE.cold
206
+ const older = row.newestSnapshot && row.resumeGeneration !== row.newestSnapshot.generation
207
+ const sentence = resumeConditionSentence(row.resumesWith, row.resumeCondition)
208
+ return older ? `${sentence} It resumes from generation ${row.resumeGeneration}: the newest is not stored yet.` : sentence
209
+ }
210
+
211
+ /** Why a revert drops a generation newer than the one it keeps. */
212
+ export const DISCARD_WHY: Record<string, string> = {
213
+ localOnly: 'only on its node',
214
+ uploadPending: 'its upload may still finish; waiting for it before reverting keeps it',
215
+ uploadAbandoned: 'Substrate will never record its upload',
216
+ incomplete: 'recorded but never captured',
217
+ }
218
+
219
+ /**
220
+ * What a state badge leaves to say: "for 36m", "upload pending for 36m", or
221
+ * the crash message. The badge names the state, so the reason's own state
222
+ * word is not repeated.
223
+ */
224
+ export function stateExtra(state: SubstrateActorState, reason: string | undefined): string | undefined {
225
+ if (!reason) return undefined
226
+ const label = ACTOR_STATE_LABEL[state]
227
+ if (label && reason.startsWith(`${label} `)) return reason.slice(label.length + 1)
228
+ if (reason === label) return undefined
229
+ return state === 'crashed' ? reason : reason[0].toLowerCase() + reason.slice(1)
230
+ }
231
+
232
+ /** What a resume from the newest snapshot gives back. */
233
+ export function resumesWithText(r: SubstrateResumesWith): string {
234
+ switch (r) {
235
+ case 'memory':
236
+ return 'resumes where it left off'
237
+ case 'filesystem':
238
+ return 'restarts the agent on its saved files'
239
+ case 'volumes':
240
+ return 'restarts the agent with its saved volumes only'
241
+ case 'cold':
242
+ return 'boots fresh'
243
+ default:
244
+ return 'Substrate names no fidelity, so what a resume restores is unknown'
245
+ }
246
+ }
247
+
248
+ /** Where a snapshot's files are kept, in a few words. */
249
+ export function durableText(s: SubstrateSnapshot): { text: string; tone: StatusTone; title: string } {
250
+ switch (s.durable) {
251
+ case 'completed':
252
+ return { text: 'stored', tone: 'healthy', title: 'Uploaded to object storage: it survives the loss of the node it was taken on.' }
253
+ case 'pending':
254
+ return {
255
+ text: 'upload pending',
256
+ tone: 'degraded',
257
+ title: s.locality
258
+ ? `Still uploading from node ${s.locality}. Until it completes, the state exists only on that node.`
259
+ : 'Still uploading. Until it completes, the state exists only on the node it was taken on.',
260
+ }
261
+ default:
262
+ return {
263
+ text: s.locality ? `only on ${s.locality}` : 'not stored',
264
+ tone: 'degraded',
265
+ title: s.locality
266
+ ? `Substrate recorded no durable copy: the files exist only on node ${s.locality}.`
267
+ : 'Substrate recorded no durable copy, and names no node holding the files.',
268
+ }
269
+ }
270
+ }
271
+
272
+ /**
273
+ * The one plan for a template whose golden actor and actors were both killed
274
+ * over its memory limit: a new template, which also builds a new golden
275
+ * snapshot, then a revert and template update for each crashed actor. Its
276
+ * commands are the crash group's, in that order. The move is what may drop
277
+ * a snapshot's memory and files, so the step says so beside it, as the
278
+ * server's group step does.
279
+ */
280
+ export function memoryRebuildStep(crashed: number): string {
281
+ return crashed === 1
282
+ ? 'Recreate with more memory and identical volumes, mounts and snapshot location. Revert the actor, move it over, then resume. The move may keep only volumes.'
283
+ : 'Recreate with more memory and identical volumes, mounts and snapshot location. Revert the actors, move them over, then resume. The move may keep only volumes.'
284
+ }
285
+
286
+ /** The recovery step for a kagent session's actor, which kagent recovers itself (pkg/substrate kagentActorStep). */
287
+ export const KAGENT_RECOVER_STEP = 'This actor looks like a kagent session. Recover it through kagent (its RevertSession API, or Recover on the chat where offered) or delete the chat there. Moved to another template with kubectl ate, it can’t be recovered.'
288
+
289
+ /** The step for a standalone kagent sandbox's actor, which has no chat to recover (pkg/substrate kagentSandboxStep). */
290
+ export const KAGENT_SANDBOX_STEP = 'This actor looks like a kagent sandbox. If so, delete the sandbox through kagent (its SandboxService) and create a new one; don’t move or revert it with kubectl ate.'
291
+
292
+ /**
293
+ * kagent's step for an actor it runs: a sandbox's, else a session's, naming the Agent when the session
294
+ * is attributed to one (pkg/substrate KagentStepForAgent).
295
+ */
296
+ export function kagentRecoverStep(k?: { sandbox?: boolean } & Partial<KagentActor>): string {
297
+ if (k?.sandbox || k?.kind === 'sandbox') return KAGENT_SANDBOX_STEP
298
+ return k?.kind === 'agentSession' && k.agent
299
+ ? KAGENT_RECOVER_STEP.replace('This actor looks like a kagent session', `This actor is a session of kagent Agent ${agentText(k.agent)}`)
300
+ : KAGENT_RECOVER_STEP
301
+ }
302
+
303
+ /** What Radar can't see of a kagent session: its chat. */
304
+ export const KAGENT_OUTCOME = 'Conversation outcome: not visible to Radar. kagent keeps chats in its own database, and a suspended actor can follow a failed model call.'
305
+
306
+ export function agentText(a: KagentAgentRef): string {
307
+ return `${a.namespace}/${a.name}`
308
+ }
309
+
310
+ /** The /actors `agent` parameter for an Agent. */
311
+ export function agentFilterValue(a: KagentAgentRef): string {
312
+ return agentText(a)
313
+ }
314
+
315
+ /**
316
+ * A kagent session id short enough for a row. kagent's ids are UUIDv7, whose
317
+ * leading digits are a timestamp shared by sessions started together, so the
318
+ * short form is the random tail.
319
+ */
320
+ export function shortSessionId(id: string): string {
321
+ const hex = id.replace(/-/g, '')
322
+ return hex.length > 8 ? `…${hex.slice(-8)}` : id
323
+ }
324
+
325
+ function agentList(agents: KagentAgentRef[] | undefined): string {
326
+ const names = (agents ?? []).map(agentText)
327
+ return names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`
328
+ }
329
+
330
+ /**
331
+ * Why a kagent session is tied to no Agent, in a sentence; atespace is the actor's, which kagent makes
332
+ * its Agent's namespace.
333
+ */
334
+ export function kagentUnattributedText(k: KagentUnattributed, atespace: string, coverage?: SubstratePoolsCoverage): string {
335
+ switch (k.reason) {
336
+ case 'earlierRevision':
337
+ return `Not tied to an Agent: its template is named for ${agentList(k.candidates) || 'an Agent'}, but for neither of its current revisions. It may be an earlier session of it, or of a deleted Agent with the same name.`
338
+ case 'agentNotReadable':
339
+ return `Not tied to an Agent: Radar didn’t read kagent Agents in namespace ${atespace} (${kagentUnreadWhy(coverage, atespace)}).`
340
+ case 'noAgent':
341
+ return `Not tied to an Agent: no kagent Agent in namespace ${atespace} has a revision with this template.`
342
+ case 'ambiguous':
343
+ return `Not tied to an Agent: ${agentList(k.candidates)} each make a template with this name.`
344
+ case 'templateUnknown':
345
+ return 'Not tied to an Agent: kagent did not name its template.'
346
+ default:
347
+ return 'Not tied to an Agent.'
348
+ }
349
+ }
350
+
351
+ /** The failed golden snapshot step for a kagent Agent's template, which kagent owns and rebuilds (pkg/substrate KagentGoldenStep). */
352
+ export function kagentGoldenStep(agent: KagentAgentRef, memory: boolean): string {
353
+ return memory
354
+ ? `Raise config.runtimeDefaults.memory in kagent’s Helm values; Agent ${agentText(agent)} then gets a new revision and template. Don’t recreate this one.`
355
+ : `Fix the cause on Agent ${agentText(agent)}: kagent owns this template and rebuilds it itself. The Agent’s Ready condition says when it retries.`
356
+ }
357
+
358
+ /** What a template is to kagent, in a few words; undefined for a template kagent doesn't own. */
359
+ export function kagentTemplateText(k?: KagentAttribution): string | undefined {
360
+ if (k?.kind === 'agentSession') {
361
+ const which = k.earlierRevision
362
+ ? `an earlier revision${k.revision ? ` (${k.revision})` : ''}, before the one new sessions start on`
363
+ : k.newSessions ? 'the revision new sessions start on' : k.desired ? 'its desired revision, not yet the one new sessions start on' : 'a current revision'
364
+ return `kagent Agent ${agentText(k.agent)}’s template for ${which}`
365
+ }
366
+ return k?.kind === 'sandbox' ? 'A kagent sandbox’s template' : undefined
367
+ }
368
+
369
+ /**
370
+ * An actor as a compact list shows it: a kagent session by its short id, with its Agent's name (or that
371
+ * it is a sandbox) beside it; anything else by its name.
372
+ */
373
+ export function compactActorLabel(a: { name: string; kagent?: KagentActor }): { name: string; agent?: string } {
374
+ if (!a.kagent) return { name: a.name }
375
+ const k = a.kagent
376
+ const agent = k.kind === 'agentSession' ? `Agent ${k.agent.name}` : k.kind === 'sandbox' ? 'kagent sandbox' : undefined
377
+ return { name: `session ${shortSessionId(k.sessionId)}`, agent }
378
+ }
379
+
380
+ /**
381
+ * Why Radar couldn't read the kagent Agents in a namespace, from the Agents' coverage: a few words for
382
+ * "Radar couldn't read kagent Agents in <ns> (…)".
383
+ */
384
+ export function kagentUnreadWhy(cov: SubstratePoolsCoverage | undefined, namespace: string): string {
385
+ if (!cov) return 'not read'
386
+ if (cov.state === 'denied' || cov.deniedNamespaces?.includes(namespace)) return 'you can’t list them'
387
+ if (cov.state === 'syncing') return 'still syncing'
388
+ if (cov.state === 'uncached' || cov.uncachedNamespaces?.includes(namespace)) return 'Radar doesn’t collect them there'
389
+ if (cov.state === 'error') return 'the read failed'
390
+ return 'not read'
391
+ }
392
+
393
+ /** What a kagent-filtered list can't say where the Agents weren't read, in a sentence; undefined when they all were. */
394
+ export function kagentUnreadText(unread: string[] | undefined, cov: SubstratePoolsCoverage | undefined): string | undefined {
395
+ if (!unread?.length) return undefined
396
+ const where = unread.map((ns) => `${ns} (${kagentUnreadWhy(cov, ns)})`).join(', ')
397
+ return `Radar couldn’t read kagent Agents in ${where}, so a session there could be any Agent’s: counts of an Agent’s sessions are lower bounds, and a session not tied to an Agent may belong to one.`
398
+ }
399
+
400
+ /** A short label for a table cell: the Agent, a sandbox, or why neither. */
401
+ export function kagentCellText(k: KagentAttribution): string {
402
+ if (k.kind === 'agentSession') return agentText(k.agent)
403
+ if (k.kind === 'sandbox') return 'kagent sandbox'
404
+ switch (k.reason) {
405
+ case 'earlierRevision':
406
+ return 'earlier revision'
407
+ case 'agentNotReadable':
408
+ return 'Agent unknown'
409
+ case 'ambiguous':
410
+ return 'ambiguous'
411
+ default:
412
+ return 'no Agent'
413
+ }
414
+ }
415
+
416
+ /** `kubectl ate revert actor`, which returns a crashed actor to suspended at its newest stored snapshot. */
417
+ export function revertCommand(ref: SubstrateRef): string {
418
+ return `kubectl ate revert actor ${ref.name} -a ${ref.atespace}`
419
+ }
420
+
421
+ /** `kubectl ate get actor-template … -o yaml`: the template's full spec. */
422
+ export function templateYamlCommand(ref: SubstrateRef): string {
423
+ return `kubectl ate get actor-template ${ref.name} -a ${ref.atespace} -o yaml`
424
+ }
425
+
426
+ export function refText(ref: SubstrateRef): string {
427
+ return `${ref.atespace} / ${ref.name}`
428
+ }
429
+
430
+ const ATTENTION_TONE: Record<SubstrateAttention['severity'], Exclude<StatusTone, 'healthy'>> = {
431
+ critical: 'unhealthy',
432
+ alert: 'alert',
433
+ warning: 'degraded',
434
+ // Expected and still within its budget, such as a drain before its Pod's deadline.
435
+ info: 'neutral',
436
+ }
437
+
438
+ /** A row's tone, by the house's four steps: critical red, alert orange, warning amber, info blue. */
439
+ export function attentionTone(a: Pick<SubstrateAttention, 'severity'>): Exclude<StatusTone, 'healthy'> {
440
+ return ATTENTION_TONE[a.severity] ?? 'degraded'
441
+ }
442
+
443
+ /** The worst tone among rows, or undefined when there are none. */
444
+ export function worstAttentionTone(rows: Pick<SubstrateAttention, 'severity'>[]): Exclude<StatusTone, 'healthy'> | undefined {
445
+ const order: SubstrateAttention['severity'][] = ['critical', 'alert', 'warning', 'info']
446
+ const worst = order.find((s) => rows.some((r) => r.severity === s))
447
+ return worst ? ATTENTION_TONE[worst] : undefined
448
+ }
449
+
450
+ export type AttentionArea = 'actors' | 'templates' | 'workers' | 'pools' | 'nodes'
451
+
452
+ const RULE_AREA: Record<SubstrateAttention['rule'], AttentionArea> = {
453
+ crashedActors: 'actors',
454
+ stuckTransition: 'actors',
455
+ uploadOverdue: 'actors',
456
+ goldenSnapshotFailed: 'templates',
457
+ noMatchingPool: 'templates',
458
+ missingTemplate: 'templates',
459
+ workerUnavailable: 'workers',
460
+ workerDraining: 'workers',
461
+ workerRestarting: 'workers',
462
+ poolShort: 'pools',
463
+ poolFull: 'pools',
464
+ poolNoRoom: 'pools',
465
+ nodeUploadsOverdue: 'nodes',
466
+ }
467
+
468
+ /** Which screen a needs-attention row belongs to. */
469
+ export function attentionArea(a: Pick<SubstrateAttention, 'rule'>): AttentionArea {
470
+ return RULE_AREA[a.rule] ?? 'actors'
471
+ }
472
+
473
+ /** The areas whose rules need Substrate's API, so a zero there is unknown while it is not read. */
474
+ export const API_AREAS: ReadonlySet<AttentionArea> = new Set(['actors', 'templates', 'workers'])
475
+
476
+ /** The atespace/name of a filter value for the /actors `template` parameter. */
477
+ export function templateFilterValue(ref: SubstrateRef): string {
478
+ return `${ref.atespace}/${ref.name}`
479
+ }
480
+
481
+ /** A subject's words for a link: "Actor research / lit-review-0193", "the 14 actors". */
482
+ export function subjectLabel(s: SubstrateSubject, count?: number): string {
483
+ switch (s.kind) {
484
+ case 'Actors':
485
+ return count !== undefined ? `Show the ${count === 1 ? 'actor' : `${count} actors`}` : 'Show the actors'
486
+ case 'Actor':
487
+ case 'ActorTemplate':
488
+ return `${s.atespace ?? ''} / ${s.name ?? ''}`
489
+ case 'WorkerPool':
490
+ case 'Pod':
491
+ case 'Worker':
492
+ case 'Agent':
493
+ return `${s.namespace ?? ''} / ${s.name ?? ''}`
494
+ default:
495
+ return s.name ?? ''
496
+ }
497
+ }
498
+
499
+ export const SUBJECT_KIND_LABEL: Record<SubstrateSubject['kind'], string> = {
500
+ Actor: 'Actor',
501
+ ActorTemplate: 'Template',
502
+ Worker: 'Worker',
503
+ WorkerPool: 'Pool',
504
+ Node: 'Node',
505
+ Pod: 'Pod',
506
+ Actors: 'Actors',
507
+ Agent: 'Agent',
508
+ }
509
+
510
+ /** Coverage that is not a full read: counts over it are lower bounds, and its empty list proves nothing. */
511
+ export function coverageInPart(cov: SubstrateCoverage | undefined): boolean {
512
+ return !cov || cov.state !== 'full'
513
+ }
514
+
515
+ /** A coverage that could not be read at all. */
516
+ export function coverageUnread(cov: SubstrateCoverage | undefined): boolean {
517
+ return !cov || cov.state === 'denied' || cov.state === 'failed'
518
+ }
519
+
520
+ /** Why a kind was not read in full, in a clause: "Substrate denied atespaces a, b". */
521
+ export function coverageReason(cov: SubstrateCoverage | undefined, noun: string): string {
522
+ if (!cov) return `${noun} were not read`
523
+ if (cov.state === 'partial') {
524
+ if (cov.code === 'incomplete' && cov.message) return cov.message
525
+ if (cov.code === 'capExceeded' && cov.cap === undefined && cov.count === undefined && cov.message) return cov.message
526
+ if (cov.code === 'capExceeded') return `Radar read the first ${cov.cap ?? cov.count ?? 'few'} ${noun} and stopped there`
527
+ if (cov.code === 'scoped') return `Substrate would not list atespaces, so Radar read only ${cov.readAtespaces?.length ? cov.readAtespaces.join(', ') : 'the atespaces set in the connection'}; others are unknown`
528
+ if (cov.unreadAtespaces?.length) return `Radar ran out of time before reading ${cov.unreadAtespaces.length === 1 ? 'atespace' : 'atespaces'} ${cov.unreadAtespaces.join(', ')}`
529
+ if (cov.deniedAtespaces?.length) return `Substrate denied ${cov.deniedAtespaces.length === 1 ? 'atespace' : 'atespaces'} ${cov.deniedAtespaces.join(', ')}`
530
+ return `some ${noun} could not be read`
531
+ }
532
+ if (cov.state === 'denied') return `Substrate denied permission to list ${noun}${cov.message ? `: ${cov.message}` : ''}`
533
+ if (cov.state === 'failed') return `${noun} could not be read${cov.message ? `: ${cov.message}` : ''}`
534
+ return ''
535
+ }
536
+
537
+ /** What each API tier state means for the reader, and what to do about it. */
538
+ export interface TierReading {
539
+ title: string
540
+ detail: string
541
+ nextStep?: string
542
+ /** A command that checks or does the next step, shown as a copyable chip. */
543
+ command?: string
544
+ tone: StatusTone
545
+ }
546
+
547
+ const CODE_READING: Partial<Record<SubstrateCode, Omit<TierReading, 'detail'> & { detail?: string }>> = {
548
+ notConfigured: { title: 'Not connected', tone: 'unknown', nextStep: 'Choose who Radar reads Substrate as, in Settings → Agent Substrate.' },
549
+ targetChanged: {
550
+ title: 'Saved for another cluster',
551
+ tone: 'unknown',
552
+ detail: 'The connection was saved while this context pointed at another cluster, so Radar does not use it here.',
553
+ nextStep: 'Review it in Settings → Agent Substrate.',
554
+ },
555
+ sharedRadar: {
556
+ title: 'Needs sign-in',
557
+ tone: 'unknown',
558
+ detail: 'This Radar is shared without sign-in, so it can’t tell who is asking and doesn’t read Substrate’s API.',
559
+ nextStep: 'Turn on sign-in for this Radar; then each person sees what their own Kubernetes access allows.',
560
+ },
561
+ apiDisabled: {
562
+ title: 'Turned off for this Radar',
563
+ tone: 'unknown',
564
+ detail: 'The operator turned off reading Substrate’s API here.',
565
+ nextStep: 'Ask your operator to set substrate.api.enabled in Radar’s Helm values.',
566
+ },
567
+ mintDenied: {
568
+ title: 'Couldn’t create the shared identity’s token',
569
+ tone: 'unhealthy',
570
+ detail: 'Radar needs Kubernetes credentials that can create a token for ate-system/ate-client.',
571
+ nextStep: 'Check your Kubernetes credentials. If Kubernetes denied the token request, ask a cluster admin for create on serviceaccounts/token for ate-client in ate-system.',
572
+ command: 'kubectl auth can-i create serviceaccounts/ate-client --subresource=token -n ate-system',
573
+ },
574
+ userTokenRequired: { title: 'Sign-in token required', tone: 'unhealthy' },
575
+ notInstalled: { title: 'API server not found', tone: 'unknown', nextStep: 'Check that Substrate’s API server runs as Service ate-system/api, or set its endpoint in Settings → Agent Substrate, under Advanced.' },
576
+ tls: { title: 'TLS check failed', tone: 'unhealthy', nextStep: 'Check the CA file and server name in Settings → Agent Substrate, under Advanced, or that the cluster’s trust bundle for Substrate exists.' },
577
+ unreachable: { title: 'API server unreachable', tone: 'unhealthy', nextStep: 'Check that the API server’s Pods are running, then retry; with a custom endpoint, check it is reachable from this machine.' },
578
+ unauthenticated: { title: 'Substrate rejected the identity', tone: 'unhealthy', nextStep: 'Check that the token is current, or choose another identity.' },
579
+ denied: { title: 'Substrate denied the read', tone: 'unhealthy', nextStep: 'Ask a Substrate owner to grant this identity the viewer role, or choose another identity.' },
580
+ settingsFile: { title: 'Radar couldn’t read its saved connection', tone: 'unhealthy', nextStep: 'Check that ~/.radar/substrate.json is readable, then choose the identity again.' },
581
+ invalidSettings: { title: 'The connection settings are invalid', tone: 'unhealthy', nextStep: 'Check the token file and CA file paths, then save again.' },
582
+ contextChanged: { title: 'The connection changed during the read', tone: 'unknown', nextStep: 'Retry: Radar reads again through the new connection.' },
583
+ failed: { title: 'Reading Substrate failed', tone: 'unhealthy', nextStep: 'Retry; if it keeps failing, read the API server’s log.' },
584
+ }
585
+
586
+ /**
587
+ * The same codes for a signed-in person on an in-cluster Radar or Radar Hub,
588
+ * who reads as ate-client with nothing to configure: no Advanced fields, no
589
+ * other identity to choose, no "this machine". Steps name what they can ask
590
+ * for instead.
591
+ */
592
+ const NO_FORM_READING: Partial<Record<SubstrateCode, Omit<TierReading, 'detail'> & { detail?: string; withReason?: boolean }>> = {
593
+ notInstalled: {
594
+ title: 'Substrate isn’t installed here',
595
+ tone: 'unknown',
596
+ detail: 'Substrate’s shared client identity (ate-system/ate-client) doesn’t exist here.',
597
+ nextStep: 'Check that Substrate is installed in ate-system.',
598
+ command: 'kubectl -n ate-system get sa ate-client',
599
+ },
600
+ tls: {
601
+ title: 'Radar couldn’t verify Substrate’s API server',
602
+ tone: 'unhealthy',
603
+ detail: 'Radar couldn’t verify {endpoint} from inside the cluster.',
604
+ withReason: true,
605
+ nextStep: 'Ask your operator to check the certificate Radar trusts for it: the cluster’s trust bundle for Substrate, or the substrate.api.caConfigMap and serverName Helm values.',
606
+ },
607
+ unreachable: {
608
+ title: 'Radar couldn’t reach Substrate’s API server',
609
+ tone: 'unhealthy',
610
+ detail: 'Radar couldn’t reach {endpoint} from inside the cluster.',
611
+ withReason: true,
612
+ nextStep: 'Check that Substrate’s API server Pods are running.',
613
+ command: 'kubectl -n ate-system get pods',
614
+ },
615
+ unauthenticated: {
616
+ title: 'Substrate didn’t accept the shared identity’s token',
617
+ tone: 'unhealthy',
618
+ detail: 'Substrate didn’t accept the token Radar created for ate-system/ate-client: it checks who issued a token and for which audience, before any role.',
619
+ withReason: true,
620
+ nextStep: 'Ask a Substrate operator to check that its API server trusts this cluster’s ServiceAccount tokens for the audience api.ate-system.svc. A role grant won’t fix this.',
621
+ },
622
+ denied: {
623
+ title: 'Substrate refused the shared identity',
624
+ tone: 'unhealthy',
625
+ detail: 'Substrate denied ate-system/ate-client the read: it isn’t granted in this install.',
626
+ withReason: true,
627
+ nextStep: 'Ask a Substrate operator to grant it the viewer role; until then, this Radar can’t read Substrate as it stands.',
628
+ },
629
+ }
630
+
631
+ /**
632
+ * The steps that send the reader to Settings → Agent Substrate, as they read
633
+ * inside it: the form is on the same page. notConfigured's detail already says
634
+ * what to do there.
635
+ */
636
+ const IN_SETTINGS_STEP: Partial<Record<SubstrateCode, string | undefined>> = {
637
+ notConfigured: undefined,
638
+ targetChanged: 'Review it below, then save it for this cluster.',
639
+ notInstalled: 'Check that Substrate’s API server runs as Service ate-system/api, or set its endpoint under Advanced.',
640
+ tls: 'Check the CA file and server name under Advanced, or that the cluster’s trust bundle for Substrate exists.',
641
+ }
642
+
643
+ export function tierReading(tier: SubstrateAPITier, { inSettings = false }: { inSettings?: boolean } = {}): TierReading {
644
+ if (tier.state === 'connected') return { title: 'Connected', detail: '', tone: 'healthy' }
645
+ if (tier.state === 'connecting') return { title: 'Connecting', detail: 'The connection is saved; Radar is reading Substrate’s API for the first time.', tone: 'unknown' }
646
+ const noForm = tier.code ? tier.identity?.mode === 'sharedAsCaller' && NO_FORM_READING[tier.code] : undefined
647
+ if (noForm) {
648
+ // The plain state is Radar's; the server's own words follow as its reason.
649
+ const { withReason, ...reading } = noForm
650
+ const own = noForm.detail?.replace('{endpoint}', tier.endpoint ?? 'Substrate’s API server')
651
+ return { ...reading, detail: withReason && tier.reason ? `${own} ${tier.reason}` : own ?? tier.reason ?? '' }
652
+ }
653
+ const code = tier.code ?? (tier.state === 'notConfigured' ? 'notConfigured' : undefined)
654
+ const known = code ? CODE_READING[code] : undefined
655
+ const detail = tier.reason ?? known?.detail ?? 'Radar has not read Substrate’s API.'
656
+ if (known) {
657
+ const nextStep = inSettings && code && code in IN_SETTINGS_STEP ? IN_SETTINGS_STEP[code] : known.nextStep
658
+ return { ...known, nextStep, detail: known.detail && !tier.reason ? known.detail : detail }
659
+ }
660
+ if (tier.state === 'notConfigured') return { title: 'Not connected', tone: 'unknown', detail, nextStep: inSettings ? undefined : CODE_READING.notConfigured!.nextStep }
661
+ return { title: 'Not read', tone: 'unknown', detail }
662
+ }
663
+
664
+ /** The shared identity in words: who Substrate sees, and that it is not the user. */
665
+ export function sharedIdentityText(principal: string): string {
666
+ return `${principal}, the identity kubectl ate uses when no --token-file is given. It is not you: Substrate shows Radar what that identity may see.`
667
+ }
668
+
669
+ /** Countable bar segments: one per actor while it is small enough to count, then proportional. */
670
+ export const COUNTABLE_LIMIT = 80
671
+
672
+ export interface BarSegment {
673
+ state: SubstrateActorState
674
+ count: number
675
+ /** Share of the bar, 0–1. */
676
+ share: number
677
+ }
678
+
679
+ export function stateBarSegments(counts: SubstrateStateCounts): { segments: BarSegment[]; countable: boolean } {
680
+ const segments = ACTOR_STATE_ORDER.map((state) => ({ state, count: counts.byState[state] ?? 0 }))
681
+ .filter((s) => s.count > 0)
682
+ .map((s) => ({ ...s, share: counts.total > 0 ? s.count / counts.total : 0 }))
683
+ return { segments, countable: counts.total > 0 && counts.total <= COUNTABLE_LIMIT }
684
+ }
685
+
686
+ /** "2,104"; undefined (not read) never renders as 0. */
687
+ export function countText(n: number | undefined, unknown = 'unknown'): string {
688
+ return n === undefined ? unknown : n.toLocaleString('en-US')
689
+ }
690
+
691
+ /** Bytes as Kubernetes writes them: 2Gi, 512Mi. */
692
+ export function bytesText(bytes: number): string {
693
+ const units = ['', 'Ki', 'Mi', 'Gi', 'Ti']
694
+ let v = bytes
695
+ let i = 0
696
+ while (v >= 1024 && i < units.length - 1) {
697
+ v /= 1024
698
+ i++
699
+ }
700
+ const rounded = Number.isInteger(v) ? String(v) : v.toFixed(1).replace(/\.0$/, '')
701
+ return `${rounded}${units[i]}`
702
+ }
703
+
704
+ /** Millicores as Kubernetes writes them: 2, 500m. */
705
+ export function cpuText(milli: number): string {
706
+ return milli % 1000 === 0 ? String(milli / 1000) : `${milli}m`
707
+ }
708
+
709
+ export interface GoldenReading {
710
+ label: string
711
+ severity: BadgeSeverity
712
+ /** What the state means, in a sentence. */
713
+ meaning: string
714
+ }
715
+
716
+ /**
717
+ * A template's golden snapshot as the reader should take it. A build no pool
718
+ * can run never finishes (Substrate retries it), so it reads as blocked.
719
+ */
720
+ export function goldenReading(t: Pick<SubstrateTemplateRow, 'golden' | 'matchingPools' | 'matchingPoolsComplete' | 'kagent'>): GoldenReading {
721
+ switch (t.golden.state) {
722
+ case 'ready':
723
+ return { label: 'Ready', severity: 'success', meaning: 'New actors start from the golden snapshot.' }
724
+ case 'failed':
725
+ if (t.kagent?.kind === 'agentSession') {
726
+ return { label: 'Failed', severity: 'warning', meaning: `New actors without a seed tag start from a cold boot. ${kagentGoldenStep(t.kagent.agent, t.golden.cause === 'memoryLimit')}` }
727
+ }
728
+ // New actors boot cold; nothing is lost: the warning of its Needs attention row.
729
+ return { label: 'Failed', severity: 'warning', meaning: 'The build failed and Substrate does not retry it: new actors not seeded from a tag start from a cold boot, not a prepared snapshot. Templates can’t be edited: recreate it to build again.' }
730
+ case 'disabled':
731
+ return { label: 'Disabled', severity: 'neutral', meaning: 'The template turns golden snapshots off: every new actor boots cold.' }
732
+ }
733
+ // At risk, not lost: the alert of its Needs attention row.
734
+ if (t.golden.blocked === 'noMatchingPool') {
735
+ return { label: 'Can’t build: no pool can run it', severity: 'alert', meaning: 'The build runs as an actor on a worker, and no pool’s labels match the template’s worker selector, so it retries without end. New actors can’t run either.' }
736
+ }
737
+ return { label: 'Building', severity: 'warning', meaning: 'Substrate is warming the template up; new actors boot cold until it is ready.' }
738
+ }
739
+
740
+ export interface PoolReading {
741
+ label: string
742
+ severity: BadgeSeverity
743
+ meaning: string
744
+ controllerFinding?: boolean
745
+ /** Kubernetes' own phase for the WorkerPool ("Scaling"), shown beside as its cause or context. */
746
+ kubernetes?: string
747
+ }
748
+
749
+ /**
750
+ * One reading of a pool, the same in its list and on its page: Substrate's
751
+ * capacity verdict with the count behind it, and Kubernetes' phase as context.
752
+ */
753
+ export function poolReading(p: Pick<SubstratePoolRow, 'capacity' | 'lacking' | 'placement' | 'kubernetes'>, finding?: SubstrateAttention): PoolReading {
754
+ const reading = poolCapacityReading(p)
755
+ const k = p.kubernetes
756
+ if (k?.health === 'unhealthy' || (k?.health === 'degraded' && k.healthDetail && finding?.severity !== 'critical' && finding?.severity !== 'alert')) {
757
+ const label = k.healthReason === 'SandboxConfigNotFound' ? 'Sandbox configuration missing'
758
+ : k.healthReason === 'Provisioning stalled' ? 'Provisioning stalled' : 'Sandbox configuration unresolved'
759
+ return { ...reading, label, severity: k.health === 'unhealthy' ? 'error' : 'warning', controllerFinding: true }
760
+ }
761
+ if (finding) return { ...reading, severity: toneSeverity(attentionTone(finding)) }
762
+ return reading
763
+ }
764
+
765
+ function poolCapacityReading(p: Pick<SubstratePoolRow, 'capacity' | 'lacking' | 'placement' | 'kubernetes'>): PoolReading {
766
+ const kubernetes = p.kubernetes?.healthReason || undefined
767
+ const desired = p.kubernetes?.desired
768
+ switch (p.capacity) {
769
+ case 'short': {
770
+ const observed = p.placement?.complete ? p.placement.workers.active : undefined
771
+ const have = observed ?? p.kubernetes?.pods?.ready ?? p.kubernetes?.reportedReady
772
+ const count = have === undefined ? '' : ` · ${have} of ${desired ?? '?'} ${observed === undefined ? 'Pods ready' : 'active'}`
773
+ return {
774
+ label: `Short of workers${count}`,
775
+ severity: 'warning',
776
+ meaning: 'Fewer workers take actors than the pool wants. New and resuming actors may wait or fail to start.',
777
+ kubernetes,
778
+ }
779
+ }
780
+ // Slots are utilization, not health: only a pool that can place nothing new blocks work, and only that gets emphasis.
781
+ case 'full':
782
+ return { label: 'No free actor slots', severity: 'warning', meaning: 'No active worker has a free actor slot, so Substrate places no more actors in this pool. New actors whose selectors match only this pool cannot start.', kubernetes }
783
+ // As blocking as a full pool: the warning of its Needs attention row (poolNoRoom).
784
+ case 'noRoom': {
785
+ const what = lackingText(p.lacking)
786
+ return {
787
+ label: `No ${what} left for an actor`,
788
+ severity: 'warning',
789
+ meaning: `Active workers have free actor slots, but none has the ${what} left for an actor of any template that can run on this pool, so new and resuming actors wait for a worker.`,
790
+ kubernetes,
791
+ }
792
+ }
793
+ case 'free':
794
+ return { label: 'Free actor slots', severity: p.placement?.complete && p.kubernetes?.health === 'healthy' ? 'success' : 'neutral', meaning: 'At least one active worker has a free actor slot. Whether an actor fits depends on its size and its snapshot’s restore constraints.', kubernetes }
795
+ case undefined:
796
+ return { label: 'Unknown', severity: 'neutral', meaning: 'Neither Kubernetes nor Substrate was read well enough to say.', kubernetes }
797
+ }
798
+ }
799
+
800
+ /** What a pool's free slots lack, in words: "CPU", "memory", "CPU or memory". */
801
+ export function lackingText(lacking: SubstrateLacking | undefined): string {
802
+ switch (lacking) {
803
+ case 'cpu':
804
+ return 'CPU'
805
+ case 'memory':
806
+ return 'memory'
807
+ }
808
+ return 'CPU or memory'
809
+ }
810
+
811
+ /**
812
+ * Why a pool's Substrate read failed, in words. Only notFound proves the pool
813
+ * is gone; incomplete means Radar read too little to tell either way.
814
+ */
815
+ export function poolReadFailure(error: unknown, namespace: string): string {
816
+ const code = substrateErrorCode(error)
817
+ const message = error instanceof Error ? error.message : undefined
818
+ if (code === 'notFound') return 'There is no WorkerPool by this name, and Substrate has no workers for one.'
819
+ if (code === 'incomplete') return `Radar can’t tell whether this pool exists: it read too little of the WorkerPools or of Substrate’s workers${message ? ` (${message})` : ''}.`
820
+ if (code === 'denied' && isForbiddenError(error)) return `Reading this WorkerPool requires get on workerpools.ate.dev in namespace ${namespace}.`
821
+ if (code === 'mintDenied' || code === 'userTokenRequired' || code === 'denied') {
822
+ const { detail, nextStep } = tierReading({ state: 'failed', code, reason: message })
823
+ return [detail, nextStep].filter(Boolean).join(' ')
824
+ }
825
+ return `Radar couldn’t read the pool from Substrate’s API${message ? `: ${message}` : ''}.`
826
+ }
827
+
828
+ /** A worker's memory-limit kill of the actor's sandbox, in words: "the worker killed its sandbox over its memory limit of 2Gi (it used 2Gi)". */
829
+ export function memoryKillText(kill: { limitBytes: number; usageBytes?: number }): string {
830
+ return `the worker killed its sandbox over its memory limit of ${bytesText(kill.limitBytes)}${kill.usageBytes ? ` (it used ${bytesText(kill.usageBytes)})` : ''}`
831
+ }
832
+
833
+ /**
834
+ * The timing that ties a kill to the crash, the evidence the server's
835
+ * `current` rests on: "2m before this crash". Undefined unless the kill is
836
+ * tied to the present crash and both times are known.
837
+ */
838
+ export function killTie(kill: { time?: string; current: boolean }, crashTime: string | undefined): string | undefined {
839
+ return kill.current ? killTiming(kill, crashTime) : undefined
840
+ }
841
+
842
+ export function killTiming(kill: { time?: string }, crashTime: string | undefined): string | undefined {
843
+ if (!kill.time || !crashTime) return undefined
844
+ const gap = Date.parse(crashTime) - Date.parse(kill.time)
845
+ if (!Number.isFinite(gap) || gap < 0) return undefined
846
+ return `${formatDuration(gap)} before this crash`
847
+ }
848
+
849
+ /** A kill line's label in the log, qualified by whether Radar can tie it to the crash. */
850
+ export function killLineLabel(kill: { time?: string; current: boolean }, crashTime: string | undefined): string {
851
+ if (!kill.current) return 'memory-limit kill attempt'
852
+ const tie = killTie(kill, crashTime)
853
+ return tie ? `memory-limit kill · ${tie}` : 'memory-limit kill'
854
+ }
855
+
856
+ /** Local date and time to the second, for a tooltip beside a relative time. */
857
+ export function localTime(iso: string): string {
858
+ return new Date(iso).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' })
859
+ }
860
+
861
+ /** "12m ago", or "in 12m" for a time ahead; a timestamp Radar can't parse is returned as is. */
862
+ export function relativeTime(iso: string, now = Date.now()): string {
863
+ const t = Date.parse(iso)
864
+ if (!Number.isFinite(t)) return iso
865
+ const s = Math.round((t - now) / 1000)
866
+ if (s > 60) return `in ${formatDuration(s * 1000)}`
867
+ if (s > -5) return 'just now'
868
+ return `${formatDuration(-s * 1000)} ago`
869
+ }
870
+
871
+ /** A container line newer than this says the actor is still running. */
872
+ export const RECENT_OUTPUT_MS = 5 * 60_000
873
+
874
+ /**
875
+ * Whether the actor's own output says it is still running, for an actor on a
876
+ * worker Substrate no longer trusts: the newest container line read. Undefined
877
+ * when the log was not read.
878
+ */
879
+ export function servingEvidence(lines: { kind: string; time?: string }[] | undefined, now = Date.now()): { recent: boolean; at?: string } | undefined {
880
+ if (!lines) return undefined
881
+ let newest: number | undefined
882
+ let at: string | undefined
883
+ for (const l of lines) {
884
+ if (l.kind !== 'container' || !l.time) continue
885
+ const t = Date.parse(l.time)
886
+ if (Number.isFinite(t) && (newest === undefined || t > newest)) {
887
+ newest = t
888
+ at = l.time
889
+ }
890
+ }
891
+ return { recent: newest !== undefined && now - newest < RECENT_OUTPUT_MS, at }
892
+ }
893
+
894
+ /**
895
+ * A reading's first sentence, shown in full, and the rest, which waits for
896
+ * Details: a row never shows a sentence cut off.
897
+ */
898
+ export function splitReading(reading: string): [string, string | undefined] {
899
+ const m = /^(.+?[.!?])\s+(?=[A-Z0-9])/.exec(reading)
900
+ if (!m) return [reading, undefined]
901
+ const rest = reading.slice(m[0].length).trim()
902
+ return [m[1], rest || undefined]
903
+ }
904
+
905
+ /**
906
+ * Codes that end a detail read for good: the object is gone, access was taken
907
+ * away, or the connection no longer stands. A page shows the failure, not the
908
+ * last answer it kept; any other refresh failure keeps that answer, marked stale.
909
+ */
910
+ const DEFINITIVE_CODES = new Set<SubstrateCode>(['notFound', 'denied', 'mintDenied', 'userTokenRequired', 'unauthenticated', 'notConfigured', 'sharedRadar', 'apiDisabled', 'targetChanged'])
911
+
912
+ export function definitiveFailure(code: SubstrateCode | undefined): boolean {
913
+ return !!code && DEFINITIVE_CODES.has(code)
914
+ }
915
+
916
+ function sentences(text: string): string[] {
917
+ return text.split(/(?<=[.!?])\s+(?=[A-Z0-9])/).map((x) => x.trim()).filter(Boolean)
918
+ }
919
+
920
+ const norm = (x: string) => x.toLowerCase().replace(/[.!?:;,]+$/g, '').replace(/\s+/g, ' ').trim()
921
+
922
+ const STOP = new Set(['a', 'an', 'the', 'on', 'of', 'to', 'it', 'its', 'is', 'and', 'or', 'in', 'for', 'only', 'also', 'so'])
923
+ const words = (x: string) => norm(x).split(/[^a-z0-9’']+/).filter((w) => w && !STOP.has(w))
924
+
925
+ /**
926
+ * A reading without the sentences its next step already says, so a banner
927
+ * states each fact once: where the action is. A sentence counts as said when
928
+ * nearly all of its words are in the step, however the step words it.
929
+ */
930
+ export function withoutRepeats(reading: string | undefined, nextStep: string | undefined): string | undefined {
931
+ if (!reading || !nextStep) return reading
932
+ const step = new Set(words(nextStep))
933
+ const said = (x: string) => {
934
+ const w = words(x)
935
+ return w.length >= 3 && w.filter((t) => step.has(t)).length / w.length >= 0.85
936
+ }
937
+ const kept = sentences(reading).filter((x) => !said(x))
938
+ return kept.length ? kept.join(' ') : undefined
939
+ }
940
+
941
+ /** The tone of an actor's cell in the placement grid: its badge's, worker impact first. */
942
+ export function placementTone(state: SubstrateActorState, impact: SubstrateWorkerImpact['kind'] | undefined): StatusTone {
943
+ return impact && state !== 'crashed' ? workerImpactTone(impact) : actorStateTone(state)
944
+ }
945
+
946
+ const WORKER_STATE_LABEL: Record<SubstrateWorkerRow['state'], { label: string; severity: BadgeSeverity }> = {
947
+ active: { label: 'Active', severity: 'success' },
948
+ draining: { label: 'Draining', severity: 'info' },
949
+ // At risk, nothing lost yet: the tone of its Needs attention row.
950
+ unavailable: { label: 'Unavailable', severity: 'alert' },
951
+ unknown: { label: 'Unknown', severity: 'neutral' },
952
+ }
953
+
954
+ /**
955
+ * A worker's chip. A registration ahead of what Substrate reconciled is part
956
+ * of it, and lost sandboxes turn it red: a green "Active" over lost actors
957
+ * would say the opposite of the actors' own rows. The chip stays one line; the
958
+ * screens say how many were lost beside it (workerState.lost).
959
+ */
960
+ export function workerStateReading(w: Pick<SubstrateWorkerRow, 'state' | 'workerState' | 'attentionSeverity'>): { label: string; severity: BadgeSeverity; title: string } {
961
+ const base = WORKER_STATE_LABEL[w.state]
962
+ const ws = w.workerState
963
+ const title = ws?.reading ?? 'Substrate’s state for the worker. Only active workers take new actors.'
964
+ const label = ws?.kind === 'reconciling' ? `${base.label} · reconciling` : base.label
965
+ const finding = w.attentionSeverity
966
+ const severity = finding === 'info' ? 'info' : finding ? toneSeverity(attentionTone({ severity: finding }))
967
+ : ws?.kind === 'reconciling' ? ws.lost ? 'error' : w.state === 'unavailable' ? 'alert' : 'warning'
968
+ : base.severity
969
+ return { label, severity, title }
970
+ }
971
+
972
+ /** What Kubernetes says about a worker's Pod, in one phrase; terminating comes first, since a Ready Pod being deleted is not counted ready. */
973
+ export function workerPodText(w: Pick<SubstrateWorkerRow, 'podReady' | 'podTerminating'>): string | undefined {
974
+ if (w.podTerminating) return 'Pod terminating'
975
+ if (w.podReady === undefined) return undefined
976
+ return w.podReady ? 'Pod ready' : 'Pod not ready'
977
+ }
978
+
979
+ /** A Substrate reason code Kubernetes-style messages lead with ("GoldenActorCrashed: …"): the words after it say the same, plainly. */
980
+ export function withoutReasonCode(message: string): string {
981
+ return message.replace(/^[A-Z][A-Za-z]+:\s+/, '')
982
+ }
983
+
984
+ /** Ready worker Pods: Radar's own count when it holds the Pods, else the WorkerPool's status. */
985
+ export function poolReadyPods(k: Pick<SubstrateK8sPool, 'reportedReady' | 'pods'>): number | undefined {
986
+ return k.pods?.ready ?? k.reportedReady
987
+ }
988
+
989
+ // Radar's stuck rule (pkg/substrate StuckAfter): a transition held longer than this is stuck.
990
+ export const STUCK_AFTER_MS = 5 * 60_000
991
+
992
+ /** A resume, suspend, revert or delete that has held past Substrate's stuck threshold. */
993
+ export function stuckInTransition(state: SubstrateActorState, updateTime: string | undefined, now = Date.now()): boolean {
994
+ if (!IN_PROGRESS_STATES.includes(state) || !updateTime) return false
995
+ const t = Date.parse(updateTime)
996
+ return Number.isFinite(t) && now - t > STUCK_AFTER_MS
997
+ }