@skyhook-io/radar-app 1.21.5 → 1.21.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +1 -1
  2. package/package.json +7 -7
  3. package/src/App.tsx +19 -1
  4. package/src/RadarApp.tsx +8 -2
  5. package/src/api/client.discoverMetrics.test.tsx +69 -0
  6. package/src/api/client.issueCorrelation.test.tsx +244 -0
  7. package/src/api/client.issueRowChanges.test.tsx +129 -0
  8. package/src/api/client.pendingOwnership.test.tsx +197 -0
  9. package/src/api/client.prometheusStatus.test.ts +4 -0
  10. package/src/api/client.restartError.test.ts +36 -1
  11. package/src/api/client.stopWorkflow.test.tsx +133 -0
  12. package/src/api/client.submitWorkflowTemplate.test.tsx +127 -0
  13. package/src/api/client.ts +572 -111
  14. package/src/api/connectionBinding.test.tsx +3 -1
  15. package/src/api/connectionBinding.ts +14 -2
  16. package/src/api/gitOpsPermissions.render.test.tsx +155 -0
  17. package/src/api/gitOpsPermissions.test.ts +90 -0
  18. package/src/api/gitOpsPermissions.ts +51 -0
  19. package/src/api/httpErrors.test.ts +30 -1
  20. package/src/api/httpErrors.ts +17 -0
  21. package/src/api/openobserveSetup.ts +85 -0
  22. package/src/api/podDebug.test.tsx +137 -0
  23. package/src/api/podDebug.ts +82 -0
  24. package/src/api/prometheusCharts.test.ts +23 -0
  25. package/src/api/prometheusCharts.ts +25 -0
  26. package/src/api/radarFeatures.render.test.tsx +43 -2
  27. package/src/api/radarFeatures.test.ts +18 -1
  28. package/src/api/radarFeatures.ts +17 -4
  29. package/src/api/reviewedActionMutation.ts +9 -2
  30. package/src/api/workloadMetrics.ts +2 -0
  31. package/src/components/applications/ApplicationsView.openResource.test.tsx +137 -11
  32. package/src/components/applications/ApplicationsView.tsx +56 -31
  33. package/src/components/cnpg/host.test.tsx +1 -1
  34. package/src/components/cnpg/host.tsx +0 -2
  35. package/src/components/dock/BottomDock.tsx +7 -3
  36. package/src/components/dock/MissingShellDebug.test.tsx +193 -0
  37. package/src/components/dock/MissingShellDebug.tsx +114 -0
  38. package/src/components/dock/PodDebugSession.test.tsx +60 -0
  39. package/src/components/dock/PodDebugSession.tsx +96 -0
  40. package/src/components/dock/TerminalTab.test.tsx +48 -4
  41. package/src/components/dock/TerminalTab.tsx +47 -25
  42. package/src/components/dock/WorkloadLogsTab.test.tsx +24 -1
  43. package/src/components/dock/WorkloadLogsTab.tsx +16 -0
  44. package/src/components/execution/BatchExecutionView.command.test.tsx +69 -0
  45. package/src/components/execution/BatchExecutionView.tsx +88 -5
  46. package/src/components/execution/BatchExecutionView.workflow-stop.test.tsx +69 -0
  47. package/src/components/execution/WorkflowRunStopAction.tsx +8 -0
  48. package/src/components/gitops/GitOpsPermissionRowActions.test.tsx +100 -0
  49. package/src/components/gitops/GitOpsPermissionRowActions.tsx +27 -0
  50. package/src/components/gitops/GitOpsView.identity.test.tsx +1 -0
  51. package/src/components/gitops/GitOpsView.permissions.test.tsx +102 -0
  52. package/src/components/gitops/GitOpsView.syncRequest.test.tsx +95 -7
  53. package/src/components/gitops/GitOpsView.tsx +93 -32
  54. package/src/components/helm/OwnedResources.tsx +1 -0
  55. package/src/components/home/mcpToolCatalog.ts +1 -0
  56. package/src/components/issues/IssuesPane.render.test.tsx +1 -1
  57. package/src/components/issues/IssuesPane.tsx +11 -0
  58. package/src/components/issues/useIssueExpansion.ts +91 -0
  59. package/src/components/resource/MetricsNotConnected.test.tsx +50 -0
  60. package/src/components/resource/MetricsNotConnected.tsx +114 -0
  61. package/src/components/resource/PVCUsageBar.tsx +2 -1
  62. package/src/components/resource/PrometheusCharts.render.test.tsx +47 -0
  63. package/src/components/resource/PrometheusCharts.tsx +14 -2
  64. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +91 -1
  65. package/src/components/resource/PrometheusChartsGrid.tsx +28 -52
  66. package/src/components/resource/RestartChart.tsx +4 -3
  67. package/src/components/resource/RightsizingPanel.source.test.tsx +34 -0
  68. package/src/components/resource/RightsizingStrip.tsx +5 -3
  69. package/src/components/resource/WorkloadMetricsSection.render.test.tsx +6 -0
  70. package/src/components/resource/WorkloadMetricsSection.tsx +14 -11
  71. package/src/components/resource/nameMatchedScope.ts +9 -3
  72. package/src/components/resources/EmptyNamespaceHint.tsx +42 -0
  73. package/src/components/resources/PodDebugAction.test.tsx +157 -0
  74. package/src/components/resources/PodDebugAction.tsx +207 -0
  75. package/src/components/resources/PodDebugPermission.tsx +21 -0
  76. package/src/components/resources/ResourcesView.empty-hint.test.tsx +132 -0
  77. package/src/components/resources/ResourcesView.tsx +39 -5
  78. package/src/components/resources/namespaceHint.test.ts +34 -0
  79. package/src/components/resources/namespaceHint.ts +19 -0
  80. package/src/components/resources/renderers/AdmissionPolicyRenderers.tsx +135 -0
  81. package/src/components/resources/renderers/NodeRenderer.tsx +2 -1
  82. package/src/components/resources/renderers/PodRenderer.tsx +12 -5
  83. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.test.tsx +24 -1
  84. package/src/components/settings/LocalIntegrationStatus.tsx +14 -3
  85. package/src/components/settings/MetricsBackendSwitch.tsx +167 -0
  86. package/src/components/settings/OpenObserveSetup.test.tsx +343 -0
  87. package/src/components/settings/OpenObserveSetup.tsx +358 -0
  88. package/src/components/settings/SettingsDialog.tsx +21 -7
  89. package/src/components/settings/openobserveStatus.test.ts +34 -0
  90. package/src/components/settings/openobserveStatus.ts +55 -0
  91. package/src/components/timeline/TimelineList.selection.test.tsx +40 -0
  92. package/src/components/timeline/TimelineList.test.ts +18 -0
  93. package/src/components/timeline/TimelineList.tsx +19 -5
  94. package/src/components/timeline/TimelineView.tsx +2 -0
  95. package/src/components/workload/WorkloadView.pendingOwnership.test.tsx +34 -0
  96. package/src/components/workload/WorkloadView.tabUrl.test.tsx +44 -0
  97. package/src/components/workload/WorkloadView.tsx +95 -10
  98. package/src/context/TimelineNavigation.test.ts +59 -0
  99. package/src/context/TimelineNavigation.tsx +86 -0
  100. package/src/contexts/CapabilitiesContext.tsx +3 -1
  101. package/src/hooks/useResourceCounts.ts +2 -1
  102. package/src/hooks/useWorkflowStopAction.ts +31 -0
  103. package/src/index.css +1 -0
  104. package/src/integrations/resourceHosts.test.tsx +2 -2
  105. package/src/integrations/resourceHosts.tsx +4 -2
  106. package/src/k8s-ui-exports.test.ts +10 -0
  107. package/src/components/resources/renderers/ValidatingAdmissionPolicyRenderer.tsx +0 -128
package/src/api/client.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { hasPrometheusCharts, metricsSourceUnavailable } from './prometheusCharts'
1
2
  import type { RightsizingRow, WorkloadRightsizingEvidence } from '@skyhook-io/k8s-ui/types/rightsizing'
2
3
  import { followSwitch, switchFinished, switchInProgress, type ContextSwitchOperation } from './contextSwitch'
3
4
  import { createListRefetchInterval, normalizeResourceList, type ResourceListBody, type ResourceListResult } from './resourceLists'
@@ -8,8 +9,8 @@ import type { ReadGap, ReadGapSet } from '@skyhook-io/k8s-ui/types/read-coverage
8
9
  import type { ClusterScope } from '@skyhook-io/k8s-ui/types/cluster-scope'
9
10
  import type { WorkloadHistoryCoverage } from '@skyhook-io/k8s-ui/utils/workload-history-notes'
10
11
  import { knownKindForPluralWithGroup, pluralToKind } from '@skyhook-io/k8s-ui/utils/navigation'
11
- import { useEffect, useRef, useCallback, useMemo } from 'react'
12
- import { argoSyncOptionsForRequest } from '@skyhook-io/k8s-ui'
12
+ import { useEffect, useRef, useCallback, useMemo, useState } from 'react'
13
+ import { argoSyncOptionsForRequest, issueOccurrence, issueRowKey, type IssueRowChange } from '@skyhook-io/k8s-ui'
13
14
  import { useClusterConnected } from '../context/clusterConnected'
14
15
  import type { KueueAdmissionResponse, KueuePositionResponse } from '@skyhook-io/k8s-ui/types/scheduling'
15
16
  import type { KueueQueueMembership, KueueQueueWorkloadsResponse } from '@skyhook-io/k8s-ui/types/kueue-queues'
@@ -17,6 +18,7 @@ import { kueueQueueRetryable } from '@skyhook-io/k8s-ui/utils/kueue-queue-worklo
17
18
  import { canonicalReadCode, readActionFor } from '@skyhook-io/k8s-ui/utils/read-actions'
18
19
  import type { SearchCoverage } from '@skyhook-io/k8s-ui/types/read-coverage'
19
20
  import type { GitOpsWriteEvidence } from '@skyhook-io/k8s-ui/utils/gitops-write-guard'
21
+ import { isAmbiguousSubmitError, type SubmittedWorkflow, type WorkflowTemplateSubmission } from '@skyhook-io/k8s-ui/utils/workflow-template-submit'
20
22
  import type {
21
23
  AppHistory,
22
24
  AppRow,
@@ -36,10 +38,11 @@ import type {
36
38
  YamlDocumentIdentity,
37
39
  YamlSchemaLoadResult,
38
40
  } from '@skyhook-io/k8s-ui'
39
- import { focusManager, useInfiniteQuery, useQuery, useMutation, useQueryClient, skipToken, type QueryClient } from '@tanstack/react-query'
41
+ import { focusManager, onlineManager, useInfiniteQuery, useQuery, useMutation, useQueryClient, skipToken, type QueryClient } from '@tanstack/react-query'
40
42
  import { showApiError, showApiSuccess, showApiNotice } from '../components/ui/Toast'
41
43
  import { useIsAuthEnabled, useNamespacedCapabilities } from '../contexts/CapabilitiesContext'
42
44
  import { applyTabPick, cleanPick, ownsTabPick, pruneTabPick, withActives, writeTabPick } from '../utils/namespacePick'
45
+ import { parseContextName } from '../utils/context-name'
43
46
  import type {
44
47
  Topology,
45
48
  ClusterInfo,
@@ -81,9 +84,10 @@ import type {
81
84
  } from '../types'
82
85
  import type { GitOpsOperationResponse } from '../types/gitops'
83
86
  import { apiUrl, automaticRequestHeaders, getApiBase, getAuthHeaders, getCredentialsMode, getBasename, routePath, stripBasename } from './config'
84
- import { CONNECTION_HEADER, connectionHeaderValue } from './connectionBinding'
85
- import { httpStatusMessage, markShownInline, readErrorBody, readErrorResponse } from './httpErrors'
87
+ import { CONNECTION_HEADER, connectionHeaderValue, useCurrentConnectionId } from './connectionBinding'
88
+ import { GitOpsActionError, httpStatusMessage, markShownInline, readErrorBody, readErrorResponse } from './httpErrors'
86
89
  import {
90
+ isRadarFeatureUnsupported,
87
91
  RadarFeatureUnsupportedError,
88
92
  guardRadarFeature,
89
93
  radarControlBlocked,
@@ -94,6 +98,7 @@ import {
94
98
  type RadarFeature,
95
99
  } from './radarFeatures'
96
100
  import { useRadarUpgradeHost } from '../context/RadarUpgradeHost'
101
+ import { isGitOpsActionTarget, gitOpsActionPermissions, gitOpsDisabledReasons, type GitOpsActionCapabilities } from './gitOpsPermissions'
97
102
  import { apiVersionToGroup } from '../utils/navigation'
98
103
  import { isBadgeWorthy } from '../utils/auditBadges'
99
104
  import type { DeploymentMode } from '../types'
@@ -1049,6 +1054,100 @@ export function useSubjectIssues(
1049
1054
  });
1050
1055
  }
1051
1056
 
1057
+ export interface CorrelatedIssuesResponse extends SubjectIssuesResponse {
1058
+ /** Set when the correlated issue isn't in this answer. not_found: resolved,
1059
+ * or outside what the caller may see. user_forbidden / read_error: a native
1060
+ * Helm release whose storage read, which serves both the issue and its
1061
+ * history, was refused or failed. */
1062
+ correlation_status?: 'not_found' | 'user_forbidden' | 'read_error';
1063
+ }
1064
+
1065
+ const ISSUE_CORRELATION_REFRESH_INTERVAL_MS = 60_000;
1066
+
1067
+ // One issue's recent changes: the per-resource lookup for the issue's subject,
1068
+ // with ?correlate=<id> so Radar correlates that issue only and returns it with
1069
+ // its timing corrected. Hosts enable it for the open row only. An older Radar
1070
+ // ignores the parameter rather than failing, so the request waits for
1071
+ // capabilities and is sent only when the flag says the server reads it.
1072
+ export function useIssueCorrelation(issue: Issue | null, enabled: boolean) {
1073
+ const capabilities = useCapabilities();
1074
+ const { gatedKey, guard } = useRadarFeature('issueCorrelation');
1075
+ const pathNs = issue?.namespace ? encodeURIComponent(issue.namespace) : "_";
1076
+ const params = new URLSearchParams({ coverage: "1" });
1077
+ if (issue?.group) params.set("group", issue.group);
1078
+ if (issue) params.set("correlate", issue.id);
1079
+ return useQuery<CorrelatedIssuesResponse>({
1080
+ // The occurrence is in the key: an issue's id survives recurrence, and a
1081
+ // cached answer for the earlier occurrence would describe the wrong window.
1082
+ queryKey: ["issues", "correlation", issue?.kind ?? "", issue?.group ?? "", issue?.namespace ?? "", issue?.name ?? "", issue?.id ?? "", issue ? issueOccurrence(issue) : "", ...gatedKey],
1083
+ queryFn: () => {
1084
+ if (!capabilities.data && capabilities.error) throw capabilities.error;
1085
+ return guard(() => fetchJSON<CorrelatedIssuesResponse>(`/issues/resource/${encodeURIComponent(issue!.kind)}/${pathNs}/${encodeURIComponent(issue!.name)}?${params}`));
1086
+ },
1087
+ retry: shouldRetryRadarQuery,
1088
+ staleTime: 30000,
1089
+ refetchInterval: (q) => q.state.error instanceof RadarFeatureUnsupportedError ? false : ISSUE_CORRELATION_REFRESH_INTERVAL_MS,
1090
+ refetchIntervalInBackground: false,
1091
+ enabled: enabled && !!issue && !capabilities.isPending,
1092
+ });
1093
+ }
1094
+
1095
+ export interface IssueRecentChangesResponse {
1096
+ /** Per issue id, the one change its row names. An issue with nothing to
1097
+ * name is absent, whatever the reason; absence is never "no changes". */
1098
+ changes: Record<string, IssueRowChange>;
1099
+ }
1100
+
1101
+ /** The server's cap on issues per batched row lookup. */
1102
+ export const ISSUE_ROW_CHANGES_MAX = 50;
1103
+
1104
+ /** One issue= value: <id>/<kind>/<namespace>/<name>[/<group>], "_" for a
1105
+ * cluster-scoped subject's namespace. */
1106
+ export function issueRowChangeParam(issue: Issue): string {
1107
+ const value = [issue.id, issue.kind, issue.namespace || "_", issue.name].map(encodeURIComponent).join("/");
1108
+ return issue.group ? `${value}/${encodeURIComponent(issue.group)}` : value;
1109
+ }
1110
+
1111
+ // The one change each issue row on screen names, from one batched lookup
1112
+ // (GET /api/issues/recent-changes), polled like an open issue's recent
1113
+ // changes. Like the per-issue correlation, it waits for capabilities and goes
1114
+ // out only when the server advertises issueCorrelation. The previous answer
1115
+ // stays while a new set of rows loads, so rows on screen before and after a
1116
+ // scroll keep their note. Keyed by issueRowKey.
1117
+ export function useIssueRowChanges(issues: Issue[]): ReadonlyMap<string, IssueRowChange> | undefined {
1118
+ const capabilities = useCapabilities();
1119
+ const { gatedKey, guard, support } = useRadarFeature('issueCorrelation');
1120
+ const rows = useMemo(() => issues.slice(0, ISSUE_ROW_CHANGES_MAX), [issues]);
1121
+ const params = useMemo(() => {
1122
+ const p = new URLSearchParams();
1123
+ for (const issue of rows) p.append("issue", issueRowChangeParam(issue));
1124
+ return p.toString();
1125
+ }, [rows]);
1126
+ const query = useQuery<IssueRecentChangesResponse>({
1127
+ queryKey: ["issues", "row-changes", params, ...gatedKey],
1128
+ queryFn: () => {
1129
+ if (!capabilities.data && capabilities.error) throw capabilities.error;
1130
+ return guard(() => fetchJSON<IssueRecentChangesResponse>(`/issues/recent-changes?${params}`));
1131
+ },
1132
+ retry: shouldRetryRadarQuery,
1133
+ staleTime: 30000,
1134
+ placeholderData: (previous) => previous,
1135
+ refetchInterval: (q) => q.state.error instanceof RadarFeatureUnsupportedError ? false : ISSUE_CORRELATION_REFRESH_INTERVAL_MS,
1136
+ refetchIntervalInBackground: false,
1137
+ enabled: rows.length > 0 && !capabilities.isPending && support !== "unsupported",
1138
+ });
1139
+ const changes = query.data?.changes;
1140
+ return useMemo(() => {
1141
+ if (!changes || rows.length === 0) return undefined;
1142
+ const out = new Map<string, IssueRowChange>();
1143
+ for (const issue of rows) {
1144
+ const change = changes[issue.id];
1145
+ if (change) out.set(issueRowKey(issue), change);
1146
+ }
1147
+ return out;
1148
+ }, [changes, rows]);
1149
+ }
1150
+
1052
1151
  import type { Trace as NetworkTrace, InClusterCapability, DrainPlan, DrainPlanPod } from '@skyhook-io/k8s-ui'
1053
1152
 
1054
1153
  // useTrace polls the static path-shaped diagnosis for one network entry
@@ -1940,6 +2039,11 @@ export function useClusterInfo() {
1940
2039
  return query;
1941
2040
  }
1942
2041
 
2042
+ function cachedContextName(queryClient: QueryClient): string | undefined {
2043
+ return queryClient.getQueryData<ClusterInfo>(["cluster-info"])?.context
2044
+ ?? queryClient.getQueryData<{ context: string }>(["connection-status"])?.context;
2045
+ }
2046
+
1943
2047
  // Version check
1944
2048
  export type InstallMethod =
1945
2049
  "homebrew" | "krew" | "scoop" | "direct" | "desktop";
@@ -2065,13 +2169,10 @@ export function useVersionCheck() {
2065
2169
 
2066
2170
  /**
2067
2171
  * Guards a fetch for an endpoint the connected Radar may predate (see
2068
- * radarFeatures.ts). A Radar known to be too old is never asked; one whose
2069
- * version is unknown is asked, and chi's unknown-route 404 is read as the same
2070
- * answer. Either way the caller gets a RadarFeatureUnsupportedError, which the
2071
- * sections render as an upgrade note instead of an error.
2072
- *
2073
- * Nothing waits on /version-check: an agent that advertises the feature flag
2074
- * is fetched immediately, and an unknown version falls through to the fetch.
2172
+ * radarFeatures.ts). Features requiring affirmative support wait for the
2173
+ * flag. Others can probe while support is unknown. A known-old version or
2174
+ * an unknown-route 404 from a probe raises RadarFeatureUnsupportedError,
2175
+ * which sections render as an upgrade note.
2075
2176
  *
2076
2177
  * Spread `gatedKey` into the query key. A gate decided from early information
2077
2178
  * (a host-supplied version before /capabilities answers) can lift later, and
@@ -3210,29 +3311,90 @@ export function useResourceAvailability(kind: string, namespace: string, name: s
3210
3311
  });
3211
3312
  }
3212
3313
 
3314
+ function hasPendingOwnership(data?: ResourceWithRelationships): boolean {
3315
+ const coverage = data?.relationships?.ownership;
3316
+ if (!coverage) return false;
3317
+ const pending = "kind_sync_pending";
3318
+ return coverage.unavailableReason === pending ||
3319
+ coverage.ownerReason === pending ||
3320
+ coverage.manager?.stop?.reason === pending ||
3321
+ coverage.manages?.unavailableReason === pending ||
3322
+ !!coverage.managers?.notChecked?.some(gap => gap.reason === pending) ||
3323
+ !!coverage.children?.notChecked?.some(gap => gap.reason === pending);
3324
+ }
3325
+
3213
3326
  // Hook that returns full response with relationships explicitly
3214
3327
  export function useResourceWithRelationships<T>(
3215
3328
  kind: string,
3216
3329
  namespace: string,
3217
3330
  name: string,
3218
3331
  group?: string,
3219
- options?: { cacheScope?: string },
3332
+ options?: { cacheScope?: string; pollPendingOwnership?: boolean },
3220
3333
  ) {
3221
- return useQuery<ResourceWithRelationships<T>>({
3222
- queryKey: ["resource", kind, namespace, name, group, ...(options?.cacheScope ? [options.cacheScope] : [])],
3223
- queryFn: () => fetchResourceWithRelationships<T>(kind, namespace, name, group),
3224
- enabled: Boolean(kind && name),
3225
- refetchInterval: (query) => goneRecheckInterval(query, undefined),
3226
- // Deep-linked detail views can mount while the kind's informer is still
3227
- // completing its initial sync: keep polling instead of erroring out.
3228
- retry: (failureCount, error) => {
3229
- if (isStillLoadingError(error)) return true;
3230
- if (isKindSyncFailed(error)) return false;
3231
- return failureCount < 1; // one retry, 4xx included, unlike the QueryClient default
3232
- },
3233
- retryDelay: (failureCount, error) =>
3234
- isStillLoadingError(error) ? 2000 : Math.min(1000 * 2 ** failureCount, 30000),
3235
- });
3334
+ const client = useQueryClient();
3335
+ const cacheScope = options?.cacheScope;
3336
+ const resourceOptions = useMemo(
3337
+ () => resourceQueryOptions<T>(kind, namespace, name, group, { cacheScope }),
3338
+ [kind, namespace, name, group, cacheScope],
3339
+ );
3340
+ const query = useQuery<ResourceWithRelationships<T>>({ ...resourceOptions, refetchIntervalInBackground: false });
3341
+ const { refetch } = query;
3342
+ const poll = options?.pollPendingOwnership;
3343
+ const apiBase = getApiBase();
3344
+
3345
+ useEffect(() => {
3346
+ if (!poll || !resourceOptions.enabled) return;
3347
+ const cache = client.getQueryCache();
3348
+ const { queryHash } = client.defaultQueryOptions(resourceOptions);
3349
+ let attempts = 0;
3350
+ let timer: ReturnType<typeof setTimeout> | undefined;
3351
+
3352
+ function schedule() {
3353
+ clearTimeout(timer);
3354
+ timer = undefined;
3355
+ const state = cache.get<ResourceWithRelationships<T>>(queryHash)?.state;
3356
+ if (!state || state.error || !hasPendingOwnership(state.data)) {
3357
+ attempts = 0;
3358
+ return;
3359
+ }
3360
+ // A hidden or offline view waits without timers; focus and reconnect
3361
+ // resume it below.
3362
+ if (!focusManager.isFocused() || !onlineManager.isOnline()) return;
3363
+ if (state.fetchStatus !== "idle" || attempts >= 8) return;
3364
+ timer = setTimeout(() => {
3365
+ timer = undefined;
3366
+ if (apiBase !== getApiBase()) return;
3367
+ attempts++;
3368
+ void refetch({ cancelRefetch: false });
3369
+ }, Math.min(5000 * 2 ** attempts, 30_000));
3370
+ }
3371
+
3372
+ // Other observers and SSE can change this answer, including after the last
3373
+ // poll. Only this view's timer spends attempts; a settled answer resets them.
3374
+ const unsubscribe = cache.subscribe(event => {
3375
+ if ((event.type === "updated" || event.type === "removed") && event.query.queryHash === queryHash) schedule();
3376
+ });
3377
+ // Redundant focus or online events must not restart a running countdown.
3378
+ const resume = () => {
3379
+ if (!focusManager.isFocused() || !onlineManager.isOnline()) {
3380
+ clearTimeout(timer);
3381
+ timer = undefined;
3382
+ } else if (timer === undefined) {
3383
+ schedule();
3384
+ }
3385
+ };
3386
+ const unsubscribeFocus = focusManager.subscribe(resume);
3387
+ const unsubscribeOnline = onlineManager.subscribe(resume);
3388
+ schedule();
3389
+ return () => {
3390
+ unsubscribe();
3391
+ unsubscribeFocus();
3392
+ unsubscribeOnline();
3393
+ clearTimeout(timer);
3394
+ };
3395
+ }, [poll, apiBase, client, resourceOptions, refetch]);
3396
+
3397
+ return query;
3236
3398
  }
3237
3399
 
3238
3400
  export interface ResourceListOptions {
@@ -4033,6 +4195,7 @@ export function useTopNodeMetrics(options?: { enabled?: boolean }) {
4033
4195
 
4034
4196
  // Prometheus types
4035
4197
  export interface PrometheusStatus {
4198
+ gkeSystemMetrics?: boolean;
4036
4199
  available: boolean;
4037
4200
  connected: boolean;
4038
4201
  /** A discovery run is in flight for the current configuration. Never true alongside connected. */
@@ -4046,6 +4209,30 @@ export interface PrometheusStatus {
4046
4209
  };
4047
4210
  contextName?: string;
4048
4211
  error?: string;
4212
+ /** Set when metrics come from a backend other than plain Prometheus. */
4213
+ source?: MetricsSource;
4214
+ /** How this install can get OpenObserve metrics: Radar Hub selects the source, or local Settings → Metrics. */
4215
+ openobserve?: "hub" | "local";
4216
+ }
4217
+
4218
+ /**
4219
+ * Where metrics come from when not a plain Prometheus. With `matchedBy`
4220
+ * unset and `unavailable` false, the source is not serving this context and
4221
+ * `error`/`warning` explain why (the cluster's own Prometheus, if any, serves).
4222
+ */
4223
+ export interface MetricsSource {
4224
+ kind: "openobserve";
4225
+ via?: "local" | "hub";
4226
+ matchedBy?: "id" | "name";
4227
+ clusterLabel?: { name: string; value: string };
4228
+ dialect?: "standard" | "collector";
4229
+ warning?: string;
4230
+ versionWarning?: string;
4231
+ missingFamilies?: string[];
4232
+ unavailable?: boolean;
4233
+ /** The match is still running; poll until it settles. */
4234
+ pending?: boolean;
4235
+ error?: string;
4049
4236
  }
4050
4237
 
4051
4238
  // Time-series sample types live in @skyhook-io/k8s-ui (shared with library
@@ -4066,6 +4253,7 @@ export interface PrometheusQueryResult {
4066
4253
  }
4067
4254
 
4068
4255
  export interface PrometheusResourceMetrics {
4256
+ source?: "gke";
4069
4257
  kind: string;
4070
4258
  namespace?: string;
4071
4259
  name: string;
@@ -4165,8 +4353,8 @@ export function prometheusStatusRefetchInterval(
4165
4353
  status: PrometheusStatus | undefined,
4166
4354
  ): number {
4167
4355
  if (!status) return PROM_STATUS_POLL_IDLE_MS;
4168
- const settled = status.connected || !!status.error;
4169
- return status.discovering || !settled
4356
+ const settled = hasPrometheusCharts(status) || !!status.error;
4357
+ return status.discovering || !settled || status.source?.pending
4170
4358
  ? PROM_STATUS_POLL_DISCOVERING_MS
4171
4359
  : PROM_STATUS_POLL_IDLE_MS;
4172
4360
  }
@@ -4235,6 +4423,39 @@ export function usePrometheusConnect() {
4235
4423
  });
4236
4424
  }
4237
4425
 
4426
+ export type MetricsDiscoveryOutcome = "connected" | "collector" | "none";
4427
+
4428
+ // Discover metrics on an install that can also read OpenObserve. The connect
4429
+ // call asks Radar Hub for the source first (when connected to it), then looks
4430
+ // for Prometheus; with nothing found, it reports whether an OpenObserve
4431
+ // collector runs. The outcome and any failure are shown in place, so there
4432
+ // are no toasts. A 502 means discovery found no usable Prometheus, whose
4433
+ // reason the status error then shows; any other failure ends discovery.
4434
+ export function useDiscoverMetrics() {
4435
+ const queryClient = useQueryClient();
4436
+ return useMutation({
4437
+ mutationFn: async (): Promise<MetricsDiscoveryOutcome> => {
4438
+ const resp = await apiFetch(`${getApiBase()}/prometheus/connect`, {
4439
+ method: "POST",
4440
+ });
4441
+ if (!resp.ok && resp.status !== 502) {
4442
+ const body = await readErrorBody(resp);
4443
+ throw new Error(body.error || `HTTP ${resp.status}`);
4444
+ }
4445
+ if (resp.ok && hasPrometheusCharts((await resp.json()) as PrometheusStatus)) return "connected";
4446
+ try {
4447
+ const presence = await fetchJSON<{ detected: boolean }>("/metrics/openobserve/collector");
4448
+ return presence.detected ? "collector" : "none";
4449
+ } catch {
4450
+ return "none";
4451
+ }
4452
+ },
4453
+ onSettled: () => {
4454
+ queryClient.invalidateQueries({ queryKey: ["prometheus-status"] });
4455
+ },
4456
+ });
4457
+ }
4458
+
4238
4459
  // Auto-discover Prometheus on first mount of any Prom-backed view, and
4239
4460
  // auto-reconnect across radar restarts on subsequent mounts.
4240
4461
  //
@@ -4270,6 +4491,8 @@ export function useAutoPromConnect(): void {
4270
4491
  const queryClient = useQueryClient();
4271
4492
  const { data: clusterInfo } = useClusterInfo();
4272
4493
  const { data: status, isLoading: statusLoading } = usePrometheusStatus();
4494
+ const chartsAvailable = hasPrometheusCharts(status);
4495
+ const sourceUnavailable = metricsSourceUnavailable(status);
4273
4496
  const attemptedRef = useRef<string | null>(null);
4274
4497
 
4275
4498
  useEffect(() => {
@@ -4278,7 +4501,7 @@ export function useAutoPromConnect(): void {
4278
4501
  if (!context || statusLoading) return;
4279
4502
 
4280
4503
  // Persist the "we've connected here before" signal once a connection lands.
4281
- if (status?.connected) {
4504
+ if (chartsAvailable) {
4282
4505
  try {
4283
4506
  window.localStorage.setItem(promAutoConnectKey(context), "1");
4284
4507
  } catch {
@@ -4287,6 +4510,9 @@ export function useAutoPromConnect(): void {
4287
4510
  return;
4288
4511
  }
4289
4512
 
4513
+ // An OpenObserve connection that can't answer is the source in use;
4514
+ // discovering Prometheus would not stand in for it.
4515
+ if (sourceUnavailable) return;
4290
4516
  if (attemptedRef.current === context) return;
4291
4517
  let cached: string | null = null;
4292
4518
  try {
@@ -4317,7 +4543,7 @@ export function useAutoPromConnect(): void {
4317
4543
  if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
4318
4544
  const nextStatus = (await resp.json()) as PrometheusStatus;
4319
4545
  queryClient.setQueryData(["prometheus-status"], nextStatus);
4320
- if (!nextStatus.connected)
4546
+ if (!hasPrometheusCharts(nextStatus))
4321
4547
  throw new Error(nextStatus.error || "Prometheus unavailable");
4322
4548
  queryClient.invalidateQueries({ queryKey: ["prometheus-status"] });
4323
4549
  })
@@ -4339,7 +4565,7 @@ export function useAutoPromConnect(): void {
4339
4565
  });
4340
4566
  }, delay);
4341
4567
  return () => window.clearTimeout(timeout);
4342
- }, [clusterInfo?.context, status?.connected, statusLoading, queryClient]);
4568
+ }, [clusterInfo?.context, chartsAvailable, sourceUnavailable, statusLoading, queryClient]);
4343
4569
  }
4344
4570
 
4345
4571
  // Fetch Prometheus metrics for a resource
@@ -5513,6 +5739,107 @@ export function useResumeCronJob() {
5513
5739
  });
5514
5740
  }
5515
5741
 
5742
+ // ============================================================================
5743
+ // Argo Workflow stop
5744
+ // ============================================================================
5745
+
5746
+ export type WorkflowStopStrategy = "Stop" | "Terminate";
5747
+
5748
+ /** What POST /workflows/{ns}/{name}/stop settled to, as the UI reports it. */
5749
+ export type WorkflowStopOutcome =
5750
+ | { state: "requested"; shutdown: string }
5751
+ | { state: "already"; shutdown: string }
5752
+ | { state: "notStored"; shutdown: string }
5753
+ | { state: "finished" };
5754
+
5755
+ // A stored Terminate satisfies either strategy. Anything else that doesn't
5756
+ // match the request means admission rewrote or dropped it, whatever `changed`
5757
+ // says: `changed` compares with the value before the patch, not the request.
5758
+ export function workflowStopOutcome(requested: WorkflowStopStrategy, response: { shutdown: string; changed: boolean }): WorkflowStopOutcome {
5759
+ const { shutdown, changed } = response;
5760
+ if (shutdown !== requested && shutdown !== "Terminate") return { state: "notStored", shutdown };
5761
+ // A Stop that admission stored as Terminate interrupts exit handlers the user meant to run.
5762
+ if (changed && shutdown !== requested) return { state: "notStored", shutdown };
5763
+ return changed ? { state: "requested", shutdown } : { state: "already", shutdown };
5764
+ }
5765
+
5766
+ export function workflowStopErrorMessage(body: { error?: string; error_code?: string }, status: number): string {
5767
+ if (body.error_code === "workflow_replaced") {
5768
+ return "A different Workflow now has this name, so nothing was stopped. Open it again to review the current run.";
5769
+ }
5770
+ return body.error || `HTTP ${status}`;
5771
+ }
5772
+
5773
+ /** The request named a run that no longer exists under this name. */
5774
+ export function isWorkflowStopTargetGone(error: unknown): boolean {
5775
+ return error instanceof ApiError && (error.status === 404 || error.data?.error_code === "workflow_replaced");
5776
+ }
5777
+
5778
+ export function reportWorkflowStopOutcome(outcome: WorkflowStopOutcome): void {
5779
+ if (outcome.state === "finished") {
5780
+ showApiNotice("Workflow already finished", "Nothing was stopped.", "info");
5781
+ } else if (outcome.state === "already") {
5782
+ showApiNotice(outcome.shutdown === "Terminate" ? "Workflow is already terminating" : "Workflow is already stopping", undefined, "info");
5783
+ } else if (outcome.state === "notStored") {
5784
+ showApiNotice(
5785
+ "Stop not stored",
5786
+ outcome.shutdown
5787
+ ? `Kubernetes accepted the change but stored shutdown "${outcome.shutdown}". An admission policy may have changed it.`
5788
+ : "Kubernetes accepted the change but stored no shutdown, so the Workflow keeps running. An admission policy may have removed it.",
5789
+ "warning",
5790
+ );
5791
+ } else if (outcome.shutdown === "Stop") {
5792
+ showApiSuccess("Stop requested", "Argo ends the running steps, then runs the exit handlers.");
5793
+ } else {
5794
+ showApiSuccess("Terminate requested", "Argo ends the running steps, including any exit handler, and starts no more.");
5795
+ }
5796
+ }
5797
+
5798
+ // The request names the reviewed run by UID only. A running Workflow's
5799
+ // resourceVersion moves with every controller status update, so pinning it
5800
+ // would refuse nearly every stop; the server still refuses a replaced run.
5801
+ export function useStopWorkflow() {
5802
+ const queryClient = useQueryClient();
5803
+
5804
+ return useMutation({
5805
+ mutationFn: async ({
5806
+ namespace,
5807
+ name,
5808
+ uid,
5809
+ strategy,
5810
+ }: {
5811
+ namespace: string;
5812
+ name: string;
5813
+ uid: string;
5814
+ strategy: WorkflowStopStrategy;
5815
+ }): Promise<WorkflowStopOutcome> => {
5816
+ const response = await apiFetch(
5817
+ `${getApiBase()}/workflows/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}/stop`,
5818
+ {
5819
+ method: "POST",
5820
+ headers: { "Content-Type": "application/json" },
5821
+ body: JSON.stringify({ uid, strategy }),
5822
+ },
5823
+ );
5824
+ if (!response.ok) {
5825
+ const body = await readErrorBody(response);
5826
+ // The run ended before the request reached it: what the user wanted holds.
5827
+ if (response.status === 409 && body.error_code === "workflow_finished") return { state: "finished" };
5828
+ throw new ApiError(workflowStopErrorMessage(body, response.status), response.status, body);
5829
+ }
5830
+ return workflowStopOutcome(strategy, await response.json());
5831
+ },
5832
+ meta: { errorMessage: "Failed to stop Workflow" },
5833
+ onSuccess: reportWorkflowStopOutcome,
5834
+ onSettled: (_data, _error, variables) => {
5835
+ queryClient.invalidateQueries({ queryKey: ["resource", "workflows", variables.namespace, variables.name] });
5836
+ queryClient.invalidateQueries({ queryKey: ["resources", "workflows"] });
5837
+ queryClient.invalidateQueries({ queryKey: ["workload-runs"] });
5838
+ queryClient.invalidateQueries({ queryKey: ["topology"] });
5839
+ },
5840
+ });
5841
+ }
5842
+
5516
5843
  // ============================================================================
5517
5844
  // Workload operations
5518
5845
  // ============================================================================
@@ -5520,33 +5847,42 @@ export function useResumeCronJob() {
5520
5847
  // Restart a workload (Deployment, StatefulSet, DaemonSet, Rollout)
5521
5848
  export function useRestartWorkload() {
5522
5849
  const queryClient = useQueryClient();
5850
+ const { support, guard } = useRadarFeature("workloadRestartPreconditions");
5851
+ const apiBase = getApiBase();
5523
5852
 
5524
5853
  return useMutation({
5525
5854
  mutationFn: async ({
5526
5855
  kind,
5527
5856
  namespace,
5528
5857
  name,
5858
+ uid,
5529
5859
  }: {
5530
5860
  kind: string;
5531
5861
  namespace: string;
5532
5862
  name: string;
5863
+ uid?: string;
5533
5864
  }) => {
5534
- const response = await apiFetch(
5535
- `${getApiBase()}/workloads/${kind}/${namespace}/${name}/restart`,
5536
- {
5537
- method: "POST",
5538
- },
5539
- );
5865
+ const url = apiUrl(`/workloads/${kind}/${namespace}/${name}/restart`, apiBase);
5866
+ const response = support === "unsupported"
5867
+ ? await apiFetch(url, { method: "POST" })
5868
+ : await guard(() => {
5869
+ if (!uid) throw new Error("The workload UID is unavailable. Refresh and try again.");
5870
+ return apiFetch(url, {
5871
+ method: "POST",
5872
+ headers: { "Content-Type": "application/json" },
5873
+ body: JSON.stringify({ uid }),
5874
+ });
5875
+ });
5540
5876
  if (!response.ok) {
5541
5877
  throw new Error(restartErrorMessage(await readErrorBody(response), response.status));
5542
5878
  }
5543
- return response.json();
5879
+ return response.json() as Promise<RestartResult>;
5544
5880
  },
5545
5881
  meta: {
5546
5882
  errorMessage: "Failed to restart workload",
5547
- successMessage: "Workload restarting",
5548
5883
  },
5549
- onSuccess: (_, variables) => {
5884
+ onSuccess: (result, variables) => {
5885
+ reportRestart(result);
5550
5886
  queryClient.invalidateQueries({
5551
5887
  queryKey: ["resources", variables.kind],
5552
5888
  });
@@ -5817,9 +6153,42 @@ export function rollbackErrorMessage(body: { error?: string; error_code?: string
5817
6153
  return body.error || `HTTP ${status}`;
5818
6154
  }
5819
6155
 
6156
+ export interface RestartResult {
6157
+ message?: string;
6158
+ restartedAt?: string;
6159
+ changed?: boolean;
6160
+ }
6161
+
6162
+ // changed:false means the workload already carried a restart request at or after
6163
+ // now (a repeated click, or a Rollout's future restartAt), so nothing new was written.
6164
+ export function restartOutcome(result: RestartResult | undefined): { title: string; detail?: string; repeated: boolean } {
6165
+ if (result?.changed !== false) return { title: "Workload restarting", repeated: false };
6166
+ const at = result.restartedAt ? new Date(result.restartedAt) : undefined;
6167
+ return {
6168
+ title: "Restart already requested",
6169
+ detail: at && !Number.isNaN(at.getTime()) ? `Requested for ${at.toLocaleString()}.` : undefined,
6170
+ repeated: true,
6171
+ };
6172
+ }
6173
+
6174
+ function reportRestart(result: RestartResult | undefined): void {
6175
+ const { title, detail, repeated } = restartOutcome(result);
6176
+ if (repeated) showApiNotice(title, detail, "info");
6177
+ else showApiSuccess(title, detail);
6178
+ }
6179
+
5820
6180
  export function restartErrorMessage(body: { error?: string; error_code?: string }, status: number): string {
5821
- if (body.error_code === "workload_paused") {
5822
- return "This Deployment is paused. Click Resume rollout, then restart.";
6181
+ switch (body.error_code) {
6182
+ case "workload_paused":
6183
+ return "This Deployment is paused. Click Resume rollout, then restart.";
6184
+ case "workload_changed":
6185
+ return "This workload changed or was replaced since you opened it. Refresh and try again.";
6186
+ case "restart_not_applicable":
6187
+ return body.error || "This workload’s update strategy won’t restart all pods.";
6188
+ case "workload_terminating":
6189
+ return "This workload is being deleted and cannot be restarted.";
6190
+ case "restart_not_stored":
6191
+ return "Kubernetes admission changed or removed the restart marker.";
5823
6192
  }
5824
6193
  return body.error || `HTTP ${status}`;
5825
6194
  }
@@ -6220,8 +6589,7 @@ export function useDrainNode(nodeUID = "") {
6220
6589
  return response.json();
6221
6590
  },
6222
6591
  onMutate: ({ name }) => {
6223
- const contextName = queryClient.getQueryData<ClusterInfo>(["cluster-info"])?.context
6224
- ?? queryClient.getQueryData<{ context: string }>(["connection-status"])?.context;
6592
+ const contextName = cachedContextName(queryClient);
6225
6593
  const activity: NodeDrainActivity = {
6226
6594
  status: "pending",
6227
6595
  requestId: ++nextNodeDrainRequestId,
@@ -7337,6 +7705,81 @@ export function useArtifactHubChart(
7337
7705
  // GitOps Mutation Factory
7338
7706
  // ============================================================================
7339
7707
 
7708
+ type GitOpsConnection = { apiBase: string; connectionId?: string };
7709
+ type GitOpsTargetVars = ArgoAppVars & { kind?: string; expectedConnection?: GitOpsConnection };
7710
+
7711
+ function gitOpsRequestTarget(queryClient: QueryClient, { namespace, name, kind }: GitOpsTargetVars): string {
7712
+ const clusterId = /^\/c\/([^/]+)$/.exec(getBasename())?.[1];
7713
+ const context = cachedContextName(queryClient);
7714
+ const cluster = clusterId ?? (context && context !== "in-cluster" ? parseContextName(context).clusterName : undefined);
7715
+ const resource = `${kind ? pluralToKind(kind) : "Application"} ${namespace}/${name}`;
7716
+ return cluster ? `${resource} on ${cluster}` : resource;
7717
+ }
7718
+
7719
+ const GITOPS_PERMISSION_MAX_AGE = 120_000;
7720
+
7721
+ type CachedGitOpsActionCapabilities = GitOpsActionCapabilities & {
7722
+ confirmedAt: Record<string, number>;
7723
+ };
7724
+
7725
+ export function useGitOpsActionCapabilities(kind: string, group: string | undefined, namespace: string, name: string, enabled = true) {
7726
+ const active = isGitOpsActionTarget(kind, group);
7727
+ const queryClient = useQueryClient();
7728
+ const { support, guard, gatedKey } = useRadarFeature("gitopsActionCapabilities");
7729
+ const apiBase = getApiBase();
7730
+ const connection = useCurrentConnectionId(apiBase);
7731
+ const queryKey = ["gitops-action-capabilities", apiBase, connection, kind, group, namespace, name, ...gatedKey];
7732
+ const [, setExpiryTime] = useState(0);
7733
+ const query = useQuery<CachedGitOpsActionCapabilities>({
7734
+ queryKey,
7735
+ queryFn: ({ signal }) => guard(async () => {
7736
+ const next = await fetchJSON<GitOpsActionCapabilities>(`/gitops/capabilities/${encodeURIComponent(kind)}/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`, signal);
7737
+ const previous = queryClient.getQueryData<CachedGitOpsActionCapabilities>(queryKey);
7738
+ const now = Date.now();
7739
+ const confirmedAt: Record<string, number> = {};
7740
+ for (const [action, capability] of Object.entries(next.actions)) {
7741
+ if (capability.allowed !== undefined || capability.unsupported) {
7742
+ confirmedAt[action] = now;
7743
+ } else if (!capability.unsupported && previous?.confirmedAt[action] !== undefined && now - previous.confirmedAt[action] < GITOPS_PERMISSION_MAX_AGE) {
7744
+ next.actions[action] = previous.actions[action];
7745
+ confirmedAt[action] = previous.confirmedAt[action];
7746
+ }
7747
+ }
7748
+ return { ...next, confirmedAt };
7749
+ }),
7750
+ enabled: enabled && active && Boolean(namespace && name) && support !== 'unsupported',
7751
+ staleTime: 15_000,
7752
+ refetchInterval: query => enabled && active && !isRadarFeatureUnsupported(query.state.error, 'gitopsActionCapabilities') ? 30_000 : false,
7753
+ });
7754
+ const now = Date.now();
7755
+ const expiries = Object.values(query.data?.confirmedAt ?? {}).map(time => time + GITOPS_PERMISSION_MAX_AGE).filter(time => time > now);
7756
+ const nextExpiry = expiries.length ? Math.min(...expiries) : undefined;
7757
+ useEffect(() => {
7758
+ if (nextExpiry === undefined) return;
7759
+ const timer = setTimeout(() => setExpiryTime(Date.now()), Math.max(0, nextExpiry - Date.now()));
7760
+ return () => clearTimeout(timer);
7761
+ }, [nextExpiry]);
7762
+ const data: GitOpsActionCapabilities | undefined = query.data && {
7763
+ actions: Object.fromEntries(Object.entries(query.data.actions).map(([action, capability]) => [action,
7764
+ (capability.allowed !== undefined || capability.unsupported) && now - query.data!.confirmedAt[action] >= GITOPS_PERMISSION_MAX_AGE
7765
+ ? { reason: "Couldn't check your permissions — retrying" }
7766
+ : capability,
7767
+ ])),
7768
+ };
7769
+ const featureUnsupported = isRadarFeatureUnsupported(query.error, 'gitopsActionCapabilities');
7770
+ const permissions = active ? gitOpsActionPermissions(support, data, featureUnsupported) : undefined;
7771
+ const permissionCheckUnavailable = active && support !== 'unsupported' && !featureUnsupported && (
7772
+ (!data && query.isError) || Object.values(permissions ?? {}).some(capability => capability.allowed === undefined && !capability.unsupported && !!capability.reason)
7773
+ );
7774
+ return {
7775
+ ...query,
7776
+ data,
7777
+ permissions,
7778
+ permissionCheckUnavailable,
7779
+ disabledReasons: active ? gitOpsDisabledReasons(support, data, featureUnsupported) : {},
7780
+ };
7781
+ }
7782
+
7340
7783
  interface GitOpsMutationConfig<TVariables, TContext = undefined> {
7341
7784
  getPath: (variables: TVariables) => string;
7342
7785
  // Called by the hook on every render (so it may call hooks); its value is
@@ -7344,6 +7787,7 @@ interface GitOpsMutationConfig<TVariables, TContext = undefined> {
7344
7787
  useRequestContext?: () => TContext;
7345
7788
  getBody?: (variables: TVariables, context: TContext) => unknown;
7346
7789
  errorMessage: string;
7790
+ isErrorShownInline?: (variables: TVariables) => boolean;
7347
7791
  successMessage?: string;
7348
7792
  getSuccessMessage?: (data: GitOpsOperationResponse, variables: TVariables) => string;
7349
7793
  getInvalidateKeys: (variables: TVariables) => (string | undefined)[][];
@@ -7353,36 +7797,46 @@ interface GitOpsMutationConfig<TVariables, TContext = undefined> {
7353
7797
  * Factory function for creating GitOps mutation hooks with consistent patterns.
7354
7798
  * Handles fetch, error handling, meta messages, and query invalidation.
7355
7799
  */
7356
- function createGitOpsMutation<TVariables, TContext = undefined>(
7800
+ function createGitOpsMutation<TVariables extends GitOpsTargetVars, TContext = undefined>(
7357
7801
  config: GitOpsMutationConfig<TVariables, TContext>,
7358
7802
  ) {
7359
- return function useGitOpsMutation() {
7803
+ return function useGitOpsMutation(options?: { reportErrors?: boolean }) {
7360
7804
  const queryClient = useQueryClient();
7361
7805
  const requestContext = config.useRequestContext?.() as TContext;
7362
- return useMutation<GitOpsOperationResponse, Error, TVariables>({
7806
+ return useMutation<GitOpsOperationResponse, GitOpsActionError, TVariables>({
7363
7807
  mutationFn: async (
7364
7808
  variables: TVariables,
7365
7809
  ): Promise<GitOpsOperationResponse> => {
7366
- const response = await apiFetch(
7367
- `${getApiBase()}${config.getPath(variables)}`,
7368
- {
7369
- method: "POST",
7370
- headers: config.getBody
7371
- ? { "Content-Type": "application/json" }
7372
- : undefined,
7373
- body: config.getBody
7374
- ? JSON.stringify(config.getBody(variables, requestContext))
7375
- : undefined,
7376
- },
7377
- );
7378
- if (!response.ok) {
7379
- const error = await readErrorBody(response);
7380
- throw new Error(error.error || `HTTP ${response.status}`);
7810
+ const target = gitOpsRequestTarget(queryClient, variables);
7811
+ try {
7812
+ const expected = variables.expectedConnection;
7813
+ if (expected && (getApiBase() !== expected.apiBase || connectionHeaderValue(expected.apiBase) !== expected.connectionId)) {
7814
+ throw new Error("The cluster connection changed before syncing. Return to the original cluster to retry.");
7815
+ }
7816
+ const response = await apiFetch(
7817
+ apiUrl(config.getPath(variables)),
7818
+ {
7819
+ method: "POST",
7820
+ headers: config.getBody
7821
+ ? { "Content-Type": "application/json" }
7822
+ : undefined,
7823
+ body: config.getBody
7824
+ ? JSON.stringify(config.getBody(variables, requestContext))
7825
+ : undefined,
7826
+ },
7827
+ );
7828
+ if (!response.ok) {
7829
+ const error = await readErrorBody(response);
7830
+ throw new GitOpsActionError(error, response.status, target);
7831
+ }
7832
+ return await response.json() as GitOpsOperationResponse;
7833
+ } catch (error) {
7834
+ if (error instanceof Error && config.isErrorShownInline?.(variables)) markShownInline(error);
7835
+ throw error;
7381
7836
  }
7382
- return response.json() as Promise<GitOpsOperationResponse>;
7383
7837
  },
7384
7838
  meta: {
7385
- errorMessage: config.errorMessage,
7839
+ errorMessage: options?.reportErrors === false ? undefined : config.errorMessage,
7386
7840
  successMessage: config.successMessage,
7387
7841
  },
7388
7842
  onSuccess: (data, variables) => {
@@ -7405,6 +7859,8 @@ type ArgoAppVars = { namespace: string; name: string };
7405
7859
  // useArgoSync sends these — splitting the type prevents callers from passing
7406
7860
  // resources/revision/prune to mutations that would silently drop them.
7407
7861
  export type ArgoSyncVars = ArgoAppVars & {
7862
+ expectedConnection?: GitOpsConnection;
7863
+ isErrorShownInline?: () => boolean;
7408
7864
  resources?: Array<{
7409
7865
  group?: string;
7410
7866
  kind: string;
@@ -7565,6 +8021,7 @@ export const useArgoSync = createGitOpsMutation<ArgoSyncVars, boolean>({
7565
8021
  useRequestContext: useArgoSyncInheritance,
7566
8022
  getBody: argoSyncRequestBody,
7567
8023
  errorMessage: "Failed to trigger sync",
8024
+ isErrorShownInline: (variables) => variables.isErrorShownInline?.() ?? false,
7568
8025
  getSuccessMessage: (_data, v) => (v.dryRun ? "Dry run started" : "Sync initiated"),
7569
8026
  getInvalidateKeys: argoInvalidateKeys,
7570
8027
  });
@@ -7572,10 +8029,10 @@ export const useArgoSync = createGitOpsMutation<ArgoSyncVars, boolean>({
7572
8029
  export function useArgoResourceValidation() {
7573
8030
  const queryClient = useQueryClient();
7574
8031
  const serverInheritsOptions = useArgoSyncInheritance();
7575
- return useMutation<ArgoResourceValidationResult, Error, ArgoSyncVars>({
8032
+ return useMutation<ArgoResourceValidationResult, GitOpsActionError, ArgoSyncVars>({
7576
8033
  mutationFn: async (variables) => {
7577
8034
  const response = await apiFetch(
7578
- `${getApiBase()}/argo/applications/${variables.namespace}/${variables.name}/validate-resource`,
8035
+ apiUrl(`/argo/applications/${variables.namespace}/${variables.name}/validate-resource`),
7579
8036
  {
7580
8037
  method: "POST",
7581
8038
  headers: { "Content-Type": "application/json" },
@@ -7592,7 +8049,7 @@ export function useArgoResourceValidation() {
7592
8049
  );
7593
8050
  if (!response.ok) {
7594
8051
  const error = await readErrorBody(response);
7595
- throw new Error(error.error || `HTTP ${response.status}`);
8052
+ throw new GitOpsActionError(error, response.status);
7596
8053
  }
7597
8054
  return response.json() as Promise<ArgoResourceValidationResult>;
7598
8055
  },
@@ -7633,48 +8090,12 @@ export const useArgoResume = createGitOpsMutation<ArgoAppVars>({
7633
8090
  getInvalidateKeys: argoInvalidateKeys,
7634
8091
  });
7635
8092
 
7636
- // useArgoRefresh has a unique parameter (hard), so it's defined separately
7637
- export function useArgoRefresh() {
7638
- const queryClient = useQueryClient();
7639
-
7640
- return useMutation({
7641
- mutationFn: async ({
7642
- namespace,
7643
- name,
7644
- hard = false,
7645
- }: {
7646
- namespace: string;
7647
- name: string;
7648
- hard?: boolean;
7649
- }) => {
7650
- const params = hard ? "?type=hard" : "";
7651
- const response = await apiFetch(
7652
- `${getApiBase()}/argo/applications/${namespace}/${name}/refresh${params}`,
7653
- {
7654
- method: "POST",
7655
- },
7656
- );
7657
- if (!response.ok) {
7658
- const error = await readErrorBody(response);
7659
- throw new Error(error.error || `HTTP ${response.status}`);
7660
- }
7661
- return response.json();
7662
- },
7663
- meta: {
7664
- errorMessage: "Failed to refresh application",
7665
- successMessage: "Application refreshed",
7666
- },
7667
- onSuccess: (_, variables) => {
7668
- // Match the standard Argo invalidation set so the GitOps detail page
7669
- // (insights strip, resource tree) refetches after Refresh / Hard
7670
- // Refresh — without these two extra keys the user clicks Refresh and
7671
- // sees stale insight/tree data until the next staleTime tick.
7672
- argoInvalidateKeys(variables).forEach((key) =>
7673
- queryClient.invalidateQueries({ queryKey: key }),
7674
- );
7675
- },
7676
- });
7677
- }
8093
+ export const useArgoRefresh = createGitOpsMutation<ArgoAppVars & { hard?: boolean }>({
8094
+ getPath: ({ namespace, name, hard }) => `/argo/applications/${namespace}/${name}/refresh${hard ? "?type=hard" : ""}`,
8095
+ errorMessage: "Failed to refresh application",
8096
+ successMessage: "Application refreshed",
8097
+ getInvalidateKeys: argoInvalidateKeys,
8098
+ });
7678
8099
 
7679
8100
  // ============================================================================
7680
8101
  // Context Switching API hooks
@@ -8258,6 +8679,46 @@ export function useWorkloadPods(
8258
8679
  });
8259
8680
  }
8260
8681
 
8682
+ // POST /api/workflowtemplates/{namespace}/{name}/submit
8683
+ //
8684
+ // Creates a Workflow that runs the template, as the caller. When the request
8685
+ // fails without a definite answer (network error, timeout or 5xx), refreshes
8686
+ // the template's run list so the user can check whether the run started.
8687
+ export function useSubmitWorkflowTemplate() {
8688
+ const queryClient = useQueryClient();
8689
+ const { guard } = useRadarFeature("workflowTemplateSubmit");
8690
+ return useMutation({
8691
+ mutationFn: ({ namespace, name, runName, parameters }: WorkflowTemplateSubmission) =>
8692
+ guard(() =>
8693
+ fetchJSON<SubmittedWorkflow>(
8694
+ `/workflowtemplates/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}/submit`,
8695
+ {
8696
+ method: "POST",
8697
+ headers: { "Content-Type": "application/json" },
8698
+ body: JSON.stringify({
8699
+ ...(runName ? { name: runName } : {}),
8700
+ ...(Object.keys(parameters).length > 0 ? { parameters } : {}),
8701
+ }),
8702
+ },
8703
+ ),
8704
+ ),
8705
+ meta: { errorMessage: "Could not submit the workflow template" },
8706
+ onError: (error, variables) => {
8707
+ if (isAmbiguousSubmitError(error)) {
8708
+ void queryClient.invalidateQueries({
8709
+ queryKey: ["workload-runs", "workflowtemplates", variables.namespace, variables.name],
8710
+ });
8711
+ }
8712
+ },
8713
+ onSuccess: (run, variables) => {
8714
+ showApiSuccess("Workflow submitted", `${run.namespace}/${run.name}`);
8715
+ void queryClient.invalidateQueries({
8716
+ queryKey: ["workload-runs", "workflowtemplates", variables.namespace, variables.name],
8717
+ });
8718
+ },
8719
+ });
8720
+ }
8721
+
8261
8722
  export function useWorkloadRuns(
8262
8723
  kind: string,
8263
8724
  namespace: string,