@skyhook-io/k8s-ui 1.7.12 → 1.7.14

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 (41) hide show
  1. package/package.json +1 -1
  2. package/src/components/applications/AppChips.tsx +109 -0
  3. package/src/components/applications/AppTooltips.tsx +199 -0
  4. package/src/components/applications/ApplicationDetail.tsx +671 -0
  5. package/src/components/applications/ApplicationsList.tsx +569 -0
  6. package/src/components/applications/ReadyBar.tsx +22 -0
  7. package/src/components/applications/index.ts +8 -0
  8. package/src/components/audit/AuditFindingsTable.tsx +3 -25
  9. package/src/components/audit/index.ts +1 -1
  10. package/src/components/checks/ChecksView.tsx +269 -142
  11. package/src/components/checks/index.ts +14 -1
  12. package/src/components/issues/IssuesView.tsx +56 -17
  13. package/src/components/issues/index.ts +2 -2
  14. package/src/components/issues/issues.test.ts +7 -0
  15. package/src/components/issues/types.ts +15 -5
  16. package/src/components/logs/WorkloadLogsViewer.tsx +8 -5
  17. package/src/components/resources/renderers/WorkloadRenderer.tsx +5 -4
  18. package/src/components/shared/DetailShell.tsx +14 -7
  19. package/src/components/shared/EditableYamlView.tsx +37 -17
  20. package/src/components/shared/ResourceActionsBar.tsx +6 -6
  21. package/src/components/timeline/TimelineList.tsx +3 -32
  22. package/src/components/timeline/TimelineSwimlanes.tsx +3 -31
  23. package/src/components/topology/K8sResourceNode.tsx +26 -5
  24. package/src/components/topology/TopologyGraph.tsx +102 -3
  25. package/src/components/topology/layout.ts +36 -11
  26. package/src/components/ui/CenteredEmpty.tsx +27 -0
  27. package/src/components/ui/ForceDeleteConfirmDialog.tsx +1 -2
  28. package/src/components/ui/SearchBox.tsx +85 -0
  29. package/src/components/ui/drawer-components.tsx +8 -0
  30. package/src/components/ui/index.ts +1 -0
  31. package/src/components/workload/WorkloadView.tsx +170 -36
  32. package/src/components/workload/index.ts +1 -1
  33. package/src/hooks/useKeyboardShortcuts.tsx +3 -1
  34. package/src/index.ts +4 -0
  35. package/src/utils/applications.test.ts +207 -0
  36. package/src/utils/applications.ts +674 -0
  37. package/src/utils/format.ts +11 -0
  38. package/src/utils/index.ts +2 -0
  39. package/src/utils/topology-neighborhood.test.ts +185 -0
  40. package/src/utils/topology-neighborhood.ts +262 -0
  41. package/src/utils/workload-colors.ts +36 -0
@@ -3,6 +3,7 @@ import { flushSync } from 'react-dom'
3
3
  import { useRefreshAnimation } from '../../hooks/useRefreshAnimation'
4
4
  import { startViewTransitionSafe } from '../../utils/view-transition'
5
5
  import { FetchResult } from '../ui/FetchResult'
6
+ import { PaneLoader } from '../ui/PaneLoader'
6
7
  import { useRegisterShortcuts } from '../../hooks/useKeyboardShortcuts'
7
8
  import { clsx } from 'clsx'
8
9
  import {
@@ -19,11 +20,14 @@ import {
19
20
  Maximize2,
20
21
  X,
21
22
  BarChart3,
23
+ Network,
22
24
  } from 'lucide-react'
23
- import type { TimelineEvent, ResourceRef, Relationships, SelectedResource, ResolvedEnvFrom } from '../../types'
25
+ import type { TimelineEvent, ResourceRef, Relationships, SelectedResource, ResolvedEnvFrom, Topology, TopologyNode } from '../../types'
24
26
  import type { GitOpsStatus } from '../../types/gitops'
25
27
  import type { NavigateToResource } from '../../utils/navigation'
26
- import { refToSelectedResource, pluralToKind } from '../../utils/navigation'
28
+ import { refToSelectedResource, pluralToKind, kindToPlural, apiVersionToGroup } from '../../utils/navigation'
29
+ import { neighborhoodFor, seedNodeIds } from '../../utils/topology-neighborhood'
30
+ import { TopologyGraph } from '../topology/TopologyGraph'
27
31
  import { gitOpsOwnerFromRelationships, type GitOpsOwnerRef } from '../../utils/gitops-owner'
28
32
  import { gitOpsRouteForResource } from '../../utils/gitops-route'
29
33
  import { isChangeEvent, isHistoricalEvent } from '../../types'
@@ -47,9 +51,11 @@ import { EditableYamlView, SaveSuccessAnimation } from '../shared/EditableYamlVi
47
51
  import { ResourceRendererDispatch, getResourceStatus, type RendererOverrides } from '../shared/ResourceRendererDispatch'
48
52
  import { DetailShell, type DetailShellTab } from '../shared/DetailShell'
49
53
  import { HelmManagedByChip, ManagedByChip, type HelmOwnerRef } from '../shared/ManagedByChip'
50
- import { getKindColorOutline, formatKindName } from '../ui/drawer-components'
54
+ import { getKindColorOutline, displayKindName } from '../ui/drawer-components'
55
+ import { midTruncate } from '../../utils/format'
51
56
 
52
- type TabType = 'overview' | 'timeline' | 'logs' | 'metrics' | 'yaml'
57
+ export type WorkloadTabType = 'overview' | 'topology' | 'timeline' | 'logs' | 'metrics' | 'yaml'
58
+ type TabType = WorkloadTabType
53
59
 
54
60
  // ============================================================================
55
61
  // MAIN WORKLOAD VIEW — presentation only, data injected via props
@@ -81,11 +87,16 @@ interface WorkloadViewProps {
81
87
  * the Escape shortcut.
82
88
  */
83
89
  breadcrumb?: ReactNode
90
+ /** Suppress the standalone back arrow — for embeddings where "back" has no
91
+ * meaningful target (a single-workload app has no app graph to return to). */
92
+ hideBackButton?: boolean
84
93
  /**
85
94
  * Controls injected into the shell's tab-row scope slot — e.g. a cluster /
86
95
  * workload picker in Radar Cloud. Absent in standalone Radar.
87
96
  */
88
97
  scopeControls?: ReactNode
98
+ /** Hide WorkloadView's own breadcrumb/identity header when a host page owns that chrome. */
99
+ compactHeader?: boolean
89
100
 
90
101
  // ── Data (injected by wrapper) ──────────────────────────────────────────
91
102
  /** The resource data object */
@@ -107,8 +118,8 @@ interface WorkloadViewProps {
107
118
  allEvents?: TimelineEvent[]
108
119
  /** Whether timeline events are loading */
109
120
  eventsLoading?: boolean
110
- /** Topology data for hierarchy building */
111
- topology?: any
121
+ /** Topology data for hierarchy building + the Topology tab's neighborhood. */
122
+ topology?: Topology
112
123
  resourceFocusedK8sEvents?: TimelineEvent[]
113
124
  resourceFocusedUpdates?: TimelineEvent[]
114
125
  resourceFocusedEventsLoading?: boolean
@@ -118,6 +129,8 @@ interface WorkloadViewProps {
118
129
  // ── Capabilities ─────────────────────────────────────────────────────────
119
130
  /** Whether secrets can be updated */
120
131
  canUpdateSecrets?: boolean
132
+ /** Whether YAML editing should be disabled for read-only host surfaces. */
133
+ readOnlyYaml?: boolean
121
134
 
122
135
  // ── Mutations ────────────────────────────────────────────────────────────
123
136
  /** Update a resource from YAML */
@@ -183,6 +196,12 @@ interface WorkloadViewProps {
183
196
  }) => ReactNode
184
197
  /** Render the metrics tab content */
185
198
  renderMetricsTab?: (props: { kind: string; namespace: string; name: string }) => ReactNode
199
+ /** Render a read-only YAML view for a related object from the workload's
200
+ * neighborhood. Providing this turns the YAML tab into an object explorer
201
+ * (rail of the workload + its Services/config/policies/pods); omitting it
202
+ * keeps the single-manifest YAML tab. Injected because resource fetching
203
+ * lives host-side. */
204
+ renderRelatedYaml?: (ref: { kind: string; namespace: string; name: string; group?: string }) => ReactNode
186
205
  /** Whether metrics are available for this resource kind */
187
206
  isMetricsAvailable?: (kind: string, resource: any) => boolean
188
207
  /** Render extra content at the bottom of the overview tab (e.g. audit findings) */
@@ -218,7 +237,9 @@ export function WorkloadView({
218
237
  initialTab,
219
238
  group,
220
239
  breadcrumb,
240
+ hideBackButton,
221
241
  scopeControls,
242
+ compactHeader,
222
243
  // Data
223
244
  resource,
224
245
  relationships,
@@ -237,6 +258,7 @@ export function WorkloadView({
237
258
  resourceFocusedUpdatesError = null,
238
259
  // Capabilities
239
260
  canUpdateSecrets,
261
+ readOnlyYaml,
240
262
  // Mutations
241
263
  onUpdateResource,
242
264
  isUpdatingResource,
@@ -246,6 +268,7 @@ export function WorkloadView({
246
268
  onTabChange,
247
269
  // Render props
248
270
  renderLogsTab,
271
+ renderRelatedYaml,
249
272
  renderMetricsTab,
250
273
  isMetricsAvailable,
251
274
  // Duplicate
@@ -292,7 +315,6 @@ export function WorkloadView({
292
315
  // startViewTransitionSafe handles the API-missing fallback AND
293
316
  // swallows the InvalidStateError that the API rejects with when
294
317
  // a new transition supersedes an in-flight one (rapid clicks).
295
- // (SKY-833 bug 49)
296
318
  startViewTransitionSafe(() => flushSync(() => setShowYaml(yaml)))
297
319
  }, [])
298
320
 
@@ -317,10 +339,75 @@ export function WorkloadView({
317
339
  })
318
340
  }, [allEvents, topology, kind, namespace, name])
319
341
 
342
+ // Topology tab — the seeded neighborhood around this one workload (its
343
+ // ownership core + attached Services/config/policies), not the whole namespace.
344
+ const neighborhoodSeed = useMemo(() => [{ kind, namespace, name }], [kind, namespace, name])
345
+ const neighborhood = useMemo(
346
+ () => (topology ? neighborhoodFor(topology, neighborhoodSeed) : null),
347
+ [topology, neighborhoodSeed],
348
+ )
349
+ const neighborhoodFocusId = useMemo(
350
+ () => (topology ? seedNodeIds(topology, neighborhoodSeed)[0] : undefined),
351
+ [topology, neighborhoodSeed],
352
+ )
353
+
354
+ // The Topology tab stays visible while topology is loading (the pane shows a
355
+ // loader) and hides only when topology arrived and nothing matched the seed.
356
+ // A deep-linked ?tab=topology that turns out unavailable falls back to
357
+ // overview instead of rendering an empty body under a hidden tab.
358
+ const topologyTabHidden = !!topology && (!neighborhood || neighborhood.nodes.length === 0)
359
+ const effectiveTab: TabType = activeTab === 'topology' && topologyTabHidden ? 'overview' : activeTab
360
+
361
+ // YAML tab object rail — the same neighborhood, as a manifest list: the
362
+ // workload first, then routing → config → policy/scaling → ownership.
363
+ const yamlObjects = useMemo(() => {
364
+ if (!neighborhood) return []
365
+ const order: Record<string, number> = {
366
+ Service: 1, Ingress: 1, HTTPRoute: 1,
367
+ ConfigMap: 2, Secret: 2,
368
+ HorizontalPodAutoscaler: 3, PodDisruptionBudget: 3, NetworkPolicy: 3,
369
+ ReplicaSet: 4, Pod: 5,
370
+ }
371
+ return neighborhood.nodes
372
+ .filter((n) => n.kind !== 'Internet' && n.kind !== 'PodGroup')
373
+ .map((n) => ({
374
+ id: n.id,
375
+ kind: n.kind as string,
376
+ namespace: (n.data?.namespace as string) || namespace,
377
+ name: n.name,
378
+ group: apiVersionToGroup(n.data?.apiVersion as string | undefined),
379
+ primary: n.id === neighborhoodFocusId,
380
+ }))
381
+ .sort((a, b) =>
382
+ a.primary !== b.primary
383
+ ? (a.primary ? -1 : 1)
384
+ : (order[a.kind] ?? 9) - (order[b.kind] ?? 9) || a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name),
385
+ )
386
+ }, [neighborhood, neighborhoodFocusId, namespace])
387
+ // null = the workload's own manifest (the editable one).
388
+ const [yamlObjectId, setYamlObjectId] = useState<string | null>(null)
389
+ useEffect(() => setYamlObjectId(null), [kind, namespace, name])
390
+ const yamlObject = yamlObjectId ? yamlObjects.find((o) => o.id === yamlObjectId) : undefined
391
+ const handleTopologyNodeClick = useCallback(
392
+ (node: TopologyNode) => {
393
+ if (!onNavigateToResource || !node.kind || !node.name) return
394
+ onNavigateToResource({
395
+ kind: kindToPlural(node.kind),
396
+ namespace: (node.data?.namespace as string) || '',
397
+ name: node.name,
398
+ group: apiVersionToGroup(node.data?.apiVersion as string | undefined),
399
+ })
400
+ },
401
+ [onNavigateToResource],
402
+ )
403
+
320
404
  // Flatten events from hierarchy
321
405
  const resourceEvents = useMemo(() => {
322
406
  return getAllEventsFromHierarchy(resourceLanes)
323
407
  }, [resourceLanes])
408
+ const overviewEvents = resourceEvents.length > 0 ? resourceEvents : (resourceFocusedK8sEvents ?? [])
409
+ const overviewEventsLoading = resourceEvents.length > 0 ? eventsLoading : resourceFocusedEventsLoading
410
+ const overviewEventsError = resourceEvents.length > 0 ? undefined : resourceFocusedK8sError
324
411
 
325
412
  // Get pods from relationships and hierarchy
326
413
  const childPods = useMemo(() => {
@@ -446,6 +533,7 @@ export function WorkloadView({
446
533
  const showMetricsTab = isMetricsAvailable ? isMetricsAvailable(kind, resource) : false
447
534
  const tabs: DetailShellTab<TabType>[] = [
448
535
  { id: 'overview', label: 'Overview', icon: <Layers className="w-4 h-4" /> },
536
+ { id: 'topology', label: 'Topology', icon: <Network className="w-4 h-4" />, hidden: topologyTabHidden },
449
537
  {
450
538
  id: 'timeline',
451
539
  label: 'Timeline',
@@ -467,7 +555,7 @@ export function WorkloadView({
467
555
  <div className="flex items-center justify-between px-4 pt-3 pb-2">
468
556
  <div className="flex items-center gap-2 flex-wrap">
469
557
  <span className={clsx('badge', getKindColorOutline(apiKind))}>
470
- {formatKindName(apiKind)}
558
+ {displayKindName(apiKind, resource?.kind)}
471
559
  </span>
472
560
  {status && (
473
561
  <span className={clsx('badge', status.color)}>
@@ -548,6 +636,7 @@ export function WorkloadView({
548
636
  data={resource}
549
637
  onCopy={(text) => copyToClipboard(text, 'yaml')}
550
638
  copied={copied === 'yaml'}
639
+ readOnly={readOnlyYaml}
551
640
  onSaved={handleSaved}
552
641
  onSave={onUpdateResource}
553
642
  isSaving={isUpdatingResource}
@@ -593,7 +682,7 @@ export function WorkloadView({
593
682
  <DetailShell
594
683
  breadcrumb={breadcrumb}
595
684
  nav={
596
- breadcrumb ? undefined : (
685
+ breadcrumb || hideBackButton ? undefined : (
597
686
  <button
598
687
  onClick={onBack}
599
688
  className="p-1.5 mt-0.5 text-theme-text-secondary hover:text-theme-text-primary hover:bg-theme-elevated rounded-lg transition-colors"
@@ -617,7 +706,7 @@ export function WorkloadView({
617
706
  </div>
618
707
  <div className="flex items-center gap-3 text-sm text-theme-text-secondary">
619
708
  <span className={clsx('badge', getKindColorOutline(apiKind))}>
620
- {formatKindName(apiKind)}
709
+ {displayKindName(apiKind, resource?.kind)}
621
710
  </span>
622
711
  {status && (
623
712
  <span className={clsx('badge', status.color)}>
@@ -673,13 +762,14 @@ export function WorkloadView({
673
762
  </>
674
763
  }
675
764
  tabs={tabs}
676
- activeTab={activeTab}
765
+ activeTab={effectiveTab}
677
766
  onTabChange={handleSetTab}
678
767
  scopeControls={scopeControls}
679
768
  tabStripEnd={<ResourceActionsBar resource={selectedResource} data={resource} hideLogs {...actionsBarProps} />}
680
769
  overlay={saveSuccess ? <SaveSuccessAnimation /> : null}
770
+ compactHeader={compactHeader}
681
771
  >
682
- {activeTab === 'overview' && (
772
+ {effectiveTab === 'overview' && (
683
773
  <InfoTab
684
774
  resource={resource}
685
775
  selectedResource={selectedResource}
@@ -695,15 +785,32 @@ export function WorkloadView({
695
785
  onSwitchToTimeline={() => handleSetTab('timeline')}
696
786
  rendererOverrides={rendererOverrides}
697
787
  resolvedEnvFrom={resolvedEnvFrom}
698
- events={resourceFocusedK8sEvents}
699
- eventsLoading={resourceFocusedEventsLoading}
788
+ events={overviewEvents}
789
+ eventsLoading={overviewEventsLoading}
700
790
  updates={resourceFocusedUpdates}
701
- eventsError={resourceFocusedK8sError}
791
+ eventsError={overviewEventsError}
702
792
  updatesError={resourceFocusedUpdatesError}
703
793
  extraContent={renderOverviewExtra && renderOverviewExtra({ kind, namespace, name })}
704
794
  />
705
795
  )}
706
- {activeTab === 'timeline' && (
796
+ {effectiveTab === 'topology' && (
797
+ <div className="relative h-full min-h-0 w-full">
798
+ {topology ? (
799
+ <TopologyGraph
800
+ topology={neighborhood}
801
+ viewMode="resources"
802
+ groupingMode="namespace"
803
+ hideGroupHeader
804
+ onNodeClick={handleTopologyNodeClick}
805
+ showExportButton={false}
806
+ focusNodeId={neighborhoodFocusId}
807
+ />
808
+ ) : (
809
+ <PaneLoader label="Loading topology…" className="absolute inset-0" />
810
+ )}
811
+ </div>
812
+ )}
813
+ {effectiveTab === 'timeline' && (
707
814
  <EventsTab
708
815
  events={resourceEvents}
709
816
  resourceLanes={resourceLanes}
@@ -716,7 +823,7 @@ export function WorkloadView({
716
823
  onSelectEvent={setSelectedEventId}
717
824
  />
718
825
  )}
719
- {activeTab === 'logs' && renderLogsTab && (
826
+ {effectiveTab === 'logs' && renderLogsTab && (
720
827
  renderLogsTab({
721
828
  kind,
722
829
  apiKind,
@@ -730,29 +837,56 @@ export function WorkloadView({
730
837
  onConsumeInitialContainer: () => setInitialContainer(null),
731
838
  })
732
839
  )}
733
- {activeTab === 'metrics' && renderMetricsTab && (
840
+ {effectiveTab === 'metrics' && renderMetricsTab && (
734
841
  <div className="h-full overflow-auto p-4">
735
842
  {renderMetricsTab({ kind: resource?.kind || kind, namespace, name })}
736
843
  </div>
737
844
  )}
738
- {activeTab === 'yaml' && (
739
- <div className="h-full overflow-auto">
740
- {!resource ? (
741
- <FetchResult loading={resourceLoading} error={resourceError} className="h-32" />
742
- ) : (
743
- <EditableYamlView
744
- resource={selectedResource}
745
- data={resource}
746
- onCopy={(text) => copyToClipboard(text, 'yaml')}
747
- copied={copied === 'yaml'}
748
- onSaved={handleSaved}
749
- onSave={onUpdateResource}
750
- isSaving={isUpdatingResource}
751
- saveError={updateResourceError}
752
- onDuplicate={onDuplicate}
753
- onDownload={onDownload}
754
- />
845
+ {effectiveTab === 'yaml' && (
846
+ <div className="flex h-full min-h-0">
847
+ {renderRelatedYaml && yamlObjects.length > 1 && (
848
+ <div className="flex w-56 shrink-0 flex-col gap-0.5 overflow-y-auto border-r border-theme-border bg-theme-base px-2 py-2">
849
+ <div className="px-1.5 pb-1 pt-0.5 text-[10px] font-medium uppercase tracking-wide text-theme-text-tertiary">Objects</div>
850
+ {yamlObjects.map((o) => {
851
+ const active = o.primary ? yamlObjectId === null : yamlObjectId === o.id
852
+ return (
853
+ <button
854
+ key={o.id}
855
+ type="button"
856
+ onClick={() => setYamlObjectId(o.primary ? null : o.id)}
857
+ className={clsx(
858
+ 'flex w-full flex-col rounded-md px-1.5 py-1.5 text-left transition-colors',
859
+ active ? 'selection selection-ring' : 'hover:bg-theme-hover',
860
+ )}
861
+ >
862
+ <span className="truncate text-xs font-medium text-theme-text-primary">{midTruncate(o.name, 26)}</span>
863
+ <span className="text-[10px] uppercase tracking-wide text-theme-text-tertiary">{o.kind}</span>
864
+ </button>
865
+ )
866
+ })}
867
+ </div>
755
868
  )}
869
+ <div className="h-full min-w-0 flex-1 overflow-auto">
870
+ {yamlObject && !yamlObject.primary && renderRelatedYaml ? (
871
+ renderRelatedYaml(yamlObject)
872
+ ) : !resource ? (
873
+ <FetchResult loading={resourceLoading} error={resourceError} className="h-32" />
874
+ ) : (
875
+ <EditableYamlView
876
+ resource={selectedResource}
877
+ data={resource}
878
+ onCopy={(text) => copyToClipboard(text, 'yaml')}
879
+ copied={copied === 'yaml'}
880
+ readOnly={readOnlyYaml}
881
+ onSaved={handleSaved}
882
+ onSave={onUpdateResource}
883
+ isSaving={isUpdatingResource}
884
+ saveError={updateResourceError}
885
+ onDuplicate={onDuplicate}
886
+ onDownload={onDownload}
887
+ />
888
+ )}
889
+ </div>
756
890
  </div>
757
891
  )}
758
892
  </DetailShell>
@@ -1240,7 +1374,7 @@ function InfoTab({
1240
1374
  onClick={onSwitchToTimeline}
1241
1375
  className="text-xs text-theme-text-tertiary hover:text-theme-text-secondary transition-colors"
1242
1376
  >
1243
- These are events for this resource only. Switch to the <span className="underline">Timeline</span> tab to see events across all related resources.
1377
+ Showing recent events across this workload. Switch to the <span className="underline">Timeline</span> tab for full history and resource relationships.
1244
1378
  </button>
1245
1379
  )}
1246
1380
  renderSidebar={(sidebarSections) => (
@@ -1,2 +1,2 @@
1
- export { WorkloadView } from './WorkloadView'
1
+ export { WorkloadView, type WorkloadTabType } from './WorkloadView'
2
2
  export { ResourceDetailDrawer } from './ResourceDetailDrawer'
@@ -1,6 +1,6 @@
1
1
  import { createContext, useContext, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
2
2
 
3
- export type ShortcutScope = 'global' | 'topology' | 'resources' | 'timeline' | 'helm' | 'gitops' | 'traffic' | 'drawer'
3
+ export type ShortcutScope = 'global' | 'topology' | 'resources' | 'timeline' | 'helm' | 'gitops' | 'traffic' | 'applications' | 'audit' | 'drawer'
4
4
 
5
5
  // Scope priority: higher number = higher priority (wins when multiple scopes active)
6
6
  const SCOPE_PRIORITY: Record<ShortcutScope, number> = {
@@ -11,6 +11,8 @@ const SCOPE_PRIORITY: Record<ShortcutScope, number> = {
11
11
  helm: 1,
12
12
  gitops: 1,
13
13
  traffic: 1,
14
+ applications: 1,
15
+ audit: 1,
14
16
  drawer: 2,
15
17
  }
16
18
 
package/src/index.ts CHANGED
@@ -53,6 +53,10 @@ export * from './components/issues'
53
53
  // Cluster switcher (shared trigger+dropdown for OSS Radar and Radar Hub)
54
54
  export * from './components/cluster-switcher'
55
55
 
56
+ // Applications (shared host-agnostic list + detail shell for the deployable-
57
+ // software surface; OSS renders single-cluster, Cloud adds the fleet layer)
58
+ export * from './components/applications'
59
+
56
60
  // Compare (ResourceCompareView, CompareResourcePicker, normalize utilities)
57
61
  export * from './components/compare'
58
62
 
@@ -0,0 +1,207 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { compareVersions, appGroupLagMessage, matchWorkloadAcrossInstances, foldAppGroups, identityEnvInferred, type AppGroupFoldEntry } from './applications'
3
+
4
+ describe('compareVersions', () => {
5
+ it('orders semver', () => {
6
+ expect(compareVersions('1.2.0', '1.10.0')).toBe(-1)
7
+ expect(compareVersions('v2.0.0', 'v2.0.0')).toBe(0)
8
+ })
9
+
10
+ // Date-stamped CI tags are the dominant shape on real clusters
11
+ // (main_2026-03-26_05) — semver-only made promotion lag inert on them.
12
+ it('orders same-prefix date-stamped tags by date then sequence', () => {
13
+ expect(compareVersions('main_2026-03-26_05', 'main_2026-06-02_03')).toBe(-1)
14
+ expect(compareVersions('main_2026-06-02_03', 'main_2026-06-02_01')).toBe(1)
15
+ expect(compareVersions('main_2026-06-02_03', 'main_2026-06-02_03')).toBe(0)
16
+ })
17
+
18
+ it('refuses date tags with different prefixes', () => {
19
+ expect(compareVersions('main_2026-06-02_03', 'hotfix_2026-06-02_03')).toBeNull()
20
+ expect(compareVersions('billing_main_2026-05-18_00', 'project-infra_main_2026-06-05_01')).toBeNull()
21
+ })
22
+
23
+ it('refuses mixed date-tag vs non-date and unparseable input', () => {
24
+ expect(compareVersions('main_2026-06-02_03', '1.2.0')).toBeNull()
25
+ expect(compareVersions('latest', 'abc123')).toBeNull()
26
+ expect(compareVersions(undefined, '1.0.0')).toBeNull()
27
+ })
28
+
29
+ it('handles long compound prefixes as one prefix', () => {
30
+ expect(compareVersions('billing_main_2026-05-18_00', 'billing_main_2026-06-05_01')).toBe(-1)
31
+ })
32
+ })
33
+
34
+ // The lag arrow is the trust-fatal output: direction, unranked exclusion, and
35
+ // same-env refusal each have a distinct silent-inversion failure mode.
36
+ describe('appGroupLagMessage', () => {
37
+ it('fires when a strictly-lower env runs a strictly-newer version, with correct direction', () => {
38
+ expect(appGroupLagMessage([
39
+ { env: 'dev', version: '2.0.0' },
40
+ { env: 'staging', version: '1.0.0' },
41
+ ])).toBe('staging is behind dev')
42
+ })
43
+
44
+ it('does not fire when the higher env is newer (healthy promotion)', () => {
45
+ expect(appGroupLagMessage([
46
+ { env: 'dev', version: '1.0.0' },
47
+ { env: 'staging', version: '2.0.0' },
48
+ ])).toBeNull()
49
+ })
50
+
51
+ it('never draws arrows through unranked (discovered) envs', () => {
52
+ expect(appGroupLagMessage([
53
+ { env: 'qa', version: '9.0.0' },
54
+ { env: 'prod', version: '1.0.0' },
55
+ ])).toBeNull()
56
+ })
57
+
58
+ it('never compares two instances of the same env', () => {
59
+ expect(appGroupLagMessage([
60
+ { env: 'prod', version: '2.0.0' },
61
+ { env: 'prod', version: '1.0.0' },
62
+ ])).toBeNull()
63
+ })
64
+
65
+ it('treats missing or incomparable versions as no signal', () => {
66
+ expect(appGroupLagMessage([{ env: 'dev' }, { env: 'prod', version: '1.0.0' }])).toBeNull()
67
+ expect(appGroupLagMessage([
68
+ { env: 'dev', version: 'latest' },
69
+ { env: 'prod', version: '1.0.0' },
70
+ ])).toBeNull()
71
+ })
72
+
73
+ it('orders date-stamped CI tags through the ladder', () => {
74
+ expect(appGroupLagMessage([
75
+ { env: 'dev', version: 'main_2026-06-07_02' },
76
+ { env: 'staging', version: 'main_2026-03-26_05' },
77
+ ])).toBe('staging is behind dev')
78
+ })
79
+ })
80
+
81
+ describe('identityEnvInferred', () => {
82
+ it('marks only namespace-derived identity envs as inferred', () => {
83
+ expect(identityEnvInferred({ key: 'billing', env: 'staging', confidence: 'medium', evidence: 'namespace stem "billing" + shared image repo repo/app' })).toBe(true)
84
+ expect(identityEnvInferred({ key: 'billing', env: 'staging', confidence: 'medium', evidence: 'name stem "billing" + shared image repo repo/app' })).toBe(false)
85
+ expect(identityEnvInferred({ key: 'billing', env: 'staging', confidence: 'medium', evidence: 'environment label "staging" + name/repo evidence' })).toBe(false)
86
+ expect(identityEnvInferred({ key: 'billing', env: 'staging', confidence: 'high', evidence: 'Argo CD source path billing (env overlay staging)' })).toBe(false)
87
+ })
88
+ })
89
+
90
+ // Position-preserving env switch: exact match, stem fallback (suffix, prefix,
91
+ // discovered tokens), and the explicit no-counterpart null.
92
+ describe('matchWorkloadAcrossInstances', () => {
93
+ const dep = (name: string, namespace = 'staging') => ({ kind: 'Deployment', namespace, name })
94
+
95
+ it('prefers the exact kind+name match', () => {
96
+ expect(matchWorkloadAcrossInstances('Deployment/dev/billing', [dep('billing')])).toEqual(dep('billing'))
97
+ })
98
+
99
+ it('prefers namespace-specific exact matches and refuses ambiguous same-name matches', () => {
100
+ expect(matchWorkloadAcrossInstances('Deployment/dev/billing', [dep('billing', 'prod'), dep('billing', 'dev')])).toEqual(dep('billing', 'dev'))
101
+ expect(matchWorkloadAcrossInstances('Deployment/dev/billing', [dep('billing', 'prod'), dep('billing', 'staging')])).toBeNull()
102
+ })
103
+
104
+ it('falls back to the env-affix-stripped stem (suffix and prefix)', () => {
105
+ expect(matchWorkloadAcrossInstances('Deployment/dev/billing-dev', [dep('billing-staging')])).toEqual(dep('billing-staging'))
106
+ expect(matchWorkloadAcrossInstances('Deployment/qa/qa-koala', [dep('staging-koala')])).toEqual(dep('staging-koala'))
107
+ })
108
+
109
+ it('strips discovered env tokens passed via extraTokens', () => {
110
+ const tokens = new Set(['loadtest'])
111
+ expect(matchWorkloadAcrossInstances('Deployment/team/api-loadtest', [dep('api', 'dev')], tokens)).toEqual(dep('api', 'dev'))
112
+ expect(matchWorkloadAcrossInstances('Deployment/team/api-loadtest', [dep('api', 'dev')])).toBeNull()
113
+ })
114
+
115
+ it('returns null when no counterpart exists', () => {
116
+ expect(matchWorkloadAcrossInstances('Deployment/dev/billing', [dep('finops')])).toBeNull()
117
+ expect(matchWorkloadAcrossInstances('garbage', [dep('billing')])).toBeNull()
118
+ })
119
+ })
120
+
121
+ // foldAppGroups pins the collapse experiment's safety rails — each fails
122
+ // silently in a component-embedded loop.
123
+ describe('foldAppGroups', () => {
124
+ const entry = (key: string, name: string, famEnv?: string, over: Partial<AppGroupFoldEntry> = {}): AppGroupFoldEntry => ({
125
+ row: { key, name, identity: famEnv ? { key: 'billing', env: famEnv, confidence: 'medium', evidence: 'e' } : undefined },
126
+ health: 'healthy',
127
+ versions: [],
128
+ ready: 1,
129
+ desired: 1,
130
+ kinds: { Deployment: 1 },
131
+ classComposition: [{ cls: 'service', count: 1 }],
132
+ ...over,
133
+ })
134
+
135
+ it('folds app group members into one ladder row with instances hidden by default', () => {
136
+ const rows = foldAppGroups([entry('a', 'billing', 'dev'), entry('b', 'billing-staging', 'staging'), entry('c', 'lonely')], new Set(), false)
137
+ expect(rows.map((r) => r.kind)).toEqual(['group', 'instance'])
138
+ const group = rows[0] as Extract<(typeof rows)[0], { kind: 'group' }>
139
+ expect(group.label).toBe('billing')
140
+ expect(group.cells.map((c) => c.env)).toEqual(['dev', 'staging'])
141
+ expect(group.ready).toBe(2)
142
+ })
143
+
144
+ it('renders a filter-orphaned member as the plain instance it is', () => {
145
+ const rows = foldAppGroups([entry('a', 'billing', 'dev')], new Set(), false)
146
+ expect(rows).toEqual([{ kind: 'instance', entry: entry('a', 'billing', 'dev') }])
147
+ })
148
+
149
+ it('search auto-expansion emits the member rows', () => {
150
+ const rows = foldAppGroups([entry('a', 'billing', 'dev'), entry('b', 'billing-staging', 'staging')], new Set(), true)
151
+ expect(rows.map((r) => r.kind)).toEqual(['group', 'instance', 'instance'])
152
+ expect(rows.filter((r) => r.kind === 'instance').every((r) => (r as { child?: boolean }).child)).toBe(true)
153
+ })
154
+
155
+ it('aggregates same-env instances into one cell: count, worst health, newest version', () => {
156
+ const rows = foldAppGroups(
157
+ [
158
+ entry('a', 'billing', 'staging', { versions: ['1.0.0'], health: 'healthy' }),
159
+ entry('b', 'billing-2', 'staging', { versions: ['2.0.0'], health: 'unhealthy' }),
160
+ entry('c', 'billing-dev', 'dev'),
161
+ ],
162
+ new Set(),
163
+ false,
164
+ )
165
+ const group = rows[0] as Extract<(typeof rows)[0], { kind: 'group' }>
166
+ const staging = group.cells.find((c) => c.env === 'staging')!
167
+ expect(staging.count).toBe(2)
168
+ expect(staging.health).toBe('unhealthy')
169
+ expect(staging.version).toBe('2.0.0')
170
+ })
171
+
172
+ it('derives the group workload class like the server: service+worker collapses, jobs make mixed', () => {
173
+ const mk = (cls: 'service' | 'worker' | 'job', key: string, env: string) =>
174
+ entry(key, key, env, { classComposition: [{ cls, count: 1 }] })
175
+ const sw = foldAppGroups([mk('service', 'a', 'dev'), mk('worker', 'b', 'staging')], new Set(), false)
176
+ expect((sw[0] as { workloadClass?: string }).workloadClass).toBe('service')
177
+ const sj = foldAppGroups([mk('service', 'a', 'dev'), mk('job', 'b', 'staging')], new Set(), false)
178
+ expect((sj[0] as { workloadClass?: string }).workloadClass).toBe('mixed')
179
+ })
180
+
181
+ it('scopes non-portable identities but folds portable identities across scopes', () => {
182
+ const portable = (key: string, name: string, env: string): AppGroupFoldEntry => ({
183
+ ...entry(key, name, env),
184
+ row: { key, name, identity: { key: 'billing', env, confidence: 'high', evidence: 'e', portable: true } },
185
+ })
186
+
187
+ const oss = foldAppGroups(
188
+ [portable('a', 'billing', 'dev'), entry('b', 'billing-staging', 'staging')],
189
+ new Set(),
190
+ false,
191
+ )
192
+ expect(oss.map((r) => r.kind)).toEqual(['group'])
193
+
194
+ const local = foldAppGroups(
195
+ [entry('a', 'billing', 'dev'), entry('b', 'billing-staging', 'staging')],
196
+ new Set(),
197
+ false,
198
+ { localScope: (e) => e.row.key },
199
+ )
200
+ expect(local.map((r) => r.kind)).toEqual(['instance', 'instance'])
201
+
202
+ const grouped = foldAppGroups([portable('a', 'billing', 'dev'), portable('b', 'billing-staging', 'staging')], new Set(), false, {
203
+ localScope: (e) => e.row.key,
204
+ })
205
+ expect(grouped.map((r) => r.kind)).toEqual(['group'])
206
+ })
207
+ })