@skyhook-io/radar-app 1.22.0 → 1.22.2

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 (95) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +98 -29
  3. package/src/RadarApp.tsx +5 -0
  4. package/src/api/client.ts +18 -1
  5. package/src/api/cnpg-history.ts +3 -3
  6. package/src/api/cnpg-storage.ts +3 -3
  7. package/src/api/diagnose.test.ts +34 -0
  8. package/src/api/diagnose.ts +17 -4
  9. package/src/api/radarFeatures.test.ts +13 -1
  10. package/src/api/radarFeatures.ts +2 -0
  11. package/src/api/resourceActions.test.ts +829 -0
  12. package/src/api/resourceActions.ts +584 -0
  13. package/src/api/resourceActions.ui.test.tsx +1882 -0
  14. package/src/api/reviewedActionMutation.ts +56 -28
  15. package/src/api/substrateHealth.ts +2 -3
  16. package/src/api/traffic.ts +13 -5
  17. package/src/api/workloadMetrics.test.ts +11 -2
  18. package/src/api/workloadMetrics.ts +2 -2
  19. package/src/api/workloadSource.test.tsx +857 -0
  20. package/src/api/workloadSource.ts +292 -0
  21. package/src/components/APIUnreachableBanner.test.tsx +19 -0
  22. package/src/components/APIUnreachableBanner.tsx +20 -0
  23. package/src/components/ConnectionErrorView.test.tsx +63 -2
  24. package/src/components/ConnectionErrorView.tsx +88 -68
  25. package/src/components/diagnose/ActivityTurn.tsx +6 -4
  26. package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
  27. package/src/components/diagnose/AssessmentCard.tsx +1 -2
  28. package/src/components/diagnose/ContinueInAgentButton.test.tsx +7 -0
  29. package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
  30. package/src/components/diagnose/DiagnoseContext.tsx +28 -3
  31. package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
  32. package/src/components/diagnose/Home.test.tsx +6 -0
  33. package/src/components/diagnose/Home.tsx +13 -3
  34. package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +1 -1
  35. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
  36. package/src/components/diagnose/InvestigationEvidencePane.tsx +19 -2
  37. package/src/components/diagnose/InvestigationFindingsFooter.test.tsx +413 -0
  38. package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
  39. package/src/components/diagnose/InvestigationView.tsx +130 -25
  40. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
  41. package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
  42. package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
  43. package/src/components/diagnose/QuestionComposer.tsx +13 -8
  44. package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
  45. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
  46. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
  47. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
  48. package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
  49. package/src/components/diagnose/investigationEvidence/identity.test.ts +1 -1
  50. package/src/components/diagnose/investigationEvidence/projection.test.ts +1 -1
  51. package/src/components/diagnose/investigationState.ts +9 -0
  52. package/src/components/diagnose/launch.ts +1 -1
  53. package/src/components/diagnose/parts.test.tsx +11 -3
  54. package/src/components/diagnose/toolCallLabel.ts +3 -0
  55. package/src/components/dock/PodDebugSession.test.tsx +66 -0
  56. package/src/components/dock/PodDebugSession.tsx +3 -1
  57. package/src/components/dock/TerminalTab.test.tsx +43 -3
  58. package/src/components/dock/TerminalTab.tsx +10 -1
  59. package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
  60. package/src/components/helm/InstallWizard.tsx +1 -1
  61. package/src/components/home/ActivitySummary.tsx +3 -8
  62. package/src/components/home/ClusterHealthCard.tsx +91 -17
  63. package/src/components/home/ClusterHealthCard.utilization.test.tsx +187 -0
  64. package/src/components/home/HomeView.tsx +6 -26
  65. package/src/components/home/TopologyPreview.test.tsx +31 -30
  66. package/src/components/home/TopologyPreview.tsx +19 -28
  67. package/src/components/home/mcpToolCatalog.ts +4 -4
  68. package/src/components/resources/PodEvictAction.test.tsx +951 -0
  69. package/src/components/resources/PodEvictAction.tsx +167 -0
  70. package/src/components/resources/ResourcesView.tsx +3 -0
  71. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +5 -4
  72. package/src/components/resources/renderers/RolloutRenderer.tsx +4 -1
  73. package/src/components/resources/renderers/WorkloadRenderer.tsx +7 -1
  74. package/src/components/settings/LocalConnectionSettings.tsx +4 -4
  75. package/src/components/settings/SettingsDialog.tsx +23 -18
  76. package/src/components/settings/integrationQueries.test.ts +98 -0
  77. package/src/components/settings/integrationQueries.ts +36 -0
  78. package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
  79. package/src/components/traffic/TrafficView.tsx +91 -35
  80. package/src/components/ui/Markdown.test.tsx +37 -0
  81. package/src/components/ui/Markdown.tsx +15 -2
  82. package/src/components/useContextSwitchFlow.test.tsx +27 -2
  83. package/src/components/useContextSwitchFlow.tsx +20 -22
  84. package/src/components/workload/WorkloadView.tsx +83 -4
  85. package/src/components/workload/WorkloadView.workloadSource.test.tsx +121 -0
  86. package/src/context/ConnectionContext.tsx +24 -5
  87. package/src/context/ConnectionProvider.connectionId.test.tsx +14 -0
  88. package/src/context/ConnectionProvider.handover.test.tsx +94 -0
  89. package/src/context/DiagnoseCustomization.tsx +20 -2
  90. package/src/hooks/useEventSource.test.tsx +275 -4
  91. package/src/hooks/useEventSource.ts +278 -51
  92. package/src/index.ts +1 -0
  93. package/src/utils/navigation.test.ts +1 -6
  94. package/src/utils/navigation.ts +9 -44
  95. package/src/utils/network-policy-navigation.test.ts +21 -36
@@ -0,0 +1,413 @@
1
+ // @vitest-environment jsdom
2
+ import { act, type ReactNode } from "react";
3
+ import { createRoot } from "react-dom/client";
4
+ import { MemoryRouter } from "react-router-dom";
5
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
6
+ import { afterEach, beforeEach, expect, it, vi } from "vitest";
7
+ import {
8
+ subscribeRun,
9
+ type DiagnoseStreamEvent,
10
+ type RunSummary,
11
+ type SubscribeHandlers,
12
+ } from "../../api/diagnose";
13
+ import {
14
+ DiagnoseCustomizationProvider,
15
+ type RenderInvestigationFindingsFooter,
16
+ } from "../../context/DiagnoseCustomization";
17
+ import { EXAMPLE_INVESTIGATION_RUN } from "./exampleInvestigation";
18
+ import transcript from "./exampleInvestigation.events.json";
19
+ import { InvestigationView } from "./InvestigationView";
20
+
21
+ vi.mock("../../api/diagnose", async (original) => ({
22
+ ...(await original<typeof import("../../api/diagnose")>()),
23
+ subscribeRun: vi.fn(),
24
+ }));
25
+ vi.mock("./DiagnoseContext", () => ({
26
+ useDiagnose: () => ({
27
+ refreshRuns: vi.fn(),
28
+ agents: [{ name: "claude", hosted: true, assessmentExplanations: true }],
29
+ }),
30
+ }));
31
+ vi.mock("../../context/ThemeContext", () => ({
32
+ useTheme: () => ({ theme: "light" }),
33
+ }));
34
+ vi.mock("../ui/Tooltip", () => ({
35
+ Tooltip: ({ children }: { children: ReactNode }) => children,
36
+ }));
37
+
38
+ const events = transcript as unknown as DiagnoseStreamEvent[];
39
+ const evidenceRef = events.find((e) => e.step?.evidenceRef)?.step?.evidenceRef;
40
+ if (!evidenceRef) throw new Error("The example transcript needs a cited read");
41
+ const run = {
42
+ ...EXAMPLE_INVESTIGATION_RUN,
43
+ id: "hosted-run",
44
+ ownedByMe: false,
45
+ visibility: "organization" as const,
46
+ canContinue: true,
47
+ };
48
+ let container: HTMLDivElement;
49
+ let root: ReturnType<typeof createRoot>;
50
+ let stream: SubscribeHandlers;
51
+ let footer: Parameters<RenderInvestigationFindingsFooter>[0];
52
+ const scrollTo = vi.fn();
53
+ const renderFooter: RenderInvestigationFindingsFooter = (props) => {
54
+ footer = props;
55
+ return (
56
+ <article aria-label="Proposed change" tabIndex={-1}>
57
+ Review change
58
+ </article>
59
+ );
60
+ };
61
+ beforeEach(() => {
62
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
63
+ vi.stubGlobal(
64
+ "ResizeObserver",
65
+ class {
66
+ observe() {}
67
+ disconnect() {}
68
+ },
69
+ );
70
+ vi.stubGlobal("matchMedia", () => ({
71
+ matches: true,
72
+ addEventListener() {},
73
+ removeEventListener() {},
74
+ }));
75
+ vi.mocked(subscribeRun).mockImplementation((_id, handlers) => {
76
+ stream = handlers;
77
+ return () => {};
78
+ });
79
+ container = document.createElement("div");
80
+ document.body.appendChild(container);
81
+ root = createRoot(container);
82
+ });
83
+ afterEach(() => {
84
+ act(() => root.unmount());
85
+ container.remove();
86
+ vi.unstubAllGlobals();
87
+ });
88
+
89
+ function render(canContinue = true, summary: Partial<RunSummary> = {}) {
90
+ act(() =>
91
+ root.render(
92
+ <QueryClientProvider client={new QueryClient()}>
93
+ <MemoryRouter>
94
+ <DiagnoseCustomizationProvider
95
+ value={undefined}
96
+ renderFindingsFooter={renderFooter}
97
+ >
98
+ <InvestigationView
99
+ run={{ ...run, canContinue, ...summary }}
100
+ agentLabel="Hosted"
101
+ maximized={false}
102
+ />
103
+ </DiagnoseCustomizationProvider>
104
+ </MemoryRouter>
105
+ </QueryClientProvider>,
106
+ ),
107
+ );
108
+ const findings = container.querySelector<HTMLElement>(
109
+ "[data-investigation-findings-scroll]",
110
+ )!;
111
+ scrollTo.mockClear();
112
+ findings.scrollTo = scrollTo;
113
+ return findings;
114
+ }
115
+
116
+ function replay(saved: DiagnoseStreamEvent[] = events) {
117
+ act(() => {
118
+ for (const [i, event] of saved.entries()) stream.onEvent(event, i + 1);
119
+ stream.onEvent({ type: "replay_complete" });
120
+ });
121
+ }
122
+
123
+ it("waits for the replay boundary before exposing a landing target", () => {
124
+ const findings = render();
125
+ for (const [i, event] of events.entries()) {
126
+ act(() => stream.onEvent(event, i + 1));
127
+ expect(findings.querySelector("[aria-label='Proposed change']")).toBeNull();
128
+ }
129
+ act(() => stream.onEvent({ type: "replay_complete" }));
130
+ expect(findings.querySelector("[aria-label='Proposed change']")).toBeTruthy();
131
+ });
132
+
133
+ it("lands on the resolved card in Findings and returns to the actual assessment and composer", () => {
134
+ const findings = render();
135
+ expect(
136
+ findings.querySelector("article[aria-label='Proposed change']"),
137
+ ).toBeNull();
138
+ replay();
139
+ const card = findings.querySelector<HTMLElement>(
140
+ "[aria-label='Proposed change']",
141
+ )!;
142
+ const assessment = findings.querySelector<HTMLElement>(
143
+ ".investigation-assessment",
144
+ )!;
145
+ expect(
146
+ assessment.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING,
147
+ ).toBeTruthy();
148
+ expect(scrollTo).not.toHaveBeenCalled();
149
+ act(() => footer.askQuestion!());
150
+ expect(document.activeElement?.tagName).toBe("TEXTAREA");
151
+ act(() => footer.revealInFindings(card));
152
+ expect(document.activeElement).toBe(card);
153
+ expect(findings.parentElement?.classList.contains("hidden")).toBe(false);
154
+ expect(scrollTo).toHaveBeenCalledTimes(1);
155
+ act(() => footer.viewAssessment!());
156
+ expect(document.activeElement).toBe(assessment);
157
+ expect(footer.evidenceLink(evidenceRef)).toEqual(expect.any(Function));
158
+ expect(footer.evidenceLink("unrelated")).toBeUndefined();
159
+ });
160
+
161
+ it("opens the precise raw tool result when Findings has no card for its read", async () => {
162
+ render();
163
+ const original = events.find(
164
+ (event) => event.step?.evidenceRef === evidenceRef,
165
+ )!;
166
+ const step = {
167
+ ...original.step!,
168
+ tool: "read_cluster_provider",
169
+ id: "raw-receipt",
170
+ };
171
+ replay([{ type: "turn" }, { type: "step", step }, { type: "done" }]);
172
+ const activity = container.querySelector<HTMLElement>(
173
+ "[data-investigation-activity-scroll]",
174
+ )!;
175
+ activity.scrollTo = vi.fn();
176
+ const open = footer.evidenceLink(evidenceRef);
177
+ expect(open).toEqual(expect.any(Function));
178
+ act(() => open!());
179
+ await vi.waitFor(() => {
180
+ expect(document.activeElement?.id).toBe(
181
+ "investigation-activity-turn-0-step-raw-receipt",
182
+ );
183
+ });
184
+ expect(activity.contains(document.activeElement)).toBe(true);
185
+ });
186
+
187
+ it("keeps a proposal bound to its earlier read and withholds ambiguous references", () => {
188
+ render();
189
+ const original = events.find(
190
+ (event) => event.step?.evidenceRef === evidenceRef,
191
+ )!;
192
+ const followUp: DiagnoseStreamEvent = {
193
+ type: "turn",
194
+ question: "Check another resource",
195
+ };
196
+ replay([...events, followUp]);
197
+ expect(footer.evidenceLink(evidenceRef)).toEqual(expect.any(Function));
198
+ act(() =>
199
+ stream.onEvent({
200
+ ...original,
201
+ step: { ...original.step!, id: "duplicate" },
202
+ }),
203
+ );
204
+ expect(footer.evidenceLink(evidenceRef)).toBeUndefined();
205
+ });
206
+
207
+ it("opens the original Kubernetes read after a second read updates its Findings card", async () => {
208
+ const findings = render();
209
+ const activity = container.querySelector<HTMLElement>(
210
+ "[data-investigation-activity-scroll]",
211
+ )!;
212
+ activity.scrollTo = vi.fn();
213
+ const newerRef = "ev_sampleinvestigationaaaaaaa_seconddeploymentreadbaaaaa";
214
+ function read(id: string, ref: string, version: string): DiagnoseStreamEvent {
215
+ return {
216
+ type: "step",
217
+ step: {
218
+ id,
219
+ tool: "get_resource",
220
+ status: "done",
221
+ isError: false,
222
+ radarEvidence: true,
223
+ evidenceRef: ref,
224
+ result: JSON.stringify({
225
+ apiVersion: "apps/v1",
226
+ kind: "Deployment",
227
+ metadata: {
228
+ name: run.name,
229
+ namespace: run.namespace,
230
+ resourceVersion: version,
231
+ },
232
+ status: { readyReplicas: 2, replicas: 3 },
233
+ }),
234
+ },
235
+ };
236
+ }
237
+ replay([
238
+ { type: "turn" },
239
+ read("initial-read", evidenceRef, "before-change"),
240
+ { type: "done" },
241
+ { type: "turn", question: "Check the current workload", verify: true },
242
+ read("verified-read", newerRef, "after-change"),
243
+ { type: "done" },
244
+ ]);
245
+ act(() => footer.evidenceLink(evidenceRef)!());
246
+ await vi.waitFor(() => {
247
+ expect(document.activeElement?.id).toBe(
248
+ "investigation-activity-turn-0-step-initial-read",
249
+ );
250
+ expect(document.activeElement?.textContent).toContain("before-change");
251
+ expect(document.activeElement?.textContent).not.toContain("after-change");
252
+ });
253
+ act(() => footer.evidenceLink(newerRef)!());
254
+ await vi.waitFor(() => {
255
+ expect(findings.contains(document.activeElement)).toBe(true);
256
+ expect(document.activeElement?.hasAttribute("data-evidence-card")).toBe(
257
+ true,
258
+ );
259
+ });
260
+ });
261
+
262
+ it("keeps read-only proposals in Findings without exposing a follow-up action", () => {
263
+ const findings = render(false);
264
+ replay();
265
+ expect(findings.textContent).toContain("Review change");
266
+ expect(footer.askQuestion).toBeUndefined();
267
+ });
268
+
269
+ it("lets an assigned reader see the private proposal and its evidence through a running turn and replay", () => {
270
+ const explanation = "Only the investigator can ask follow-up questions.";
271
+ const findings = render(false, {
272
+ visibility: "private",
273
+ status: "running",
274
+ ownedByMe: false,
275
+ continueBlockedReason: explanation,
276
+ });
277
+ replay([{ type: "turn" }]);
278
+ expect(container.textContent).not.toContain("Stop agent");
279
+ expect(footer.askQuestion).toBeUndefined();
280
+ // The server's run summary still says running after the terminal event.
281
+ act(() => {
282
+ for (const [i, event] of events.slice(1).entries())
283
+ stream.onEvent(event, i + 2);
284
+ });
285
+ expect(findings.querySelector("[aria-label='Proposed change']")).toBeTruthy();
286
+ expect(footer.evidenceLink(evidenceRef)).toEqual(expect.any(Function));
287
+ expect(container.textContent).toContain(explanation);
288
+ expect(container.querySelector("textarea")).toBeNull();
289
+ expect(findings.textContent).not.toContain("Explain simply");
290
+ expect(footer.askQuestion).toBeUndefined();
291
+ });
292
+
293
+ it("can land on a proposal even when saved evidence is permanently unavailable", () => {
294
+ const findings = render();
295
+ act(() =>
296
+ stream.onEvent({
297
+ type: "history_unavailable",
298
+ error: "Could not restore history",
299
+ retryable: false,
300
+ }),
301
+ );
302
+ expect(findings.textContent).toContain("Saved evidence unavailable");
303
+ const card = findings.querySelector<HTMLElement>(
304
+ "[aria-label='Proposed change']",
305
+ )!;
306
+ act(() => footer.revealInFindings(card));
307
+ expect(document.activeElement).toBe(card);
308
+ expect(footer.viewAssessment).toBeUndefined();
309
+ expect(footer.evidenceLink(evidenceRef)).toBeUndefined();
310
+ expect(footer.askQuestion).toBeUndefined();
311
+ });
312
+
313
+ it("expands Captured results and focuses an unplaced main read in a story-shaped investigation", async () => {
314
+ const findings = render();
315
+ const proposalRef = "ev_sampleinvestigationaaaaaaa_proposalgetresourcereadaaa";
316
+ const proposalRead: DiagnoseStreamEvent = {
317
+ type: "step",
318
+ step: {
319
+ id: "proposal-read",
320
+ tool: "get_resource",
321
+ status: "done",
322
+ isError: false,
323
+ radarEvidence: true,
324
+ evidenceRef: proposalRef,
325
+ result: JSON.stringify({
326
+ apiVersion: "apps/v1",
327
+ kind: "Deployment",
328
+ metadata: {
329
+ name: run.name,
330
+ namespace: run.namespace,
331
+ resourceVersion: "42",
332
+ },
333
+ status: { readyReplicas: 1, replicas: 2 },
334
+ }),
335
+ },
336
+ };
337
+ replay([...events.slice(0, -1), proposalRead, events[events.length - 1]]);
338
+
339
+ const resultsToggle = findings.querySelector<HTMLButtonElement>(
340
+ 'button[aria-controls="investigation-captured-results"]',
341
+ )!;
342
+ const resultsPanel = findings.querySelector<HTMLElement>(
343
+ "#investigation-captured-results",
344
+ )!;
345
+ const targetCard = resultsPanel.querySelector<HTMLElement>(
346
+ '[data-evidence-source="turn-0-step-proposal-read"]',
347
+ )!;
348
+ expect(resultsToggle.getAttribute("aria-expanded")).toBe("false");
349
+ expect(targetCard).toBeTruthy();
350
+ expect(targetCard.closest("[inert]")).not.toBeNull();
351
+
352
+ const open = footer.evidenceLink(proposalRef);
353
+ expect(open).toEqual(expect.any(Function));
354
+ act(() => open!());
355
+
356
+ await vi.waitFor(() => {
357
+ expect(resultsToggle.getAttribute("aria-expanded")).toBe("true");
358
+ expect(targetCard.closest("[inert]")).toBeNull();
359
+ expect(document.activeElement).toBe(targetCard);
360
+ expect(document.activeElement?.hasAttribute("data-evidence-card")).toBe(
361
+ true,
362
+ );
363
+ });
364
+ expect(resultsPanel.contains(document.activeElement)).toBe(true);
365
+ });
366
+
367
+ it("preserves visible story cards and focuses the non-inert Captured results card when a story duplicate is inert", async () => {
368
+ const findings = render();
369
+ replay();
370
+ const placedRef = "ev_sampleinvestigationaaaaaaa_applicationdiagnosebundlea";
371
+ const resultsToggle = findings.querySelector<HTMLButtonElement>(
372
+ 'button[aria-controls="investigation-captured-results"]',
373
+ )!;
374
+ const resultsPanel = findings.querySelector<HTMLElement>(
375
+ "#investigation-captured-results",
376
+ )!;
377
+ const story = findings.querySelector<HTMLElement>("[data-story]")!;
378
+ const storyToggle = findings.querySelector<HTMLButtonElement>(
379
+ "[data-story] > button[aria-expanded]",
380
+ )!;
381
+
382
+ act(() => storyToggle.click());
383
+ expect(story.getAttribute("data-story-open")).toBe("true");
384
+ expect(resultsToggle.getAttribute("aria-expanded")).toBe("false");
385
+
386
+ const open = footer.evidenceLink(placedRef);
387
+ expect(open).toEqual(expect.any(Function));
388
+ act(() => open!());
389
+
390
+ await vi.waitFor(() => {
391
+ expect(story.contains(document.activeElement)).toBe(true);
392
+ expect(document.activeElement?.id.startsWith("story-")).toBe(true);
393
+ expect(document.activeElement?.closest("[inert]")).toBeNull();
394
+ });
395
+ const storyCard = document.activeElement as HTMLElement;
396
+ expect(resultsToggle.getAttribute("aria-expanded")).toBe("false");
397
+
398
+ act(() => storyToggle.click());
399
+ expect(story.getAttribute("data-story-open")).toBe("false");
400
+ expect(story.contains(storyCard)).toBe(true);
401
+ expect(storyCard.closest("[inert]")).not.toBeNull();
402
+
403
+ act(() => footer.evidenceLink(placedRef)!());
404
+ await vi.waitFor(() => {
405
+ expect(resultsToggle.getAttribute("aria-expanded")).toBe("true");
406
+ expect(resultsPanel.contains(document.activeElement)).toBe(true);
407
+ expect(document.activeElement).not.toBe(storyCard);
408
+ expect(document.activeElement?.hasAttribute("data-evidence-card")).toBe(
409
+ true,
410
+ );
411
+ expect(document.activeElement?.closest("[inert]")).toBeNull();
412
+ });
413
+ });
@@ -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
+ });