BugReportBubble.test.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /**
  2. * Tests for the BugReportBubble component.
  3. */
  4. import { describe, it, expect, afterEach, vi } from 'vitest';
  5. import { render, screen, waitFor } from '../utils';
  6. import userEvent from '@testing-library/user-event';
  7. import { http, HttpResponse } from 'msw';
  8. import { server } from '../mocks/server';
  9. import { BugReportBubble } from '../../components/BugReportBubble';
  10. function getDescriptionTextarea() {
  11. return document.querySelector('textarea') as HTMLTextAreaElement;
  12. }
  13. function getSubmitButton() {
  14. const buttons = screen.getAllByRole('button');
  15. return buttons.find(
  16. (b) =>
  17. b.className.includes('bg-red-500') &&
  18. !b.className.includes('rounded-full') &&
  19. b.textContent !== ''
  20. );
  21. }
  22. function setupLoggingEndpoints() {
  23. server.use(
  24. http.post('*/bug-report/start-logging', () => {
  25. return HttpResponse.json({ started: true, was_debug: false });
  26. }),
  27. http.post('*/bug-report/stop-logging', () => {
  28. return HttpResponse.json({ logs: 'test debug logs' });
  29. })
  30. );
  31. }
  32. /** Mocks the printer list and per-printer diagnostic the form scans on open. */
  33. function setupDiagnosticEndpoints(
  34. printers: { id: number; name: string }[],
  35. results: Record<number, 'ok' | 'problems'>
  36. ) {
  37. server.use(
  38. http.get('*/printers/', () =>
  39. HttpResponse.json(
  40. printers.map((p) => ({
  41. id: p.id,
  42. name: p.name,
  43. serial_number: '00M09A000000000',
  44. ip_address: `192.168.1.${20 + p.id}`,
  45. is_active: true,
  46. model: 'X1C',
  47. nozzle_count: 1,
  48. }))
  49. )
  50. ),
  51. http.get('*/printers/:id/diagnostic', ({ params }) => {
  52. const overall = results[Number(params.id)] ?? 'ok';
  53. return HttpResponse.json({
  54. printer_id: Number(params.id),
  55. ip_address: `192.168.1.${20 + Number(params.id)}`,
  56. overall,
  57. checks: [{ id: 'port_mqtt', status: overall === 'problems' ? 'fail' : 'pass', params: {} }],
  58. });
  59. })
  60. );
  61. }
  62. describe('BugReportBubble', () => {
  63. it('renders the floating bug button', () => {
  64. render(<BugReportBubble />);
  65. const button = screen.getByRole('button');
  66. expect(button).toBeInTheDocument();
  67. });
  68. it('opens panel when bubble is clicked', async () => {
  69. const user = userEvent.setup();
  70. render(<BugReportBubble />);
  71. await user.click(screen.getByRole('button'));
  72. expect(getDescriptionTextarea()).toBeInTheDocument();
  73. });
  74. it('closes panel when X button is clicked', async () => {
  75. const user = userEvent.setup();
  76. render(<BugReportBubble />);
  77. // Open
  78. await user.click(screen.getByRole('button'));
  79. expect(getDescriptionTextarea()).toBeInTheDocument();
  80. // Close via the X button
  81. const buttons = screen.getAllByRole('button');
  82. const closeButton = buttons.find((b) => b.querySelector('.lucide-x'));
  83. if (closeButton) await user.click(closeButton);
  84. await waitFor(() => {
  85. expect(document.querySelector('textarea')).not.toBeInTheDocument();
  86. });
  87. });
  88. it('disables submit when description is empty', async () => {
  89. const user = userEvent.setup();
  90. render(<BugReportBubble />);
  91. await user.click(screen.getByRole('button'));
  92. expect(getSubmitButton()).toBeDisabled();
  93. });
  94. it('enables submit when description is provided', async () => {
  95. const user = userEvent.setup();
  96. render(<BugReportBubble />);
  97. await user.click(screen.getByRole('button'));
  98. await user.type(getDescriptionTextarea(), 'Something is broken');
  99. expect(getSubmitButton()).not.toBeDisabled();
  100. });
  101. it('shows logging state with step indicators after start', async () => {
  102. const user = userEvent.setup();
  103. setupLoggingEndpoints();
  104. render(<BugReportBubble />);
  105. await user.click(screen.getByRole('button'));
  106. await user.type(getDescriptionTextarea(), 'Test bug report');
  107. const submitBtn = getSubmitButton();
  108. if (submitBtn) await user.click(submitBtn);
  109. // Should show step indicators and elapsed timer
  110. await waitFor(() => {
  111. expect(screen.queryByTestId('bug-report-step-reproduce')).toBeInTheDocument();
  112. });
  113. // Should show elapsed timer (00:00 format)
  114. await waitFor(() => {
  115. const timer = screen.queryByText(/00:0/);
  116. expect(timer).toBeInTheDocument();
  117. });
  118. });
  119. it('shows success state after successful submission', async () => {
  120. const user = userEvent.setup();
  121. setupLoggingEndpoints();
  122. server.use(
  123. http.post('*/bug-report/submit', () => {
  124. return HttpResponse.json({
  125. success: true,
  126. message: 'Bug report submitted successfully!',
  127. issue_url: 'https://github.com/maziggy/bambuddy/issues/42',
  128. issue_number: 42,
  129. });
  130. })
  131. );
  132. render(<BugReportBubble />);
  133. await user.click(screen.getByRole('button'));
  134. await user.type(getDescriptionTextarea(), 'Test bug');
  135. const submitBtn = getSubmitButton();
  136. if (submitBtn) await user.click(submitBtn);
  137. // Wait for logging state, then click stop
  138. await waitFor(() => {
  139. expect(screen.queryByTestId('bug-report-step-reproduce')).toBeInTheDocument();
  140. });
  141. // Find and click the Stop & Submit button
  142. const stopBtn = screen.getAllByRole('button').find(
  143. (b) => b.className.includes('bg-red-500') && !b.className.includes('rounded-full')
  144. );
  145. if (stopBtn) await user.click(stopBtn);
  146. await waitFor(
  147. () => {
  148. expect(screen.getByText(/#42/)).toBeInTheDocument();
  149. },
  150. { timeout: 10000 }
  151. );
  152. });
  153. it('shows error state after failed submission', async () => {
  154. const user = userEvent.setup();
  155. setupLoggingEndpoints();
  156. server.use(
  157. http.post('*/bug-report/submit', () => {
  158. return HttpResponse.json({
  159. success: false,
  160. message: 'Relay not available',
  161. issue_url: null,
  162. issue_number: null,
  163. });
  164. })
  165. );
  166. render(<BugReportBubble />);
  167. await user.click(screen.getByRole('button'));
  168. await user.type(getDescriptionTextarea(), 'Test bug');
  169. const submitBtn = getSubmitButton();
  170. if (submitBtn) await user.click(submitBtn);
  171. // Wait for logging state, then click stop
  172. await waitFor(() => {
  173. expect(screen.queryByTestId('bug-report-step-reproduce')).toBeInTheDocument();
  174. });
  175. const stopBtn = screen.getAllByRole('button').find(
  176. (b) => b.className.includes('bg-red-500') && !b.className.includes('rounded-full')
  177. );
  178. if (stopBtn) await user.click(stopBtn);
  179. await waitFor(
  180. () => {
  181. expect(screen.getByText(/Relay not available/)).toBeInTheDocument();
  182. },
  183. { timeout: 10000 }
  184. );
  185. });
  186. it('has expandable data collection notice', async () => {
  187. const user = userEvent.setup();
  188. render(<BugReportBubble />);
  189. await user.click(screen.getByRole('button'));
  190. const details = document.querySelector('details');
  191. expect(details).toBeInTheDocument();
  192. });
  193. it('lists affected printers as collapsed rows, not stacked checklists', async () => {
  194. const user = userEvent.setup();
  195. setupDiagnosticEndpoints(
  196. [
  197. { id: 1, name: 'Printer Alpha' },
  198. { id: 2, name: 'Printer Beta' },
  199. { id: 3, name: 'Printer Gamma' },
  200. ],
  201. { 1: 'problems', 2: 'problems', 3: 'ok' }
  202. );
  203. render(<BugReportBubble />);
  204. await user.click(screen.getByRole('button'));
  205. // Summary counts problem printers against all scanned printers.
  206. expect(
  207. await screen.findByText('2 of 3 printers have connection issues')
  208. ).toBeInTheDocument();
  209. // Affected printers are listed by name; the healthy one is not.
  210. expect(screen.getByText('Printer Alpha')).toBeInTheDocument();
  211. expect(screen.getByText('Printer Beta')).toBeInTheDocument();
  212. expect(screen.queryByText('Printer Gamma')).not.toBeInTheDocument();
  213. // With more than one problem the per-printer checklists stay collapsed.
  214. expect(screen.queryByText(/Found problems that explain/)).not.toBeInTheDocument();
  215. // Expanding a row reveals just that printer's checklist.
  216. await user.click(screen.getByText('Printer Alpha'));
  217. expect(await screen.findByText(/Found problems that explain/)).toBeInTheDocument();
  218. });
  219. it('auto-expands the checklist when only one printer has problems', async () => {
  220. const user = userEvent.setup();
  221. setupDiagnosticEndpoints([{ id: 1, name: 'Solo Printer' }], { 1: 'problems' });
  222. render(<BugReportBubble />);
  223. await user.click(screen.getByRole('button'));
  224. expect(
  225. await screen.findByText('1 of 1 printers have connection issues')
  226. ).toBeInTheDocument();
  227. // Single problem → the checklist is expanded without a click.
  228. expect(await screen.findByText(/Found problems that explain/)).toBeInTheDocument();
  229. });
  230. it('shows the log-health panel when the scan finds known issues', async () => {
  231. const user = userEvent.setup();
  232. setupDiagnosticEndpoints([{ id: 1, name: 'Solo Printer' }], { 1: 'ok' });
  233. server.use(
  234. http.get('*/system/health', () =>
  235. HttpResponse.json({
  236. findings: [
  237. {
  238. signature_id: 'ftp-auth-rejected',
  239. severity: 'error',
  240. category: 'layer8',
  241. wiki_anchor: 'wrong-access-code',
  242. count: 3,
  243. first_seen: '2026-05-22 09:00:00,000',
  244. last_seen: '2026-05-22 10:00:00,000',
  245. sample: 'FTP connection permission error to [IP]',
  246. },
  247. ],
  248. scanned_entries: 500,
  249. log_available: true,
  250. summary: { total: 1, layer8: 1, environment: 0, bug: 0 },
  251. })
  252. )
  253. );
  254. render(<BugReportBubble />);
  255. await user.click(screen.getByRole('button'));
  256. expect(await screen.findByText('Known issues found in your logs')).toBeInTheDocument();
  257. expect(screen.getByText('Printer rejected the access code')).toBeInTheDocument();
  258. });
  259. // Step 2 asks the user to reproduce the problem, and the panel sits over the
  260. // part of the app they have to reach to do it. Closing it used to be the only
  261. // way through and it threw the run away: the reset-on-open effect put the
  262. // panel back on step 1 while the server stayed at DEBUG, with nothing left
  263. // that could stop it (#2847).
  264. describe('a logging run that outlives the panel (#2847)', () => {
  265. afterEach(() => {
  266. vi.mocked(localStorage.getItem).mockReset();
  267. });
  268. /** The mock is shared with every other localStorage reader in the tree --
  269. * the theme context among them -- so only answer for our own key. */
  270. const storeSession = (session: Record<string, unknown>) => {
  271. vi.mocked(localStorage.getItem).mockImplementation((key: string) =>
  272. key === 'bambuddy-bug-report-session' ? JSON.stringify(session) : null
  273. );
  274. };
  275. /** Types a description and presses Start, landing on step 2. */
  276. const startRun = async (user: ReturnType<typeof userEvent.setup>, description: string) => {
  277. await user.click(screen.getByRole('button'));
  278. await user.type(getDescriptionTextarea(), description);
  279. const startBtn = getSubmitButton();
  280. if (startBtn) await user.click(startBtn);
  281. await waitFor(() => {
  282. expect(screen.queryByTestId('bug-report-step-reproduce')).toBeInTheDocument();
  283. });
  284. };
  285. const closePanel = async (user: ReturnType<typeof userEvent.setup>) => {
  286. const closeButton = screen.getAllByRole('button').find((b) => b.querySelector('.lucide-x'));
  287. if (closeButton) await user.click(closeButton);
  288. await waitFor(() => {
  289. expect(screen.queryByTestId('bug-report-step-reproduce')).not.toBeInTheDocument();
  290. });
  291. };
  292. it('survives a close and reopens on the step it left, description intact', async () => {
  293. const user = userEvent.setup();
  294. let stopCalls = 0;
  295. let submitted: { description?: string } | null = null;
  296. server.use(
  297. http.post('*/bug-report/start-logging', () => HttpResponse.json({ started: true, was_debug: false })),
  298. http.post('*/bug-report/stop-logging', () => {
  299. stopCalls += 1;
  300. return HttpResponse.json({ logs: 'captured' });
  301. }),
  302. http.post('*/bug-report/submit', async ({ request }) => {
  303. submitted = (await request.json()) as { description?: string };
  304. return HttpResponse.json({ success: true, message: 'ok', issue_number: 7 });
  305. }),
  306. );
  307. render(<BugReportBubble />);
  308. await startRun(user, 'Queue page freezes');
  309. await closePanel(user);
  310. // Closing is not cancelling: the log level only comes back down when the
  311. // user presses Stop & Submit.
  312. expect(stopCalls).toBe(0);
  313. // The disc carries the run's colour, so a closed panel still says a
  314. // recording is live and that clicking gets back to it.
  315. const disc = screen.getByRole('button');
  316. expect(disc.className).toContain('bg-amber-500');
  317. await user.click(disc);
  318. expect(screen.getByTestId('bug-report-step-reproduce')).toBeInTheDocument();
  319. const stopBtn = screen.getAllByRole('button').find(
  320. (b) => b.className.includes('bg-red-500') && !b.className.includes('rounded-full')
  321. );
  322. if (stopBtn) await user.click(stopBtn);
  323. await waitFor(() => expect(submitted).not.toBeNull());
  324. expect(submitted!.description).toBe('Queue page freezes');
  325. expect(stopCalls).toBe(1);
  326. });
  327. it('picks the run back up after a reload while the server is still logging', async () => {
  328. const user = userEvent.setup();
  329. const startedAt = Date.now() - 30_000;
  330. storeSession({ description: 'Printer card goes blank', email: '', wasDebug: false, startedAt });
  331. server.use(
  332. http.get('*/support/debug-logging', () =>
  333. HttpResponse.json({
  334. enabled: true,
  335. enabled_at: new Date(startedAt).toISOString(),
  336. duration_seconds: 30,
  337. })
  338. ),
  339. );
  340. render(<BugReportBubble />);
  341. await waitFor(() => {
  342. expect(screen.getByRole('button').className).toContain('bg-amber-500');
  343. });
  344. await user.click(screen.getByRole('button'));
  345. expect(screen.getByTestId('bug-report-step-reproduce')).toBeInTheDocument();
  346. // Elapsed comes off the run's start time, so the reload does not reset it.
  347. expect(screen.getByText('00:30')).toBeInTheDocument();
  348. });
  349. it('drops a stored run the server already stopped', async () => {
  350. storeSession({ description: 'stale', email: '', wasDebug: false, startedAt: Date.now() - 30_000 });
  351. let stopCalls = 0;
  352. server.use(
  353. http.get('*/support/debug-logging', () =>
  354. HttpResponse.json({ enabled: false, enabled_at: null, duration_seconds: null })
  355. ),
  356. http.post('*/bug-report/stop-logging', () => {
  357. stopCalls += 1;
  358. return HttpResponse.json({ logs: '' });
  359. }),
  360. );
  361. render(<BugReportBubble />);
  362. await waitFor(() => expect(localStorage.removeItem).toHaveBeenCalled());
  363. expect(screen.getByRole('button').className).toContain('bg-red-500');
  364. // Logging is already off; there is nothing to put back.
  365. expect(stopCalls).toBe(0);
  366. });
  367. it('restores the log level for a run that outlived the cap, without filing it', async () => {
  368. let stopCalls = 0;
  369. let submitCalls = 0;
  370. storeSession({ description: 'from an hour ago', email: '', wasDebug: false, startedAt: Date.now() - 3_600_000 });
  371. server.use(
  372. http.get('*/support/debug-logging', () =>
  373. HttpResponse.json({ enabled: true, enabled_at: new Date(Date.now() - 3_600_000).toISOString(), duration_seconds: 3600 })
  374. ),
  375. http.post('*/bug-report/stop-logging', () => {
  376. stopCalls += 1;
  377. return HttpResponse.json({ logs: '' });
  378. }),
  379. http.post('*/bug-report/submit', () => {
  380. submitCalls += 1;
  381. return HttpResponse.json({ success: true, message: 'ok' });
  382. }),
  383. );
  384. render(<BugReportBubble />);
  385. // The level comes back down, because nothing else was going to do it...
  386. await waitFor(() => expect(stopCalls).toBe(1));
  387. // ...but an hour-old description is not a report anyone is still waiting
  388. // to be filed, and nobody is here to see it happen.
  389. expect(submitCalls).toBe(0);
  390. expect(screen.getByRole('button').className).toContain('bg-red-500');
  391. });
  392. });
  393. });