@skyhook-io/radar-app 1.21.8 → 1.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +16 -1
  3. package/src/api/client.ts +18 -0
  4. package/src/api/cnpg-history.ts +3 -3
  5. package/src/api/cnpg-storage.ts +3 -3
  6. package/src/api/diagnose.test.ts +34 -0
  7. package/src/api/diagnose.ts +17 -4
  8. package/src/api/radarFeatures.test.ts +13 -1
  9. package/src/api/radarFeatures.ts +6 -0
  10. package/src/api/resourceActions.test.ts +829 -0
  11. package/src/api/resourceActions.ts +584 -0
  12. package/src/api/resourceActions.ui.test.tsx +1882 -0
  13. package/src/api/reviewedActionMutation.ts +56 -28
  14. package/src/api/substrateHealth.ts +2 -3
  15. package/src/api/traefik.ts +33 -0
  16. package/src/api/traffic.ts +14 -5
  17. package/src/api/workloadMetrics.test.ts +11 -2
  18. package/src/api/workloadMetrics.ts +2 -2
  19. package/src/components/CloudFunnelButton.test.tsx +39 -1
  20. package/src/components/CloudFunnelButton.tsx +10 -3
  21. package/src/components/cnpg/CNPGOverview.test.tsx +75 -3
  22. package/src/components/cnpg/CNPGOverview.tsx +62 -4
  23. package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
  24. package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
  25. package/src/components/diagnose/DiagnoseContext.tsx +28 -3
  26. package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
  27. package/src/components/diagnose/Home.tsx +3 -0
  28. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
  29. package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
  30. package/src/components/diagnose/InvestigationView.tsx +10 -2
  31. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
  32. package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
  33. package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
  34. package/src/components/diagnose/QuestionComposer.tsx +13 -8
  35. package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
  36. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
  37. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
  38. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
  39. package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
  40. package/src/components/diagnose/launch.ts +1 -1
  41. package/src/components/dock/PodDebugSession.test.tsx +66 -0
  42. package/src/components/dock/PodDebugSession.tsx +3 -1
  43. package/src/components/dock/TerminalTab.test.tsx +43 -3
  44. package/src/components/dock/TerminalTab.tsx +10 -1
  45. package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
  46. package/src/components/helm/InstallWizard.tsx +1 -1
  47. package/src/components/home/NetworkPolicyCoverageCard.test.tsx +37 -0
  48. package/src/components/home/NetworkPolicyCoverageCard.tsx +26 -2
  49. package/src/components/home/mcpToolCatalog.ts +1 -1
  50. package/src/components/resources/PodEvictAction.test.tsx +951 -0
  51. package/src/components/resources/PodEvictAction.tsx +167 -0
  52. package/src/components/resources/ResourcesView.tsx +3 -0
  53. package/src/components/resources/renderers/TraefikIngressRouteRenderer.test.tsx +23 -0
  54. package/src/components/resources/renderers/TraefikIngressRouteRenderer.tsx +23 -0
  55. package/src/components/resources/renderers/TraefikMiddlewareRenderer.test.tsx +23 -0
  56. package/src/components/resources/renderers/TraefikMiddlewareRenderer.tsx +29 -0
  57. package/src/components/resources/renderers/WorkloadRenderer.tsx +3 -0
  58. package/src/components/settings/LocalConnectionSettings.tsx +4 -4
  59. package/src/components/settings/SettingsDialog.tsx +23 -18
  60. package/src/components/settings/integrationQueries.test.ts +98 -0
  61. package/src/components/settings/integrationQueries.ts +36 -0
  62. package/src/components/traffic/TrafficConnectionsTable.test.tsx +23 -0
  63. package/src/components/traffic/TrafficConnectionsTable.tsx +5 -4
  64. package/src/components/traffic/TrafficFilterSidebar.test.tsx +14 -0
  65. package/src/components/traffic/TrafficFilterSidebar.tsx +17 -0
  66. package/src/components/traffic/TrafficFlowList.tsx +5 -5
  67. package/src/components/traffic/TrafficGraph.test.tsx +11 -0
  68. package/src/components/traffic/TrafficGraph.tsx +31 -19
  69. package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
  70. package/src/components/traffic/TrafficView.tsx +108 -41
  71. package/src/components/traffic/traffic-export.test.ts +8 -0
  72. package/src/components/traffic/traffic-export.ts +7 -4
  73. package/src/components/traffic/trafficFilters.test.ts +51 -1
  74. package/src/components/traffic/trafficFilters.ts +39 -11
  75. package/src/components/ui/Markdown.test.tsx +37 -0
  76. package/src/components/ui/Markdown.tsx +15 -2
  77. package/src/components/ui/command-items-crd.test.tsx +23 -8
  78. package/src/components/useContextSwitchFlow.test.tsx +27 -2
  79. package/src/components/useContextSwitchFlow.tsx +20 -22
  80. package/src/components/whats-new/releaseNotes.ts +75 -1
  81. package/src/components/workload/WorkloadView.tsx +16 -3
  82. package/src/integrations/resourceHosts.test.tsx +1 -1
  83. package/src/integrations/resourceHosts.tsx +3 -0
@@ -9,7 +9,160 @@ import {
9
9
  warningEvent,
10
10
  } from "../evidenceFixtures";
11
11
 
12
+ const storedRule = {
13
+ kind: "ConfigMap",
14
+ namespace: "kube-system",
15
+ name: "coredns",
16
+ key: "Corefile",
17
+ line: 5,
18
+ text: "rewrite name regex .*\\.nodes\\.vcluster\\.com kubernetes.default.svc.cluster.local",
19
+ };
20
+
21
+ // The `coreDNSFindings` shape: a verdict on the ConfigMap.
22
+ const legacyFinding = {
23
+ kind: "ConfigMap",
24
+ namespace: "kube-system",
25
+ name: "coredns",
26
+ severity: "warning",
27
+ reason: "CoreDNS service DNS rewrite",
28
+ };
29
+
12
30
  describe("semantic diagnose evidence projection", () => {
31
+ // The exact strings the server emits (internal/mcp/tools_diagnose.go,
32
+ // internal/issues/provider.go), and the "errors" wording some versions use. A
33
+ // stored CoreDNS rule is configuration; only these make DNS evidence adverse.
34
+ it.each([
35
+ "pod logs contain DNS resolution failures",
36
+ "warning events contain DNS resolution failures",
37
+ "pod logs contain DNS resolution errors",
38
+ "warning events contain DNS resolution errors",
39
+ ])("treats %j as a DNS failure with or without stored rules", (signal) => {
40
+ for (const coreDNSRules of [undefined, [storedRule]]) {
41
+ const result = project([
42
+ tool("dns-failure", "diagnose", {
43
+ resource: deployment,
44
+ resourceContext: { tier: "basic" },
45
+ pods: 0,
46
+ events: [],
47
+ dnsContext: { signals: [signal], coreDNSRules },
48
+ }),
49
+ ]);
50
+ expect(groupsOf(result.groups, "dns")[0].latest).toMatchObject({
51
+ tone: "warning",
52
+ title: "DNS failure signals",
53
+ });
54
+ }
55
+ });
56
+
57
+ it("keeps stored CoreDNS rules neutral when no lookup failed", () => {
58
+ const result = project([
59
+ tool("dns-config", "diagnose", {
60
+ resource: deployment,
61
+ resourceContext: { tier: "basic" },
62
+ pods: 0,
63
+ events: [],
64
+ dnsContext: {
65
+ signals: ["api uses dnsPolicy=None"],
66
+ coreDNSRules: [storedRule],
67
+ },
68
+ }),
69
+ ]);
70
+ expect(groupsOf(result.groups, "dns")[0].latest).toMatchObject({
71
+ tier: "context",
72
+ tone: "info",
73
+ title: "DNS configuration",
74
+ });
75
+ });
76
+
77
+ // The server's configuration signals, with resource names that contain
78
+ // failure words (internal/mcp/tools_diagnose.go, internal/issues/provider.go).
79
+ it.each([
80
+ "errors-api uses dnsPolicy=None",
81
+ "servfail-exporter sets dnsConfig.nameservers",
82
+ "failed-jobs sets dnsConfig.searches",
83
+ "CoreDNS Deployment kube-system/coredns-errors rolled 2m ago (generation=3, 2 owned ReplicaSets, newest=coredns-errors-abc)",
84
+ "Radar observed ConfigMap kube-system/coredns-failures update 4m ago",
85
+ ])("reads %j as configuration, whatever the resource is called", (signal) => {
86
+ const result = project([
87
+ tool("dns-config-name", "diagnose", {
88
+ resource: deployment,
89
+ resourceContext: { tier: "basic" },
90
+ pods: 0,
91
+ events: [],
92
+ dnsContext: { signals: [signal], coreDNSRules: [storedRule] },
93
+ }),
94
+ ]);
95
+ expect(groupsOf(result.groups, "dns")[0].latest).toMatchObject({
96
+ tone: "info",
97
+ title: "DNS configuration",
98
+ });
99
+ });
100
+
101
+ it("reads the issues DNS context sent under the dns key", () => {
102
+ const result = project([
103
+ tool("issues-dns-legacy", "issues", {
104
+ issues: [],
105
+ total: 0,
106
+ total_matched: 0,
107
+ cluster_context: {
108
+ dns: {
109
+ signals: ["CoreDNS Deployment kube-system/coredns rolled 2m ago"],
110
+ findings: [legacyFinding],
111
+ },
112
+ },
113
+ }),
114
+ ]);
115
+ expect(groupsOf(result.groups, "dns")[0].latest).toMatchObject({
116
+ tone: "info",
117
+ data: { type: "dns", dns: { coreDNSFindings: [legacyFinding] } },
118
+ });
119
+ });
120
+
121
+ it("does not let a CoreDNS verdict make the card adverse", () => {
122
+ const result = project([
123
+ tool("dns-legacy", "diagnose", {
124
+ resource: deployment,
125
+ resourceContext: { tier: "basic" },
126
+ pods: 0,
127
+ events: [],
128
+ dnsContext: { coreDNSFindings: [legacyFinding] },
129
+ }),
130
+ ]);
131
+ expect(groupsOf(result.groups, "dns")[0].latest).toMatchObject({
132
+ tone: "info",
133
+ title: "DNS configuration",
134
+ });
135
+ });
136
+
137
+ it("warns on cluster DNS context only when a lookup failure was seen", () => {
138
+ const tones = [
139
+ "Warning events in namespace shop contain DNS resolution failures",
140
+ "CoreDNS Deployment kube-system/coredns rolled out 2m ago",
141
+ ].map((signal) => {
142
+ const result = project([
143
+ tool("issues-dns", "issues", {
144
+ issues: [],
145
+ total: 0,
146
+ total_matched: 0,
147
+ cluster_context: {
148
+ dns_config: {
149
+ signals: [signal],
150
+ rules: [storedRule],
151
+ omitted_rules: 2,
152
+ },
153
+ },
154
+ }),
155
+ ]);
156
+ const latest = groupsOf(result.groups, "dns")[0].latest;
157
+ expect(latest.data).toMatchObject({
158
+ type: "dns",
159
+ dns: { coreDNSRules: [storedRule], omittedCoreDNSRules: 2 },
160
+ });
161
+ return latest.tone;
162
+ });
163
+ expect(tones).toEqual(["warning", "info"]);
164
+ });
165
+
13
166
  it("promotes only classified smoking guns and audits every partiality signal", () => {
14
167
  const result = project([
15
168
  tool("diagnose-1", "diagnose", {
@@ -9,6 +9,8 @@ import {
9
9
  type DiagnosisResourceRef,
10
10
  type DiagnosisStartupBlocker,
11
11
  diagnosisSeverityTone,
12
+ dnsSignalReportsFailure,
13
+ coreDNSRulesSummary,
12
14
  } from "../../diagnoseEvidenceTypes";
13
15
  import { metricsWindowLabel } from "./prometheus";
14
16
  import {
@@ -836,17 +838,13 @@ export function adaptDiagnose(
836
838
  const dns = record(value.dnsContext);
837
839
  if (dns) {
838
840
  const signals = stringArray(dns.signals) ?? [];
839
- const findings = Array.isArray(dns.coreDNSFindings)
840
- ? dns.coreDNSFindings
841
- : [];
841
+ const findings = [dns.coreDNSRules, dns.coreDNSFindings].flatMap((list) =>
842
+ Array.isArray(list) ? list : [],
843
+ );
842
844
  if (signals.length > 0 || findings.length > 0) {
843
- const adverse =
844
- findings.length > 0 ||
845
- signals.some((signal) =>
846
- /\b(error|failed|failures?|timeouts?|nxdomain|servfail)\b/i.test(
847
- signal,
848
- ),
849
- );
845
+ // Stored CoreDNS rules are configuration. Only a reported failure
846
+ // makes this card adverse.
847
+ const adverse = signals.some(dnsSignalReportsFailure);
850
848
  builder.observe(`dns:${scopeFromArgs(source)}`, "dns", source, {
851
849
  tier: evidenceTierForRelevance(
852
850
  adverse ? "supporting" : "context",
@@ -855,9 +853,7 @@ export function adaptDiagnose(
855
853
  relevance: relatedRelevance,
856
854
  tone: adverse ? "warning" : "info",
857
855
  title: adverse ? "DNS failure signals" : "DNS configuration",
858
- summary:
859
- signals[0] ||
860
- `${findings.length} CoreDNS finding${findings.length === 1 ? "" : "s"}`,
856
+ summary: signals[0] || coreDNSRulesSummary(findings.length),
861
857
  data: { type: "dns", dns: dns as unknown as DiagnosisDNSContext },
862
858
  });
863
859
  }
@@ -1,6 +1,10 @@
1
1
  import { type Issue, type IssueRecentChange } from "@skyhook-io/k8s-ui";
2
2
  import { type UncheckedSource } from "../../../../api/client";
3
- import { type DiagnosisDNSContext } from "../../diagnoseEvidenceTypes";
3
+ import {
4
+ type DiagnosisDNSContext,
5
+ dnsSignalReportsFailure,
6
+ coreDNSRulesSummary,
7
+ } from "../../diagnoseEvidenceTypes";
4
8
  import {
5
9
  ProjectionBuilder,
6
10
  addChanges,
@@ -111,26 +115,38 @@ export function adaptIssues(
111
115
  invalidPayload(builder, source, "Issue-related changes");
112
116
  }
113
117
  addClusterScopedChanges(builder, source, value.cluster_scoped_changes);
114
- const clusterDNS = record(record(value.cluster_context)?.dns);
118
+ // `dns_config` holds `rules`. A response may carry `dns` instead, whose
119
+ // `findings` are verdicts on a CoreDNS ConfigMap.
120
+ const clusterContext = record(value.cluster_context);
121
+ const clusterDNS =
122
+ record(clusterContext?.dns_config) ?? record(clusterContext?.dns);
115
123
  if (clusterDNS) {
116
124
  const signals = stringArray(clusterDNS.signals) ?? [];
125
+ const rules = Array.isArray(clusterDNS.rules) ? clusterDNS.rules : [];
117
126
  const findings = Array.isArray(clusterDNS.findings)
118
127
  ? clusterDNS.findings
119
128
  : [];
120
- if (signals.length > 0 || findings.length > 0) {
129
+ if (signals.length > 0 || rules.length > 0 || findings.length > 0) {
121
130
  builder.observe(`dns:issues:${scopeFromArgs(source)}`, "dns", source, {
122
131
  tier: "context",
123
132
  relevance: "broader",
124
- tone: "warning",
133
+ // A CoreDNS rollout or config change with stored rules is context.
134
+ // Only a reported failure is a warning.
135
+ tone: signals.some(dnsSignalReportsFailure) ? "warning" : "info",
125
136
  title: "Cluster DNS signals",
126
137
  summary:
127
138
  signals[0] ||
128
- `${findings.length} CoreDNS finding${findings.length === 1 ? "" : "s"}`,
139
+ coreDNSRulesSummary(rules.length + findings.length),
129
140
  data: {
130
141
  type: "dns",
131
142
  dns: {
132
143
  signals,
144
+ coreDNSRules: rules as DiagnosisDNSContext["coreDNSRules"],
133
145
  coreDNSFindings: findings as DiagnosisDNSContext["coreDNSFindings"],
146
+ omittedCoreDNSRules:
147
+ typeof clusterDNS.omitted_rules === "number"
148
+ ? clusterDNS.omitted_rules
149
+ : undefined,
134
150
  },
135
151
  },
136
152
  });
@@ -2,10 +2,32 @@ import { useContext } from "react";
2
2
  import { AlertTriangle } from "lucide-react";
3
3
  import { Badge, StatusDot, ResourceLink } from "@skyhook-io/k8s-ui";
4
4
  import { EvidenceNavigationContext } from "../navigation";
5
- import { type EvidenceDataOf, severityBadge } from "../cardParts";
5
+ import { type EvidenceDataOf } from "../cardParts";
6
6
 
7
7
  export function DNSBody({ data }: { data: EvidenceDataOf<"dns"> }) {
8
8
  const { onOpenResource } = useContext(EvidenceNavigationContext);
9
+ const rules = data.dns.coreDNSRules ?? [];
10
+ const source = (ref: { kind: string; namespace: string; name: string }) => (
11
+ <>
12
+ <Badge tone="structural" size="sm">
13
+ {ref.kind}
14
+ </Badge>
15
+ <span className="font-mono text-xs">
16
+ <ResourceLink
17
+ name={ref.name}
18
+ kind={ref.kind}
19
+ namespace={ref.namespace}
20
+ group=""
21
+ label={`${ref.namespace}/${ref.name}`}
22
+ onNavigate={
23
+ ref.kind.toLowerCase() === "configmap" && onOpenResource
24
+ ? (target) => onOpenResource(target)
25
+ : undefined
26
+ }
27
+ />
28
+ </span>
29
+ </>
30
+ );
9
31
  return (
10
32
  <div className="space-y-2">
11
33
  {(data.dns.signals ?? []).map((signal) => (
@@ -16,37 +38,52 @@ export function DNSBody({ data }: { data: EvidenceDataOf<"dns"> }) {
16
38
  {signal}
17
39
  </p>
18
40
  ))}
19
- {(data.dns.coreDNSFindings ?? []).map((finding) => (
41
+ {rules.length > 0 && (
42
+ <p className="text-xs text-theme-text-tertiary">
43
+ Rewrite and template rules in the CoreDNS config
44
+ </p>
45
+ )}
46
+ {rules.map((rule) => (
20
47
  <div
21
- key={`${finding.kind}-${finding.namespace}-${finding.name}-${finding.reason}`}
48
+ key={`${rule.namespace}-${rule.name}-${rule.key}-${rule.line}`}
22
49
  className="rounded-md border border-theme-border bg-theme-base/40 p-2"
23
50
  >
24
51
  <div className="flex flex-wrap gap-1.5">
25
- <Badge tone="structural" size="sm">
26
- {finding.kind}
27
- </Badge>
28
- <span className="font-mono text-xs">
29
- <ResourceLink
30
- name={finding.name}
31
- kind={finding.kind}
32
- namespace={finding.namespace}
33
- group=""
34
- label={`${finding.namespace}/${finding.name}`}
35
- onNavigate={
36
- finding.kind.toLowerCase() === "configmap" && onOpenResource
37
- ? (ref) => onOpenResource(ref)
38
- : undefined
39
- }
40
- />
52
+ {source(rule)}
53
+ <span className="text-xs text-theme-text-tertiary">
54
+ {rule.key}, line {rule.line}
41
55
  </span>
42
- <Badge severity={severityBadge(finding.severity)} size="sm">
43
- {finding.severity}
44
- </Badge>
45
56
  </div>
46
- <p className="mt-1 text-xs text-theme-text-secondary">
47
- {finding.reason}
48
- {finding.message ? ` — ${finding.message}` : ""}
49
- </p>
57
+ <pre className="mt-1 overflow-x-auto whitespace-pre-wrap break-words font-mono text-xs text-theme-text-secondary">
58
+ {rule.text}
59
+ </pre>
60
+ {rule.truncated && (
61
+ <p className="mt-1 text-xs text-theme-text-tertiary">
62
+ Cut short. Open the ConfigMap for the whole rule.
63
+ </p>
64
+ )}
65
+ </div>
66
+ ))}
67
+ {(data.dns.omittedCoreDNSRules ?? 0) > 0 && (
68
+ <p className="text-xs text-theme-text-tertiary">
69
+ {data.dns.omittedCoreDNSRules} more{" "}
70
+ {data.dns.omittedCoreDNSRules === 1 ? "rule is" : "rules are"} not
71
+ shown.
72
+ </p>
73
+ )}
74
+ {/* A `coreDNSFindings` entry is a verdict on the ConfigMap. Its reason
75
+ and message are shown as text, without its severity. */}
76
+ {(data.dns.coreDNSFindings ?? []).map((finding, index) => (
77
+ <div
78
+ key={`legacy-${finding.namespace}-${finding.name}-${index}`}
79
+ className="rounded-md border border-theme-border bg-theme-base/40 p-2"
80
+ >
81
+ <div className="flex flex-wrap gap-1.5">{source(finding)}</div>
82
+ {(finding.reason || finding.message) && (
83
+ <p className="mt-1 text-xs text-theme-text-secondary">
84
+ {[finding.reason, finding.message].filter(Boolean).join(": ")}
85
+ </p>
86
+ )}
50
87
  </div>
51
88
  ))}
52
89
  </div>
@@ -50,7 +50,7 @@ export function openInTerminal(command: string, title: string) {
50
50
  // buildLaunchCommand resumes the investigation's ACTUAL agent session interactively
51
51
  // (not a re-seeded prompt), so the full transcript — every tool call, finding, and
52
52
  // the agent's reasoning — carries over. Returns null when there's no resumable
53
- // session yet (first turn still running) or the run is stale (different cluster).
53
+ // session yet (first turn still running) or the run is stale (its connection closed).
54
54
  // The MCP server is re-attached on resume (it's configured per-launch, not stored
55
55
  // in the session).
56
56
  export function buildLaunchCommand(
@@ -58,3 +58,69 @@ it.each([
58
58
  await until(message)
59
59
  expect(document.body.textContent).not.toContain('attached')
60
60
  })
61
+
62
+ it('keeps a running debug terminal mounted when its connection is replaced, so the terminal can say why it ended', async () => {
63
+ const { observeConnectionStatus, resetConnectionBindingForTest } = await import('../../api/connectionBinding')
64
+ resetConnectionBindingForTest()
65
+ observeConnectionStatus({ connectionId: 'c-1' })
66
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply({ running: {} })))
67
+ const bound = { ...session, connectionId: 'c-1' }
68
+ const host = document.createElement('div')
69
+ document.body.append(host)
70
+ root = createRoot(host)
71
+ const render = () => root.render(<QueryClientProvider client={client}><PodDebugSession {...opts} session={bound}><b>attached</b></PodDebugSession></QueryClientProvider>)
72
+ await act(async () => render())
73
+ await vi.waitFor(() => expect(document.body.textContent).toContain('attached'))
74
+ await act(async () => observeConnectionStatus({ connectionId: 'c-2' }))
75
+ expect(document.body.textContent).toContain('attached')
76
+ expect(document.body.textContent).not.toContain('The cluster connection changed')
77
+ resetConnectionBindingForTest()
78
+ })
79
+
80
+ it('says the connection changed for a debug session that never reached its terminal', async () => {
81
+ const { observeConnectionStatus, resetConnectionBindingForTest } = await import('../../api/connectionBinding')
82
+ resetConnectionBindingForTest()
83
+ observeConnectionStatus({ connectionId: 'c-2' })
84
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply({ running: {} })))
85
+ const host = document.createElement('div')
86
+ document.body.append(host)
87
+ root = createRoot(host)
88
+ await act(async () => root.render(<QueryClientProvider client={client}><PodDebugSession {...opts} session={{ ...session, connectionId: 'c-1' }}><b>attached</b></PodDebugSession></QueryClientProvider>))
89
+ expect(document.body.textContent).toContain('The cluster connection changed')
90
+ expect(document.body.textContent).not.toContain('attached')
91
+ resetConnectionBindingForTest()
92
+ })
93
+
94
+ it('replaces a running debug terminal that recorded no connection once one is adopted', async () => {
95
+ const { observeConnectionStatus, resetConnectionBindingForTest } = await import('../../api/connectionBinding')
96
+ resetConnectionBindingForTest()
97
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply({ running: {} })))
98
+ await mount()
99
+ await vi.waitFor(() => expect(document.body.textContent).toContain('attached'))
100
+ await act(async () => observeConnectionStatus({ connectionId: 'c-1' }))
101
+ expect(document.body.textContent).toContain('The cluster connection changed')
102
+ resetConnectionBindingForTest()
103
+ })
104
+
105
+ it('keeps a running bound debug terminal mounted when the API base changes', async () => {
106
+ const { observeConnectionStatus, resetConnectionBindingForTest } = await import('../../api/connectionBinding')
107
+ const config = await import('../../api/config')
108
+ const original = config.getApiBase()
109
+ resetConnectionBindingForTest()
110
+ observeConnectionStatus({ connectionId: 'c-1' })
111
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply({ running: {} })))
112
+ const host = document.createElement('div')
113
+ document.body.append(host)
114
+ root = createRoot(host)
115
+ const render = () => root.render(<QueryClientProvider client={client}><PodDebugSession {...opts} session={{ ...session, apiBase: original, connectionId: 'c-1' }}><b>attached</b></PodDebugSession></QueryClientProvider>)
116
+ try {
117
+ await act(async () => render())
118
+ await vi.waitFor(() => expect(document.body.textContent).toContain('attached'))
119
+ config.setApiBase('/clusters/other/api')
120
+ await act(async () => render())
121
+ expect(document.body.textContent).toContain('attached')
122
+ } finally {
123
+ config.setApiBase(original)
124
+ resetConnectionBindingForTest()
125
+ }
126
+ })
@@ -68,7 +68,9 @@ export function PodDebugSession({ namespace, podName, containerName, session, is
68
68
  })
69
69
 
70
70
  if (!connected && !query.error && query.data?.state === 'running' && current()) setConnected(true)
71
- if (currentConnection !== session.connectionId || getApiBase() !== session.apiBase) return <div role="status" className="p-5 text-sm text-theme-text-secondary">The cluster connection changed. Reopen the Pod to inspect this debug session.</div>
71
+ // A running terminal bound to a connection keeps its scrollback and shows its own ended notice.
72
+ const changed = currentConnection !== session.connectionId || getApiBase() !== session.apiBase
73
+ if (changed && (!connected || !session.connectionId)) return <div role="status" className="p-5 text-sm text-theme-text-secondary">The cluster connection changed. Reopen the Pod to inspect this debug session.</div>
72
74
  if (connected) return <>{children}</>
73
75
 
74
76
  const status = query.data
@@ -1,4 +1,7 @@
1
+ // @vitest-environment jsdom
1
2
  import { renderToString } from 'react-dom/server'
3
+ import { act } from 'react'
4
+ import { createRoot } from 'react-dom/client'
2
5
  import { beforeEach, expect, it, vi } from 'vitest'
3
6
  import type { TerminalTabProps } from '@skyhook-io/k8s-ui'
4
7
  import { TerminalTab } from './TerminalTab'
@@ -23,24 +26,61 @@ it.each([undefined, '/bin/custom+command'])('forwards the executable and context
23
26
  expect(new URL(retry.wsUrl).searchParams.get('uid')).toBe('reviewed-pod')
24
27
  })
25
28
 
26
- it('reconnects on the connection the tab was opened on, not the latest', async () => {
29
+ it('reconnects on the connection the tab was opened on, and says so once that connection has closed', async () => {
27
30
  const { observeConnectionStatus, resetConnectionBindingForTest } = await import('../../api/connectionBinding')
28
31
  resetConnectionBindingForTest()
29
32
  observeConnectionStatus({ connectionId: 'n-1' })
30
33
  renderToString(<TerminalTab namespace="app" podName="worker" containerName="app" containers={['app']} />)
31
- observeConnectionStatus({ connectionId: 'n-2' }) // switched since the tab opened
32
34
  const { wsUrl } = await captured.props!.createSession('app')
33
35
  expect(new URL(wsUrl).searchParams.get('connection')).toBe('n-1')
36
+ observeConnectionStatus({ connectionId: 'n-2' }) // switched since the tab opened
37
+ await expect(captured.props!.createSession('app')).rejects.toThrow('the cluster connection it ran on closed')
38
+ resetConnectionBindingForTest()
39
+ })
40
+
41
+ it('shows the ended state with Close once the connection the tab opened on is replaced', async () => {
42
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
43
+ const { observeConnectionStatus, resetConnectionBindingForTest } = await import('../../api/connectionBinding')
34
44
  resetConnectionBindingForTest()
45
+ observeConnectionStatus({ connectionId: 'n-1' })
46
+ const onLeaveTerminal = vi.fn()
47
+ const root = createRoot(document.createElement('div'))
48
+ await act(async () => root.render(<TerminalTab namespace="app" podName="worker" containerName="app" containers={['app']} onLeaveTerminal={onLeaveTerminal} />))
49
+ expect(captured.props!.endedNotice).toBeUndefined()
50
+ await act(async () => observeConnectionStatus({ connectionId: 'n-2' }))
51
+ expect(captured.props!.endedNotice).toContain('the cluster connection it ran on closed')
52
+ captured.props!.onClose!()
53
+ expect(onLeaveTerminal).toHaveBeenCalledTimes(1)
54
+ await act(async () => root.unmount())
55
+ resetConnectionBindingForTest()
56
+ })
57
+
58
+ it('treats a changed API base as a closed connection', async () => {
59
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
60
+ const config = await import('../../api/config')
61
+ const original = config.getApiBase()
62
+ const root = createRoot(document.createElement('div'))
63
+ await act(async () => root.render(<TerminalTab namespace="app" podName="worker" containerName="app" containers={['app']} />))
64
+ expect(captured.props!.endedNotice).toBeUndefined()
65
+ try {
66
+ config.setApiBase('/clusters/other/api')
67
+ await act(async () => root.render(<TerminalTab namespace="app" podName="worker" containerName="app" containers={['app']} />))
68
+ expect(captured.props!.endedNotice).toContain('closed')
69
+ } finally {
70
+ config.setApiBase(original)
71
+ await act(async () => root.unmount())
72
+ }
35
73
  })
36
74
 
37
75
  it('reconnects an existing debug session to its reviewed connection without offering another container', async () => {
38
76
  const { observeConnectionStatus, resetConnectionBindingForTest } = await import('../../api/connectionBinding')
39
- observeConnectionStatus({ connectionId: 'next-cluster' })
77
+ observeConnectionStatus({ connectionId: 'reviewed-cluster' })
40
78
  renderToString(<TerminalTab namespace="demo" podName="api" containerName="debug-1" containers={['debug-1']} debugSession={{ connectionId: 'reviewed-cluster', apiBase: '/api', podUID: 'reviewed', image: 'mirror.example/debug' }} />)
41
79
  const { wsUrl } = await captured.props!.createSession('debug-1')
42
80
  expect(new URL(wsUrl).searchParams.get('connection')).toBe('reviewed-cluster')
43
81
  expect(new URL(wsUrl).searchParams.get('uid')).toBe('reviewed')
82
+ observeConnectionStatus({ connectionId: 'next-cluster' })
83
+ await expect(captured.props!.createSession('debug-1')).rejects.toThrow('the cluster connection it ran on closed')
44
84
  expect(renderToString(captured.props!.renderDebugAction!('debug-1', 'reviewed'))).toContain('different image')
45
85
  resetConnectionBindingForTest()
46
86
  })
@@ -7,7 +7,9 @@ import { useResource } from '../../api/client'
7
7
  import type { PodDebugTarget } from '../resources/PodDebugAction'
8
8
  import { MissingShellDebug } from './MissingShellDebug'
9
9
  import { PodDebugSession } from './PodDebugSession'
10
- import { useCurrentConnectionId, useOpenedConnection, withConnectionParam } from '../../api/connectionBinding'
10
+ import { connectionHeaderValue, useCurrentConnectionId, useOpenedConnection, withConnectionParam } from '../../api/connectionBinding'
11
+
12
+ const connectionClosedNotice = 'This terminal ended because the cluster connection it ran on closed (a cluster switch, a retry or a sign-in refresh). Open the Pod again to start a new terminal.'
11
13
 
12
14
  interface TerminalTabProps {
13
15
  namespace: string
@@ -30,6 +32,7 @@ export function TerminalTab({ namespace, podName, podUID, containerName, contain
30
32
  const base = debugSession?.apiBase ?? openedBase
31
33
  const currentConnection = useCurrentConnectionId()
32
34
  const sameConnection = currentConnection === connection && getApiBase() === base
35
+ const connectionClosed = getApiBase() !== base || (!!connection && !!currentConnection && currentConnection !== connection)
33
36
  const checkTargets = !!podUID && !shell && !debugSession && containers.length > 1
34
37
  const pod = useResource<PodDebugTarget>('pods', namespace, podName, undefined, { enabled: checkTargets && sameConnection && isActive !== false })
35
38
  const currentPod = sameConnection && !pod.error && pod.data?.metadata.uid === podUID ? pod.data : undefined
@@ -43,6 +46,10 @@ export function TerminalTab({ namespace, podName, podUID, containerName, contain
43
46
  const createSession = async (container: string, failedPodUID?: string) => {
44
47
  const uid = debugSession?.podUID ?? podUID ?? failedPodUID
45
48
  if (getApiBase() !== base) throw new Error('The cluster connection changed. Reopen the Pod to start a terminal.')
49
+ // The server refuses a terminal on a connection that has closed, but a browser
50
+ // can't read why a WebSocket upgrade failed, so say it here.
51
+ const current = connectionHeaderValue(base)
52
+ if (connection && current && current !== connection) throw new Error(connectionClosedNotice)
46
53
  return {
47
54
  wsUrl: withConnectionParam(getWsUrl(`/pods/${namespace}/${podName}/exec?container=${encodeURIComponent(container)}${uid ? `&uid=${encodeURIComponent(uid)}` : ''}${shell ? `&shell=${encodeURIComponent(shell)}` : ''}`), connection),
48
55
  }
@@ -64,6 +71,8 @@ export function TerminalTab({ namespace, podName, podUID, containerName, contain
64
71
  <MissingShellDebug key={JSON.stringify([uid,target])} namespace={namespace} name={podName} target={target} uid={uid} connection={connection} base={base} podDetailsLink={podDetailsLink} />}
65
72
  note={note}
66
73
  command={shell}
74
+ endedNotice={connectionClosed ? connectionClosedNotice : undefined}
75
+ onClose={onLeaveTerminal}
67
76
  />
68
77
  )
69
78
  return debugSession ? <PodDebugSession namespace={namespace} podName={podName} containerName={containerName} session={debugSession} isActive={isActive} podDetailsLink={podDetailsLink}>
@@ -1556,7 +1556,7 @@ function OverviewTab({ release, onCopy, copied }: OverviewTabProps) {
1556
1556
  </button>
1557
1557
  </div>
1558
1558
  <div className="text-xs bg-theme-base/50 rounded p-3 max-h-96 overflow-auto">
1559
- <Markdown>{release.readme}</Markdown>
1559
+ <Markdown allowImages>{release.readme}</Markdown>
1560
1560
  </div>
1561
1561
  </div>
1562
1562
  )}
@@ -640,7 +640,7 @@ function InfoStep({
640
640
  </button>
641
641
  {showReadme && (
642
642
  <div className="mt-3 p-4 bg-theme-base/50 rounded-lg text-xs overflow-auto max-h-96">
643
- <Markdown>{readme}</Markdown>
643
+ <Markdown allowImages>{readme}</Markdown>
644
644
  </div>
645
645
  )}
646
646
  </div>
@@ -78,4 +78,41 @@ describe("NetworkPolicyCoverageCard", () => {
78
78
  expect(html).not.toContain("if staged");
79
79
  expect(html).not.toContain("repeating-linear-gradient");
80
80
  });
81
+
82
+ it("says which workloads the totals leave out", () => {
83
+ const html = render(
84
+ <NetworkPolicyCoverageCard
85
+ data={{
86
+ totalPolicies: 1,
87
+ coveredWorkloads: 1,
88
+ totalWorkloads: 3,
89
+ ignoredNamespaceWorkloads: 6,
90
+ hostNetworkWorkloads: 1,
91
+ }}
92
+ onNavigate={() => {}}
93
+ />,
94
+ );
95
+ expect(html).toContain("7 not counted");
96
+
97
+ const none = render(
98
+ <NetworkPolicyCoverageCard
99
+ data={{ totalPolicies: 1, coveredWorkloads: 1, totalWorkloads: 3 }}
100
+ onNavigate={() => {}}
101
+ />,
102
+ );
103
+ expect(none).not.toContain("not counted");
104
+ });
105
+
106
+ it("does not show 0% coverage when no workloads are counted", () => {
107
+ const html = render(
108
+ <NetworkPolicyCoverageCard
109
+ data={{ totalPolicies: 2, coveredWorkloads: 0, totalWorkloads: 0, ignoredNamespaceWorkloads: 3 }}
110
+ onNavigate={() => {}}
111
+ />,
112
+ );
113
+ expect(html).toContain("No workloads counted");
114
+ expect(html).toContain("3 not counted");
115
+ expect(html).not.toContain("0%");
116
+ expect(html).not.toContain("text-red-500");
117
+ });
81
118
  });