@skyhook-io/radar-app 1.19.0 → 1.20.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 (173) hide show
  1. package/README.md +1 -1
  2. package/package.json +5 -5
  3. package/src/App.tsx +31 -5
  4. package/src/api/application-evidence.ts +63 -0
  5. package/src/api/argoSync.test.ts +22 -0
  6. package/src/api/client.audit-gating.test.tsx +48 -0
  7. package/src/api/client.kueuePosition.test.ts +32 -0
  8. package/src/api/client.kueueQueueWorkloads.test.tsx +71 -0
  9. package/src/api/client.resource-identity.test.ts +3 -0
  10. package/src/api/client.resourceIssues.test.tsx +239 -0
  11. package/src/api/client.resourcePath.test.ts +3 -0
  12. package/src/api/client.ts +285 -55
  13. package/src/api/config.ts +21 -0
  14. package/src/api/diagnose.ts +4 -0
  15. package/src/api/radarFeatures.render.test.tsx +33 -1
  16. package/src/api/radarFeatures.test.ts +47 -0
  17. package/src/api/radarFeatures.ts +40 -1
  18. package/src/api/rbac.settled.test.tsx +42 -0
  19. package/src/api/rbac.test.ts +18 -0
  20. package/src/api/rbac.ts +37 -7
  21. package/src/api/traffic.ts +9 -4
  22. package/src/api/usage-data.fixtures.ts +3 -1
  23. package/src/api/usage-data.test.tsx +134 -0
  24. package/src/api/usage-data.ts +35 -7
  25. package/src/api/workloadPodsPolling.test.ts +26 -0
  26. package/src/components/CloudConnectFlow.test.tsx +86 -0
  27. package/src/components/CloudConnectFlow.tsx +65 -27
  28. package/src/components/CloudFunnelButton.test.tsx +140 -5
  29. package/src/components/CloudFunnelButton.tsx +50 -9
  30. package/src/components/ConnectionErrorView.test.tsx +34 -0
  31. package/src/components/ConnectionErrorView.tsx +35 -11
  32. package/src/components/ContextSwitcher.tsx +5 -2
  33. package/src/components/SwitchAwareConnectionError.test.tsx +43 -0
  34. package/src/components/SwitchAwareConnectionError.tsx +85 -0
  35. package/src/components/application-evidence/ApplicationEvidenceAction.flow.test.tsx +234 -0
  36. package/src/components/application-evidence/ApplicationEvidenceAction.test.tsx +144 -0
  37. package/src/components/application-evidence/ApplicationEvidenceAction.tsx +218 -0
  38. package/src/components/capacity/CapacityDemand.tsx +3 -2
  39. package/src/components/capacity/demandSummary.test.ts +38 -0
  40. package/src/components/capacity/shared.tsx +12 -1
  41. package/src/components/cost/ApplicationCostTab.tsx +4 -0
  42. package/src/components/cost/CostTrendChart.tsx +2 -0
  43. package/src/components/cost/WorkloadCostTab.tsx +4 -0
  44. package/src/components/cost/source.test.ts +5 -0
  45. package/src/components/cost/source.ts +11 -0
  46. package/src/components/diagnose/AIMarkdown.tsx +3 -0
  47. package/src/components/diagnose/AgentSetupNotice.test.tsx +17 -0
  48. package/src/components/diagnose/AgentSetupNotice.tsx +21 -3
  49. package/src/components/diagnose/ContinueInAgentButton.mounted.test.tsx +182 -0
  50. package/src/components/diagnose/ContinueInAgentButton.test.tsx +128 -0
  51. package/src/components/diagnose/ContinueInAgentButton.tsx +303 -0
  52. package/src/components/diagnose/DiagnoseContext.question.test.tsx +1 -1
  53. package/src/components/diagnose/DiagnoseContext.tsx +68 -2
  54. package/src/components/diagnose/DiagnoseSurface.tsx +58 -113
  55. package/src/components/diagnose/ExampleInvestigationLink.tsx +20 -0
  56. package/src/components/diagnose/Home.test.tsx +26 -0
  57. package/src/components/diagnose/Home.tsx +20 -1
  58. package/src/components/diagnose/InvestigationEvidenceSections.tsx +45 -22
  59. package/src/components/diagnose/InvestigationView.tsx +94 -26
  60. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +450 -0
  61. package/src/components/diagnose/LocalDiagnoseAction.tsx +354 -35
  62. package/src/components/diagnose/NextStepJump.test.tsx +92 -0
  63. package/src/components/diagnose/NextStepJump.tsx +75 -0
  64. package/src/components/diagnose/QuestionComposer.tsx +8 -0
  65. package/src/components/diagnose/exampleInvestigation.events.json +191 -0
  66. package/src/components/diagnose/exampleInvestigation.loadFailure.test.tsx +94 -0
  67. package/src/components/diagnose/exampleInvestigation.test.tsx +248 -0
  68. package/src/components/diagnose/exampleInvestigation.ts +121 -0
  69. package/src/components/diagnose/investigationCase.test.tsx +9 -1
  70. package/src/components/diagnose/investigationEvidence/adapters/applicationFindings.test.ts +739 -0
  71. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +50 -2
  72. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +9 -0
  73. package/src/components/diagnose/investigationEvidence/builder.ts +30 -0
  74. package/src/components/diagnose/investigationEvidence/observations.ts +121 -2
  75. package/src/components/diagnose/investigationEvidence/projection.test.ts +85 -3
  76. package/src/components/diagnose/investigationEvidence/types.ts +5 -0
  77. package/src/components/diagnose/investigationState.ts +28 -0
  78. package/src/components/diagnose/lastInvestigation.test.ts +95 -0
  79. package/src/components/diagnose/lastInvestigation.ts +58 -0
  80. package/src/components/diagnose/launch.test.ts +125 -1
  81. package/src/components/diagnose/launch.ts +57 -10
  82. package/src/components/diagnose/toolCallLabel.test.ts +10 -4
  83. package/src/components/execution/BatchExecutionView.tsx +24 -11
  84. package/src/components/execution/JobSetAdmission.test.tsx +42 -0
  85. package/src/components/execution/JobSetAdmission.tsx +18 -3
  86. package/src/components/execution/JobSetMemberComparison.tsx +2 -1
  87. package/src/components/execution/runState.test.ts +14 -0
  88. package/src/components/execution/runState.ts +8 -0
  89. package/src/components/gitops/GitOpsView.rollbackGate.test.tsx +202 -0
  90. package/src/components/gitops/GitOpsView.syncRequest.test.tsx +369 -0
  91. package/src/components/gitops/GitOpsView.tsx +86 -17
  92. package/src/components/gitops/RemoteDestinationCloudHint.tsx +2 -3
  93. package/src/components/gitops/destination-toast.test.ts +1 -1
  94. package/src/components/gitops/destination-toast.ts +2 -2
  95. package/src/components/home/ClusterHealthCard.tsx +1 -1
  96. package/src/components/home/HomeAgentBlock.test.tsx +31 -3
  97. package/src/components/home/HomeAgentBlock.tsx +13 -4
  98. package/src/components/home/HomeDiagramCard.tsx +47 -0
  99. package/src/components/home/HomeView.tsx +81 -41
  100. package/src/components/home/MCPSetupDialog.test.tsx +95 -5
  101. package/src/components/home/MCPSetupDialog.tsx +30 -5
  102. package/src/components/home/ProblemsPanel.investigate.test.tsx +171 -0
  103. package/src/components/home/ProblemsPanel.test.tsx +3 -1
  104. package/src/components/home/TopologyPreview.test.tsx +73 -0
  105. package/src/components/home/TopologyPreview.tsx +120 -233
  106. package/src/components/home/TrafficSummary.test.tsx +63 -0
  107. package/src/components/home/TrafficSummary.tsx +135 -138
  108. package/src/components/home/mcpToolCatalog.ts +23 -10
  109. package/src/components/issues/IssuesPane.test.ts +11 -0
  110. package/src/components/issues/IssuesPane.tsx +15 -5
  111. package/src/components/issues/uncheckedSources.test.ts +20 -1
  112. package/src/components/issues/uncheckedSources.ts +18 -0
  113. package/src/components/kueue/KueuePendingPosition.tsx +35 -0
  114. package/src/components/kueue/useRelatedObjects.test.tsx +219 -0
  115. package/src/components/kueue/useRelatedReads.test.ts +56 -0
  116. package/src/components/kueue/useRelatedReads.ts +205 -0
  117. package/src/components/logs/MultiPodLogsTab.test.tsx +93 -0
  118. package/src/components/logs/MultiPodLogsTab.tsx +120 -0
  119. package/src/components/logs/PodLogsUnavailable.test.tsx +18 -0
  120. package/src/components/logs/PodLogsUnavailable.tsx +21 -0
  121. package/src/components/logs/RayClusterLogsTab.reselect.test.tsx +67 -0
  122. package/src/components/logs/RayClusterLogsTab.test.tsx +167 -0
  123. package/src/components/logs/RayClusterLogsTab.tsx +109 -0
  124. package/src/components/logs/ScheduledWorkloadLogsViewer.tsx +3 -2
  125. package/src/components/logs/rayClusterPods.ts +32 -0
  126. package/src/components/outageSince.test.ts +21 -0
  127. package/src/components/outageSince.ts +10 -0
  128. package/src/components/resource/PrometheusCharts.overlays.test.ts +12 -0
  129. package/src/components/resource/PrometheusCharts.tsx +3 -40
  130. package/src/components/resources/crd/CRDSchemaTab.test.tsx +28 -0
  131. package/src/components/resources/crd/CRDSchemaTab.tsx +13 -0
  132. package/src/components/resources/crd/host.tsx +14 -0
  133. package/src/components/resources/renderers/CustomResourceDefinitionRenderer.test.tsx +27 -0
  134. package/src/components/resources/renderers/CustomResourceDefinitionRenderer.tsx +12 -0
  135. package/src/components/resources/renderers/JobAdmissionRenderers.test.tsx +4 -1
  136. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +4 -3
  137. package/src/components/resources/renderers/KueueHostRenderers.test.tsx +117 -0
  138. package/src/components/resources/renderers/KueueQueueRenderers.test.tsx +97 -0
  139. package/src/components/resources/renderers/KueueQueueRenderers.tsx +139 -0
  140. package/src/components/resources/renderers/KueueWorkloadRenderer.test.tsx +7 -1
  141. package/src/components/resources/renderers/KueueWorkloadRenderer.tsx +47 -7
  142. package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.test.tsx +67 -0
  143. package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.tsx +31 -0
  144. package/src/components/resources/renderers/RayClusterRenderer.test.tsx +81 -3
  145. package/src/components/resources/renderers/RayClusterRenderer.tsx +19 -4
  146. package/src/components/traffic/TrafficView.tsx +3 -3
  147. package/src/components/ui/command-items-crd.test.tsx +23 -0
  148. package/src/components/ui/command-items.ts +2 -1
  149. package/src/components/useContextSwitchFlow.test.tsx +61 -0
  150. package/src/components/useContextSwitchFlow.tsx +21 -4
  151. package/src/components/whats-new/WhatsNew.test.ts +10 -3
  152. package/src/components/whats-new/WhatsNew.tsx +5 -1
  153. package/src/components/whats-new/WhatsNewDialog.test.tsx +17 -3
  154. package/src/components/whats-new/releaseNotes.ts +77 -4
  155. package/src/components/workload/RelatedFindingsSection.test.tsx +126 -0
  156. package/src/components/workload/RelatedFindingsSection.tsx +80 -0
  157. package/src/components/workload/WorkloadView.test.ts +10 -1
  158. package/src/components/workload/WorkloadView.tsx +85 -98
  159. package/src/components/workload/issueResourceOpener.test.ts +20 -0
  160. package/src/components/workload/issueResourceOpener.ts +17 -0
  161. package/src/context/ConnectionContext.tsx +133 -60
  162. package/src/context/ConnectionProvider.retry.test.tsx +176 -0
  163. package/src/context/ContextSwitchContext.tsx +14 -1
  164. package/src/context/DiagnoseCustomization.tsx +3 -0
  165. package/src/context/clusterConnected.ts +10 -0
  166. package/src/contexts/CapabilitiesContext.tsx +6 -4
  167. package/src/hooks/useElementSize.ts +30 -0
  168. package/src/integrations/resourceHost.test.tsx +1 -0
  169. package/src/integrations/resourceHost.ts +5 -1
  170. package/src/integrations/resourceHosts.test.tsx +21 -4
  171. package/src/integrations/resourceHosts.tsx +12 -0
  172. package/src/main.tsx +5 -0
  173. package/src/utils/related-findings.ts +46 -0
@@ -41,6 +41,7 @@ import {
41
41
  investigationPaneCenteredScrollTop,
42
42
  canStopInvestigation,
43
43
  canContinueInvestigation,
44
+ canContinueInOwnAgent,
44
45
  readOnlyNotice,
45
46
  canInvestigateFurther,
46
47
  } from "./investigationState";
@@ -87,6 +88,10 @@ import {
87
88
  type RunSummary,
88
89
  } from "../../api/diagnose";
89
90
  import { useDiagnose } from "./DiagnoseContext";
91
+ import {
92
+ ExampleInvestigationProvider,
93
+ replayExampleInvestigation,
94
+ } from "./exampleInvestigation";
90
95
  import { InvestigationRefusalAction } from "./InvestigationRefusalAction";
91
96
  import {
92
97
  TurnView,
@@ -97,8 +102,8 @@ import {
97
102
  mergeStartupSignal,
98
103
  upsertTool,
99
104
  type Turn,
100
- remediationHeadline,
101
105
  } from "./parts";
106
+ import { NextStepJump, recommendedStepHeadline } from "./NextStepJump";
102
107
  import {
103
108
  investigationActivitySourceDomId,
104
109
  investigationEvidenceStepIdsByTurn,
@@ -329,16 +334,26 @@ export function InvestigationView({
329
334
  onOpenResource,
330
335
  onOpenTimeline,
331
336
  onRevealDestination,
337
+ example = false,
338
+ onCloseExample,
339
+ onHandoffAllowedChange,
332
340
  }: {
333
341
  run: RunSummary;
334
342
  agentLabel: string;
335
343
  maximized: boolean;
344
+ /** The bundled example: replayed from the bundle, with nothing that acts
345
+ * on it or sends it anywhere. */
346
+ example?: boolean;
347
+ onCloseExample?: () => void;
336
348
  /** Opens an unambiguous evidence subject in Radar's native resource views. */
337
349
  onOpenResource?: (ref: DiagnosisResourceRef) => void;
338
350
  /** Opens Radar's Timeline filtered to the resource a changes card is about. */
339
351
  onOpenTimeline?: (scope: InvestigationTimelineScope) => void;
340
352
  /** Makes a page this view navigates to visible: restores or closes the panel. */
341
353
  onRevealDestination?: () => void;
354
+ /** Whether nothing is writing to the agent's session, so the header may
355
+ * offer to continue it in the user's own agent. */
356
+ onHandoffAllowedChange?: (allowed: boolean) => void;
342
357
  }) {
343
358
  const { kind, namespace, name } = run;
344
359
  const {
@@ -353,9 +368,11 @@ export function InvestigationView({
353
368
  // Capabilities are the declared ones of the agent that ran this run, not
354
369
  // the picker's: a reopened run keeps the backend it was made with.
355
370
  const runAgent = agents.find((agent) => agent.name === run.agent);
356
- const explanationEnabled = supportsAssessmentExplanation(runAgent);
371
+ const explanationEnabled =
372
+ !example && supportsAssessmentExplanation(runAgent);
357
373
  // A question-only run has no resource to bind a confirmed fix to.
358
- const canApply = runAgent?.apply === true && !isQuestionOnly(run);
374
+ const canApply =
375
+ !example && runAgent?.apply === true && !isQuestionOnly(run);
359
376
  // Read through a ref by the stream callback, which lives as long as the
360
377
  // run and would otherwise keep the value from before the agents loaded.
361
378
  const verifiesAfterApplyRef = useRef(false);
@@ -616,7 +633,11 @@ export function InvestigationView({
616
633
  activityRevealRequestIdRef.current = 0;
617
634
  evidenceCardLayoutRef.current.clear();
618
635
  evidenceProjectionTurnsRef.current = [];
619
- const cancel = subscribeRun(run.id, {
636
+ const subscribe = example
637
+ ? (_id: string, handlers: Parameters<typeof subscribeRun>[1]) =>
638
+ replayExampleInvestigation(handlers)
639
+ : subscribeRun;
640
+ const cancel = subscribe(run.id, {
620
641
  onEvent: (ev: DiagnoseStreamEvent, sequence?: number) => {
621
642
  const live = replayCompleteRef.current;
622
643
  switch (ev.type) {
@@ -1654,20 +1675,31 @@ export function InvestigationView({
1654
1675
  currentAssessment?.diagnosis &&
1655
1676
  (currentAssessment.diagnosis.remediation?.length ?? 0) > 0,
1656
1677
  );
1678
+ const handoffAllowed =
1679
+ !example &&
1680
+ canContinueInOwnAgent({
1681
+ run,
1682
+ busy,
1683
+ requestPending,
1684
+ gone,
1685
+ streamReady,
1686
+ verificationPending,
1687
+ latestTurnStatus: lastTurn?.status,
1688
+ });
1689
+ useEffect(() => {
1690
+ onHandoffAllowedChange?.(handoffAllowed);
1691
+ }, [handoffAllowed, onHandoffAllowedChange]);
1692
+ useEffect(
1693
+ () => () => onHandoffAllowedChange?.(false),
1694
+ [onHandoffAllowedChange],
1695
+ );
1657
1696
  const earlierPlan =
1658
1697
  assessmentNeedsCurrentStateVerification ||
1659
1698
  hasEvidenceCollectedAfterAssessment;
1660
1699
  // The jump link names the decision it leads to, not the section.
1661
- const nextStepLabel = (() => {
1662
- const dx = currentAssessment?.diagnosis;
1663
- if (!dx) return "Next steps ↓";
1664
- const index = dx.recommendedIndex ? dx.recommendedIndex - 1 : 0;
1665
- const text =
1666
- dx.steps?.[index]?.text ?? dx.remediation?.[index] ?? dx.remediation?.[0];
1667
- if (!text) return "Next steps ↓";
1668
- const headline = remediationHeadline(text);
1669
- return `Next: ${headline.length > 56 ? `${headline.slice(0, 56).trimEnd()}…` : headline} ↓`;
1670
- })();
1700
+ const nextStepHeadline = recommendedStepHeadline(
1701
+ currentAssessment?.diagnosis,
1702
+ );
1671
1703
  // What a reader in a channel needs with the verdict: where, when, and the
1672
1704
  // receipts behind it, cause first, at most three.
1673
1705
  const assessmentCopy = useMemo(() => {
@@ -1801,7 +1833,7 @@ export function InvestigationView({
1801
1833
  setEvidenceUpdateAvailable(false);
1802
1834
  };
1803
1835
 
1804
- const composer = !unavailable ? (
1836
+ const composer = example ? null : !unavailable ? (
1805
1837
  <div className="shrink-0 border-t border-theme-border px-3 py-2.5">
1806
1838
  {canStop ? (
1807
1839
  <button
@@ -1947,10 +1979,34 @@ export function InvestigationView({
1947
1979
  ) : undefined;
1948
1980
 
1949
1981
  return (
1982
+ <ExampleInvestigationProvider value={example}>
1950
1983
  <div
1951
1984
  data-investigation-view
1952
1985
  className={`@container/investigation relative flex min-h-0 flex-1 flex-col bg-theme-surface ${maximized ? "investigation-split-enabled" : ""}`}
1953
1986
  >
1987
+ {example ? (
1988
+ <div
1989
+ data-investigation-example
1990
+ className="flex items-center gap-2 border-b border-theme-border bg-theme-elevated px-3 py-2 text-xs text-theme-text-secondary"
1991
+ >
1992
+ <Badge severity="info" size="sm">
1993
+ Example
1994
+ </Badge>
1995
+ <span className="min-w-0 flex-1">
1996
+ A sample investigation from a test cluster, not from yours. It is
1997
+ read-only.
1998
+ </span>
1999
+ {onCloseExample ? (
2000
+ <button
2001
+ type="button"
2002
+ onClick={onCloseExample}
2003
+ className="shrink-0 rounded-md border border-theme-border px-2 py-1 font-medium text-theme-text-primary hover:bg-theme-hover"
2004
+ >
2005
+ Close example
2006
+ </button>
2007
+ ) : null}
2008
+ </div>
2009
+ ) : null}
1954
2010
  {stale ? (
1955
2011
  <div className="flex items-center gap-2 border-b border-amber-500/35 bg-amber-500/10 px-3 py-2 text-xs text-theme-text-secondary">
1956
2012
  <AlertTriangle className="h-4 w-4 shrink-0 text-amber-500" />
@@ -1964,7 +2020,17 @@ export function InvestigationView({
1964
2020
  </span>
1965
2021
  </div>
1966
2022
  ) : null}
1967
- {!stale && gone ? (
2023
+ {example && gone ? (
2024
+ <div
2025
+ role="alert"
2026
+ className="flex items-center gap-2 border-b border-theme-border bg-theme-elevated px-3 py-2 text-xs text-theme-text-secondary"
2027
+ >
2028
+ <AlertTriangle className="h-4 w-4 shrink-0 text-amber-500" />
2029
+ <span className="min-w-0 flex-1">
2030
+ Radar couldn&apos;t load the example. Close it and open it again.
2031
+ </span>
2032
+ </div>
2033
+ ) : !stale && gone ? (
1968
2034
  <div className="flex items-center gap-2 border-b border-theme-border bg-theme-elevated px-3 py-2 text-xs text-theme-text-secondary">
1969
2035
  <AlertTriangle className="h-4 w-4 shrink-0 text-amber-500" />
1970
2036
  <span className="min-w-0 flex-1">
@@ -1982,7 +2048,7 @@ export function InvestigationView({
1982
2048
  </button>
1983
2049
  </div>
1984
2050
  ) : null}
1985
- {!stale && !gone && endedEarly ? (
2051
+ {!example && !stale && !gone && endedEarly ? (
1986
2052
  <div
1987
2053
  role="status"
1988
2054
  className="flex items-center gap-2 border-b border-theme-border bg-theme-elevated px-3 py-2 text-xs text-theme-text-secondary"
@@ -2204,7 +2270,8 @@ export function InvestigationView({
2204
2270
  turn.status === "error" &&
2205
2271
  !turn.question &&
2206
2272
  !turn.apply &&
2207
- !stale
2273
+ !stale &&
2274
+ !example
2208
2275
  ? retryDiagnosis
2209
2276
  : undefined
2210
2277
  }
@@ -2538,8 +2605,13 @@ export function InvestigationView({
2538
2605
  }
2539
2606
  assessmentAction={
2540
2607
  hasNextSteps ? (
2541
- <button
2542
- type="button"
2608
+ <NextStepJump
2609
+ label={
2610
+ earlierPlan
2611
+ ? "Earlier proposed steps"
2612
+ : undefined
2613
+ }
2614
+ headline={nextStepHeadline}
2543
2615
  onClick={() => {
2544
2616
  const section = nextStepsRef.current;
2545
2617
  const scroller = evidenceScrollRef.current;
@@ -2556,12 +2628,7 @@ export function InvestigationView({
2556
2628
  : "smooth",
2557
2629
  });
2558
2630
  }}
2559
- className="ml-auto rounded-md px-2 py-1 text-xs font-medium text-accent-text hover:bg-theme-hover"
2560
- >
2561
- {earlierPlan
2562
- ? "Earlier proposed steps ↓"
2563
- : nextStepLabel}
2564
- </button>
2631
+ />
2565
2632
  ) : null
2566
2633
  }
2567
2634
  explanation={explanationFor(currentAssessment)}
@@ -2749,5 +2816,6 @@ export function InvestigationView({
2749
2816
  confidence={turns[lastRemediationIdx]?.diagnosis?.confidence}
2750
2817
  />
2751
2818
  </div>
2819
+ </ExampleInvestigationProvider>
2752
2820
  );
2753
2821
  }
@@ -0,0 +1,450 @@
1
+ // @vitest-environment jsdom
2
+ import { act, useEffect } from "react";
3
+ import { createRoot, type Root } from "react-dom/client";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
+
6
+ import type { RunSummary } from "../../api/diagnose";
7
+ import { DiagnoseProvider, useDiagnose } from "./DiagnoseContext";
8
+ import {
9
+ defaultDiagnoseAction,
10
+ IssueDiagnoseButton,
11
+ } from "./LocalDiagnoseAction";
12
+
13
+ const api = vi.hoisted(() => ({
14
+ runs: [] as RunSummary[],
15
+ hosted: false,
16
+ listRuns: vi.fn(),
17
+ recordUsageEvent: vi.fn(),
18
+ }));
19
+
20
+ vi.mock("../../api/usage-data", async (importOriginal) => ({
21
+ ...(await importOriginal<object>()),
22
+ recordUsageEvent: api.recordUsageEvent,
23
+ }));
24
+
25
+ vi.mock("../../api/diagnose", async (importOriginal) => ({
26
+ ...(await importOriginal<object>()),
27
+ fetchAgents: async () => ({
28
+ enabled: true,
29
+ eligible: true,
30
+ consented: { "claude:safeguarded": true },
31
+ agents: [
32
+ {
33
+ name: "claude",
34
+ label: "Claude Code",
35
+ path: "/bin/claude",
36
+ version: "",
37
+ present: true,
38
+ supported: true,
39
+ hosted: api.hosted,
40
+ questions: true,
41
+ profiles: ["safeguarded"],
42
+ consentSurfaces: { safeguarded: "claude:safeguarded" },
43
+ },
44
+ ],
45
+ }),
46
+ listRuns: api.listRuns,
47
+ getRun: vi.fn(() => new Promise(() => {})),
48
+ }));
49
+
50
+ vi.mock("../../api/client", async (importOriginal) => ({
51
+ ...(await importOriginal<object>()),
52
+ useContexts: () => ({ data: [{ name: "cluster-a", isCurrent: true }] }),
53
+ }));
54
+
55
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
56
+ let root: Root;
57
+ const probe = {} as { d: ReturnType<typeof useDiagnose> };
58
+
59
+ function Probe() {
60
+ const d = useDiagnose();
61
+ useEffect(() => {
62
+ probe.d = d;
63
+ });
64
+ return null;
65
+ }
66
+
67
+ const flush = () =>
68
+ act(async () => {
69
+ await new Promise((resolve) => setTimeout(resolve, 0));
70
+ });
71
+
72
+ const ago = (h: number) => new Date(Date.now() - h * 3600_000).toISOString();
73
+ const investigated = (over: Partial<RunSummary> = {}): RunSummary => ({
74
+ id: "run-cart",
75
+ kind: "Deployment",
76
+ group: "apps",
77
+ namespace: "shop",
78
+ name: "cart",
79
+ context: "cluster-a",
80
+ status: "done",
81
+ preview: "Pods crash on a bad flag",
82
+ assessedAt: ago(2),
83
+ createdAt: ago(3),
84
+ updatedAt: ago(2),
85
+ ...over,
86
+ });
87
+
88
+ async function renderButton(
89
+ health: "problem" | "healthy" = "problem",
90
+ createdAt?: string,
91
+ ) {
92
+ await act(async () =>
93
+ root.render(
94
+ <DiagnoseProvider browserURLState={false}>
95
+ <Probe />
96
+ {defaultDiagnoseAction({
97
+ kind: "Deployment",
98
+ group: "apps",
99
+ namespace: "shop",
100
+ name: "cart",
101
+ health,
102
+ createdAt,
103
+ })}
104
+ </DiagnoseProvider>,
105
+ ),
106
+ );
107
+ await flush();
108
+ await flush();
109
+ }
110
+
111
+ const trigger = () =>
112
+ document.querySelector<HTMLButtonElement>("button[aria-label]")!;
113
+ const dialog = () => document.querySelector('[role="dialog"]');
114
+ const buttonNamed = (text: string) =>
115
+ [...document.querySelectorAll("button")].find((b) => b.textContent === text)!;
116
+
117
+ beforeEach(() => {
118
+ api.runs = [];
119
+ api.hosted = false;
120
+ api.listRuns.mockReset();
121
+ api.listRuns.mockImplementation(async () => ({ runs: api.runs }));
122
+ localStorage.clear();
123
+ const element = document.createElement("div");
124
+ document.body.appendChild(element);
125
+ root = createRoot(element);
126
+ });
127
+
128
+ afterEach(async () => {
129
+ await act(async () => root.unmount());
130
+ document.body.replaceChildren();
131
+ });
132
+
133
+ describe("a resource's last investigation", () => {
134
+ it("shows what the earlier investigation found before starting another", async () => {
135
+ api.runs = [investigated()];
136
+ await renderButton("problem");
137
+ const openRun = vi.spyOn(probe.d, "openRun");
138
+ const openInvestigation = vi.spyOn(probe.d, "openInvestigation");
139
+ await act(async () => trigger().click());
140
+ expect(dialog()?.textContent).toContain("Pods crash on a bad flag");
141
+ expect(openInvestigation).not.toHaveBeenCalled();
142
+ await act(async () => buttonNamed("Open investigation").click());
143
+ expect(openRun).toHaveBeenCalledWith("run-cart");
144
+ });
145
+
146
+ it("marks the button with a filled sparkle only when there is history", async () => {
147
+ await renderButton("problem");
148
+ expect(trigger().querySelector("svg")?.getAttribute("fill")).toBe("none");
149
+ api.runs = [investigated()];
150
+ await act(async () => window.dispatchEvent(new Event("focus")));
151
+ await flush();
152
+ expect(trigger().querySelector("svg")?.getAttribute("fill")).toBe(
153
+ "currentColor",
154
+ );
155
+ });
156
+
157
+ it("keeps the usual action one click further on", async () => {
158
+ api.runs = [investigated()];
159
+ await renderButton("problem");
160
+ const openInvestigation = vi.spyOn(probe.d, "openInvestigation");
161
+ await act(async () => trigger().click());
162
+ await act(async () => buttonNamed("Investigate again").click());
163
+ expect(openInvestigation).toHaveBeenCalledWith({
164
+ kind: "Deployment",
165
+ group: "apps",
166
+ namespace: "shop",
167
+ name: "cart",
168
+ });
169
+ });
170
+
171
+ it("offers a question on a healthy resource", async () => {
172
+ api.runs = [investigated({ preview: "Healthy" })];
173
+ await renderButton("healthy");
174
+ const openQuestion = vi.spyOn(probe.d, "openQuestion");
175
+ await act(async () => trigger().click());
176
+ expect(dialog()?.textContent).toContain("Healthy");
177
+ await act(async () => buttonNamed("Ask a question").click());
178
+ expect(openQuestion).toHaveBeenCalled();
179
+ });
180
+
181
+ it.each([
182
+ ["the object was recreated since", () => [investigated()], ago(1)],
183
+ [
184
+ "it ran on another cluster",
185
+ () => [investigated({ context: "cluster-b" })],
186
+ undefined,
187
+ ],
188
+ ])("stays out of the way when %s", async (_, runs, createdAt) => {
189
+ api.runs = runs();
190
+ await renderButton("problem", createdAt);
191
+ const openInvestigation = vi.spyOn(probe.d, "openInvestigation");
192
+ await act(async () => trigger().click());
193
+ expect(dialog()).toBeNull();
194
+ expect(openInvestigation).toHaveBeenCalled();
195
+ });
196
+
197
+ it("is off for hosted agents, which keep their own shared history", async () => {
198
+ api.hosted = true;
199
+ api.runs = [investigated()];
200
+ await renderButton("problem");
201
+ await act(async () => trigger().click());
202
+ expect(dialog()).toBeNull();
203
+ });
204
+
205
+ it("never opens a live run on another cluster's same-named resource", async () => {
206
+ api.runs = [
207
+ investigated({
208
+ status: "running",
209
+ context: "cluster-b",
210
+ assessedAt: undefined,
211
+ }),
212
+ ];
213
+ await renderButton("problem");
214
+ const openRun = vi.spyOn(probe.d, "openRun");
215
+ await act(async () => trigger().click());
216
+ expect(openRun).not.toHaveBeenCalled();
217
+ });
218
+
219
+ it("takes focus, and gives Escape back to the button without closing what's under it", async () => {
220
+ api.runs = [investigated()];
221
+ await renderButton("problem");
222
+ const underneath = vi.fn();
223
+ document.addEventListener("keydown", underneath);
224
+ const button = trigger();
225
+ await act(async () => button.click());
226
+ await flush();
227
+ expect(document.activeElement?.textContent).toBe("Open investigation");
228
+ await act(async () =>
229
+ document.activeElement!.dispatchEvent(
230
+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true }),
231
+ ),
232
+ );
233
+ expect(underneath).not.toHaveBeenCalled();
234
+ expect(button.isConnected).toBe(true);
235
+ expect(document.activeElement).toBe(button);
236
+ document.removeEventListener("keydown", underneath);
237
+ });
238
+
239
+ it("still opens a hosted agent's live run, whose cluster label differs", async () => {
240
+ api.hosted = true;
241
+ api.runs = [
242
+ investigated({
243
+ status: "running",
244
+ context: "Prod cluster",
245
+ assessedAt: undefined,
246
+ }),
247
+ ];
248
+ await renderButton("healthy");
249
+ const openRun = vi.spyOn(probe.d, "openRun");
250
+ await act(async () => trigger().click());
251
+ expect(openRun).toHaveBeenCalledWith("run-cart");
252
+ });
253
+
254
+ it("ignores a list that resolves after a newer one", async () => {
255
+ api.runs = [investigated()];
256
+ await renderButton("problem");
257
+ let resolveOld!: (v: { runs: RunSummary[] }) => void;
258
+ api.listRuns.mockImplementationOnce(
259
+ () => new Promise((resolve) => (resolveOld = resolve)),
260
+ );
261
+ await act(async () => window.dispatchEvent(new Event("focus")));
262
+ api.runs = [];
263
+ await act(async () => window.dispatchEvent(new Event("focus")));
264
+ await flush();
265
+ await act(async () => resolveOld({ runs: [investigated()] }));
266
+ await flush();
267
+ await act(async () => trigger().click());
268
+ expect(dialog()).toBeNull();
269
+ });
270
+
271
+ it("doesn't reopen the panel by itself after a new run finishes", async () => {
272
+ api.runs = [investigated()];
273
+ await renderButton("problem");
274
+ await act(async () => trigger().click());
275
+ expect(dialog()).not.toBeNull();
276
+ api.runs = [
277
+ investigated({ id: "run-new", status: "running", assessedAt: undefined }),
278
+ investigated(),
279
+ ];
280
+ await act(async () => probe.d.refreshRuns());
281
+ await flush();
282
+ api.runs = [
283
+ investigated({ id: "run-new", assessedAt: new Date().toISOString() }),
284
+ investigated(),
285
+ ];
286
+ await act(async () => probe.d.refreshRuns());
287
+ await flush();
288
+ await flush();
289
+ expect(dialog()).toBeNull();
290
+ });
291
+
292
+ it("catches up when the window regains focus", async () => {
293
+ await renderButton("problem");
294
+ expect(dialog()).toBeNull();
295
+ api.runs = [investigated()];
296
+ await act(async () => window.dispatchEvent(new Event("focus")));
297
+ await flush();
298
+ await act(async () => trigger().click());
299
+ expect(dialog()?.textContent).toContain("Pods crash on a bad flag");
300
+ });
301
+ });
302
+
303
+ describe("an issue row's Investigate action", () => {
304
+ const rowToggle = vi.fn();
305
+ async function renderIssueRow(size: "default" | "compact" = "default") {
306
+ rowToggle.mockReset();
307
+ await act(async () =>
308
+ root.render(
309
+ <DiagnoseProvider browserURLState={false}>
310
+ <Probe />
311
+ <div role="button" onClick={rowToggle} className="overflow-hidden">
312
+ <IssueDiagnoseButton
313
+ kind="Deployment"
314
+ group="apps"
315
+ namespace="shop"
316
+ name="cart"
317
+ size={size}
318
+ />
319
+ </div>
320
+ </DiagnoseProvider>,
321
+ ),
322
+ );
323
+ await flush();
324
+ await flush();
325
+ }
326
+ const issueButton = () =>
327
+ [...document.querySelectorAll("button")].find((b) =>
328
+ b.textContent?.includes("Investigate"),
329
+ )!;
330
+
331
+ it.each(["default", "compact"] as const)(
332
+ "shows the last investigation outside the row, without toggling it (%s)",
333
+ async (size) => {
334
+ api.runs = [investigated()];
335
+ await renderIssueRow(size);
336
+ const openRun = vi.spyOn(probe.d, "openRun");
337
+ await act(async () => issueButton().click());
338
+ // Portaled out of the row, which clips its contents.
339
+ expect(dialog()?.parentElement).toBe(document.body);
340
+ expect(dialog()?.textContent).toContain("Pods crash on a bad flag");
341
+ await act(async () => buttonNamed("Open investigation").click());
342
+ expect(openRun).toHaveBeenCalledWith("run-cart");
343
+ expect(rowToggle).not.toHaveBeenCalled();
344
+ },
345
+ );
346
+
347
+ const investigateEvent = { type: "ui", name: "issue_action:investigate" };
348
+
349
+ it("counts starting an investigation", async () => {
350
+ api.runs = [];
351
+ await renderIssueRow();
352
+ api.recordUsageEvent.mockClear();
353
+ await act(async () => issueButton().click());
354
+ expect(api.recordUsageEvent.mock.calls).toEqual([[investigateEvent]]);
355
+ });
356
+
357
+ it("counts investigating again, not opening the last investigation", async () => {
358
+ api.runs = [investigated()];
359
+ await renderIssueRow();
360
+ api.recordUsageEvent.mockClear();
361
+ await act(async () => issueButton().click());
362
+ expect(api.recordUsageEvent).not.toHaveBeenCalled();
363
+ await act(async () => buttonNamed("Investigate again").click());
364
+ expect(api.recordUsageEvent.mock.calls).toEqual([[investigateEvent]]);
365
+ });
366
+
367
+ it("re-investigates from the panel", async () => {
368
+ api.runs = [investigated()];
369
+ await renderIssueRow();
370
+ const openInvestigation = vi.spyOn(probe.d, "openInvestigation");
371
+ await act(async () => issueButton().click());
372
+ await act(async () => buttonNamed("Investigate again").click());
373
+ expect(openInvestigation).toHaveBeenCalledWith({
374
+ kind: "Deployment",
375
+ group: "apps",
376
+ namespace: "shop",
377
+ name: "cart",
378
+ });
379
+ expect(rowToggle).not.toHaveBeenCalled();
380
+ });
381
+
382
+ it("starts straight away when there's nothing recent", async () => {
383
+ api.runs = [];
384
+ await renderIssueRow();
385
+ const openInvestigation = vi.spyOn(probe.d, "openInvestigation");
386
+ await act(async () => issueButton().click());
387
+ expect(dialog()).toBeNull();
388
+ expect(openInvestigation).toHaveBeenCalled();
389
+ });
390
+
391
+ it("tabs out of the panel back to the button", async () => {
392
+ api.runs = [investigated()];
393
+ await renderIssueRow();
394
+ const button = issueButton();
395
+ await act(async () => button.click());
396
+ await flush();
397
+ const last = buttonNamed("Investigate again");
398
+ last.focus();
399
+ await act(async () =>
400
+ last.dispatchEvent(
401
+ new KeyboardEvent("keydown", { key: "Tab", bubbles: true }),
402
+ ),
403
+ );
404
+ expect(document.activeElement).toBe(button);
405
+ expect(dialog()?.getAttribute("inert")).not.toBeNull();
406
+ expect(rowToggle).not.toHaveBeenCalled();
407
+ });
408
+
409
+ it("opens above a button near the bottom of the screen", async () => {
410
+ api.runs = [investigated()];
411
+ await renderIssueRow();
412
+ const button = issueButton();
413
+ const rect = vi
414
+ .spyOn(HTMLElement.prototype, "getBoundingClientRect")
415
+ .mockReturnValue({
416
+ top: 700,
417
+ bottom: 720,
418
+ left: 900,
419
+ right: 1000,
420
+ width: 100,
421
+ height: 20,
422
+ x: 900,
423
+ y: 700,
424
+ toJSON: () => ({}),
425
+ });
426
+ const height = vi
427
+ .spyOn(HTMLElement.prototype, "offsetHeight", "get")
428
+ .mockReturnValue(150);
429
+ vi.stubGlobal("innerHeight", 768);
430
+ await act(async () => button.click());
431
+ await flush();
432
+ expect(dialog()!.getAttribute("style")).toContain("top: 544px");
433
+ rect.mockRestore();
434
+ height.mockRestore();
435
+ vi.unstubAllGlobals();
436
+ });
437
+
438
+ it("closes when the list scrolls, keeping keyboard focus on the button", async () => {
439
+ api.runs = [investigated()];
440
+ await renderIssueRow();
441
+ const button = issueButton();
442
+ await act(async () => button.click());
443
+ await flush();
444
+ expect(document.activeElement?.textContent).toBe("Open investigation");
445
+ await act(async () => document.dispatchEvent(new Event("scroll")));
446
+ await flush();
447
+ expect(dialog()?.getAttribute("inert")).not.toBeNull();
448
+ expect(document.activeElement).toBe(button);
449
+ });
450
+ });