BugReportBubble.tsx 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. import { useState, useRef, useCallback, useEffect } from 'react';
  2. import { Bug, X, Loader2, CheckCircle, AlertCircle, AlertTriangle, Trash2, Upload, Circle, CheckCircle2, Stethoscope } from 'lucide-react';
  3. import { useTranslation } from 'react-i18next';
  4. import { useQuery } from '@tanstack/react-query';
  5. import { api, bugReportApi, supportApi, type PrinterDiagnosticResult } from '../api/client';
  6. import { DiagnosticChecklist } from './ConnectionDiagnostic';
  7. import { SystemHealthPanel } from './SystemHealthPanel';
  8. import { Collapsible } from './Collapsible';
  9. import { useIsMobile } from '../hooks/useIsMobile';
  10. type ViewState = 'form' | 'logging' | 'stopping' | 'review' | 'submitting' | 'success' | 'error';
  11. /** One scanned printer paired with its name — the diagnostic result alone
  12. * carries no name, and the bug-report panel lists affected printers by name. */
  13. type DiagnosticEntry = { name: string; result: PrinterDiagnosticResult };
  14. const MAX_DIMENSION = 1920;
  15. const JPEG_QUALITY = 0.7;
  16. const MAX_LOG_SECONDS = 300; // 5 minutes
  17. /**
  18. * A logging run outlives the panel that started it (#2847).
  19. *
  20. * Step 2 asks the user to reproduce the problem, and the panel sits over the
  21. * part of the app they have to reach to do that. Closing it has to be allowed,
  22. * so the run is written down rather than held only in component state: the
  23. * panel reopens on the step it left, and a reload lands there too instead of
  24. * leaving the server at DEBUG with nothing in the UI still tracking it.
  25. *
  26. * The screenshot is deliberately not persisted. A 1920px JPEG runs to hundreds
  27. * of kilobytes against an origin-wide budget this app shares with everything
  28. * else it stores, and it survives a close either way — only a reload loses it,
  29. * and it is the one optional field on the form.
  30. */
  31. const SESSION_KEY = 'bambuddy-bug-report-session';
  32. interface LoggingSession {
  33. description: string;
  34. email: string;
  35. /** Debug logging was already on before this run, so stopping must leave it on. */
  36. wasDebug: boolean;
  37. /** Wall clock. Elapsed is derived from it rather than counted in ticks, which
  38. * a background tab throttles — the 5-minute cap has to mean five minutes. */
  39. startedAt: number;
  40. }
  41. function readSession(): LoggingSession | null {
  42. try {
  43. const raw = window.localStorage.getItem(SESSION_KEY);
  44. if (!raw) return null;
  45. const parsed = JSON.parse(raw) as Partial<LoggingSession>;
  46. if (typeof parsed?.startedAt !== 'number') return null;
  47. return {
  48. description: typeof parsed.description === 'string' ? parsed.description : '',
  49. email: typeof parsed.email === 'string' ? parsed.email : '',
  50. wasDebug: parsed.wasDebug === true,
  51. startedAt: parsed.startedAt,
  52. };
  53. } catch {
  54. // Unparseable or unreadable. Treat it as no session rather than trapping
  55. // the user in a panel that cannot restore.
  56. return null;
  57. }
  58. }
  59. function writeSession(session: LoggingSession): void {
  60. try {
  61. window.localStorage.setItem(SESSION_KEY, JSON.stringify(session));
  62. } catch {
  63. // Quota, or storage refused outright in a locked-down browser. The run
  64. // still works and still survives a close; it just will not survive a
  65. // reload, which is no worse than before it was written down at all.
  66. }
  67. }
  68. function clearSession(): void {
  69. try {
  70. window.localStorage.removeItem(SESSION_KEY);
  71. } catch {
  72. // See writeSession.
  73. }
  74. }
  75. function compressImage(file: File): Promise<string> {
  76. return new Promise((resolve, reject) => {
  77. const img = new Image();
  78. img.onload = () => {
  79. let { width, height } = img;
  80. if (width > MAX_DIMENSION || height > MAX_DIMENSION) {
  81. const scale = MAX_DIMENSION / Math.max(width, height);
  82. width = Math.round(width * scale);
  83. height = Math.round(height * scale);
  84. }
  85. const canvas = document.createElement('canvas');
  86. canvas.width = width;
  87. canvas.height = height;
  88. const ctx = canvas.getContext('2d');
  89. if (!ctx) { reject(new Error('No canvas context')); return; }
  90. ctx.drawImage(img, 0, 0, width, height);
  91. const dataUrl = canvas.toDataURL('image/jpeg', JPEG_QUALITY);
  92. resolve(dataUrl.replace(/^data:[^;]+;base64,/, ''));
  93. };
  94. img.onerror = reject;
  95. img.src = URL.createObjectURL(file);
  96. });
  97. }
  98. function formatElapsed(seconds: number): string {
  99. const m = Math.floor(seconds / 60);
  100. const s = seconds % 60;
  101. return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
  102. }
  103. interface BugReportBubbleProps {
  104. /**
  105. * Render the floating disc in the bottom-right corner. False when the
  106. * trigger lives somewhere else — the compact header does this (#2750), so
  107. * the panel still mounts here while the button that opens it sits in the
  108. * header. The panel deliberately stays at the Layout root rather than
  109. * moving into the header with its button: the header is a ``fixed z-40``
  110. * element and therefore its own stacking context, so a ``z-50`` panel
  111. * nested inside it would be capped at the header's level and end up
  112. * underneath every ordinary z-50 modal in the app.
  113. */
  114. showTrigger?: boolean;
  115. /** Controlled open state. Falls back to internal state when omitted. */
  116. open?: boolean;
  117. onOpenChange?: (open: boolean) => void;
  118. /**
  119. * Fired when a logging run starts or ends. The floating disc shows a live run
  120. * itself, but the compact layout replaces the disc with a header button and
  121. * has no room for a timer, so Layout uses this to mark that button and to
  122. * offer a way back into the run from the debug-logging banner (#2847).
  123. */
  124. onLoggingChange?: (active: boolean) => void;
  125. }
  126. export function BugReportBubble({ showTrigger = true, open, onOpenChange, onLoggingChange }: BugReportBubbleProps = {}) {
  127. const { t } = useTranslation();
  128. const isMobile = useIsMobile();
  129. const [internalOpen, setInternalOpen] = useState(false);
  130. const isControlled = open !== undefined;
  131. const isOpen = isControlled ? open : internalOpen;
  132. const setIsOpen = useCallback(
  133. (next: boolean) => {
  134. if (!isControlled) setInternalOpen(next);
  135. onOpenChange?.(next);
  136. },
  137. [isControlled, onOpenChange],
  138. );
  139. const [viewState, setViewState] = useState<ViewState>('form');
  140. const [description, setDescription] = useState('');
  141. const [email, setEmail] = useState('');
  142. const [screenshot, setScreenshot] = useState<string | null>(null);
  143. const [isDragging, setIsDragging] = useState(false);
  144. const [issueUrl, setIssueUrl] = useState<string | null>(null);
  145. const [issueNumber, setIssueNumber] = useState<number | null>(null);
  146. const [errorMessage, setErrorMessage] = useState('');
  147. const [elapsedSeconds, setElapsedSeconds] = useState(0);
  148. const [startedAt, setStartedAt] = useState<number | null>(null);
  149. const [wasDebug, setWasDebug] = useState(false);
  150. // Logs from a stopped run, held until the user submits or discards them
  151. // (#3363). Stopping never files the report by itself.
  152. const [heldLogs, setHeldLogs] = useState<string | null>(null);
  153. const heldLogsRef = useRef(heldLogs);
  154. heldLogsRef.current = heldLogs;
  155. const modalRef = useRef<HTMLDivElement>(null);
  156. const fileInputRef = useRef<HTMLInputElement>(null);
  157. const handleStopLoggingRef = useRef<() => void>(() => {});
  158. // Read inside effects that must not re-run when the view changes.
  159. const viewStateRef = useRef(viewState);
  160. viewStateRef.current = viewState;
  161. const isLogging = viewState === 'logging';
  162. useEffect(() => {
  163. onLoggingChange?.(isLogging);
  164. }, [isLogging, onLoggingChange]);
  165. // Before the user files a report, diagnose configured printers. Most bug
  166. // reports are setup issues — surfacing a connection problem inline lets the
  167. // user self-fix instead of waiting on a triage round-trip. The result is
  168. // always shown (healthy or not) so the user can see the check ran.
  169. const diagnosticScan = useQuery({
  170. queryKey: ['bugReportDiagnostic'],
  171. enabled: isOpen && viewState === 'form',
  172. staleTime: 30_000,
  173. queryFn: async (): Promise<DiagnosticEntry[]> => {
  174. const printers = await api.getPrinters();
  175. const entries = await Promise.all(
  176. printers.map(async (p) => {
  177. const result = await api.diagnosePrinter(p.id).catch(() => null);
  178. return result ? { name: p.name, result } : null;
  179. }),
  180. );
  181. return entries.filter((e): e is DiagnosticEntry => e !== null);
  182. },
  183. });
  184. const diagnosticEntries = diagnosticScan.data ?? [];
  185. const diagnosticProblems = diagnosticEntries.filter((e) => e.result.overall === 'problems');
  186. // Scan recent logs against the known-issue catalog. Like the diagnostic
  187. // above, this surfaces user-fixable ("layer 8") problems before a report is
  188. // filed. Only shown when something matched — a clean scan stays silent so
  189. // the form is uncluttered.
  190. const logHealthScan = useQuery({
  191. queryKey: ['bugReportLogHealth'],
  192. enabled: isOpen && viewState === 'form',
  193. staleTime: 30_000,
  194. queryFn: api.getSystemHealth,
  195. });
  196. const logFindings = logHealthScan.data?.findings ?? [];
  197. // Elapsed timer for logging phase — auto-stop at 5 minutes. Measured against
  198. // the run's start time rather than counted in ticks: the run continues while
  199. // the panel is closed and while the tab is in the background, where timers
  200. // are throttled hard enough that a tick count is not a clock.
  201. useEffect(() => {
  202. if (viewState !== 'logging' || startedAt === null) return;
  203. const tick = () => {
  204. const elapsed = Math.floor((Date.now() - startedAt) / 1000);
  205. setElapsedSeconds(elapsed);
  206. if (elapsed >= MAX_LOG_SECONDS) handleStopLoggingRef.current();
  207. };
  208. tick();
  209. const timer = setInterval(tick, 1000);
  210. return () => clearInterval(timer);
  211. }, [viewState, startedAt]);
  212. // Reset on open rather than in the click handler: the panel now has two
  213. // possible triggers (the floating disc here, and the compact header's button
  214. // which only flips the controlled flag), and a stale half-filled form
  215. // reappearing for one of them would be a nasty little inconsistency.
  216. //
  217. // A run in progress is the exception (#2847). Step 2 asks the user to
  218. // reproduce the problem, which usually means reaching a part of the app the
  219. // panel is sitting on top of, so closing it has to be allowed — and the only
  220. // thing that stops debug logging is the Stop Logging button on the step this
  221. // reset used to throw away. A stopped run's logs are kept the same way: on
  222. // the review, while sending, and after a failed send, which reopens on the
  223. // review (#3363). Debug logging is already off by then, so they cannot be
  224. // captured again.
  225. useEffect(() => {
  226. if (!isOpen) return;
  227. if (['logging', 'stopping', 'review', 'submitting'].includes(viewStateRef.current)) return;
  228. if (viewStateRef.current === 'error' && heldLogsRef.current !== null) {
  229. setViewState('review');
  230. return;
  231. }
  232. setViewState('form');
  233. setDescription('');
  234. setEmail('');
  235. setScreenshot(null);
  236. setIssueUrl(null);
  237. setIssueNumber(null);
  238. setErrorMessage('');
  239. setElapsedSeconds(0);
  240. setStartedAt(null);
  241. setWasDebug(false);
  242. setHeldLogs(null);
  243. }, [isOpen]);
  244. // Pick a run back up after a reload. The panel's own state is gone by then,
  245. // but the server still has the log level raised, so without this the app is
  246. // left logging at DEBUG with nothing in the report flow still pointing at it.
  247. useEffect(() => {
  248. const session = readSession();
  249. if (!session) return;
  250. let cancelled = false;
  251. (async () => {
  252. let stillLogging: boolean;
  253. try {
  254. stillLogging = (await supportApi.getDebugLoggingState()).enabled;
  255. } catch {
  256. // Can't tell. Leave the session written down for the next load rather
  257. // than dropping a run that may well still be going.
  258. return;
  259. }
  260. if (cancelled || viewStateRef.current !== 'form') return;
  261. if (!stillLogging) {
  262. // Switched off from the System page, or the run was finished in another
  263. // tab. Either way there is nothing left to resume.
  264. clearSession();
  265. return;
  266. }
  267. const elapsed = Math.floor((Date.now() - session.startedAt) / 1000);
  268. if (elapsed >= MAX_LOG_SECONDS) {
  269. // Past the cap with nobody watching — the browser was closed, or the
  270. // tab sat elsewhere for an hour. Put the log level back, but do not
  271. // submit: a description written that long ago is not a report anyone is
  272. // still expecting to be filed, and no one is here to see it happen.
  273. try {
  274. await bugReportApi.stopLogging(session.wasDebug);
  275. } catch {
  276. // The banner in Layout still shows the raised level, and the System
  277. // page can lower it.
  278. }
  279. clearSession();
  280. return;
  281. }
  282. setDescription(session.description);
  283. setEmail(session.email);
  284. setWasDebug(session.wasDebug);
  285. setStartedAt(session.startedAt);
  286. setElapsedSeconds(elapsed);
  287. setViewState('logging');
  288. })();
  289. return () => { cancelled = true; };
  290. }, []);
  291. const handleOpen = () => setIsOpen(true);
  292. const handleClose = () => {
  293. setIsOpen(false);
  294. };
  295. const handleFile = useCallback(async (file: File) => {
  296. if (!file.type.startsWith('image/')) return;
  297. try {
  298. const b64 = await compressImage(file);
  299. setScreenshot(b64);
  300. } catch {
  301. // Ignore read errors
  302. }
  303. }, []);
  304. const handlePaste = useCallback((e: React.ClipboardEvent) => {
  305. const items = e.clipboardData?.items;
  306. if (!items) return;
  307. for (const item of items) {
  308. if (item.type.startsWith('image/')) {
  309. const file = item.getAsFile();
  310. if (file) handleFile(file);
  311. break;
  312. }
  313. }
  314. }, [handleFile]);
  315. const handleDragOver = useCallback((e: React.DragEvent) => {
  316. e.preventDefault();
  317. setIsDragging(true);
  318. }, []);
  319. const handleDragLeave = useCallback((e: React.DragEvent) => {
  320. e.preventDefault();
  321. setIsDragging(false);
  322. }, []);
  323. const handleDrop = useCallback((e: React.DragEvent) => {
  324. e.preventDefault();
  325. setIsDragging(false);
  326. const file = e.dataTransfer.files?.[0];
  327. if (file) handleFile(file);
  328. }, [handleFile]);
  329. const handleStartLogging = async () => {
  330. if (!description.trim()) return;
  331. try {
  332. const result = await bugReportApi.startLogging();
  333. const runStartedAt = Date.now();
  334. setWasDebug(result.was_debug);
  335. setStartedAt(runStartedAt);
  336. setElapsedSeconds(0);
  337. setViewState('logging');
  338. writeSession({
  339. description: description.trim(),
  340. email: email.trim(),
  341. wasDebug: result.was_debug,
  342. startedAt: runStartedAt,
  343. });
  344. } catch (err) {
  345. setErrorMessage(err instanceof Error ? err.message : t('bugReport.unexpectedError'));
  346. setViewState('error');
  347. }
  348. };
  349. const handleStopLogging = async () => {
  350. // The cap can fire while the panel is closed. Show the panel so the review
  351. // it ends on is in front of the user instead of behind them.
  352. setIsOpen(true);
  353. // The run is over from here whichever way it goes, so there is nothing left
  354. // to resume — including when stopping fails, where the banner in Layout is
  355. // what surfaces a log level that did not come back down.
  356. clearSession();
  357. setStartedAt(null);
  358. setViewState('stopping');
  359. try {
  360. const stopResult = await bugReportApi.stopLogging(wasDebug);
  361. // A public GitHub issue is filed only from the review step: a click on
  362. // stop (#3363) or the 5-minute cap is not a decision to send.
  363. setHeldLogs(stopResult.logs ?? '');
  364. setViewState('review');
  365. } catch (err) {
  366. setErrorMessage(err instanceof Error ? err.message : t('bugReport.unexpectedError'));
  367. setViewState('error');
  368. }
  369. };
  370. handleStopLoggingRef.current = handleStopLogging;
  371. const handleDiscard = () => {
  372. setHeldLogs(null);
  373. setViewState('form');
  374. setIsOpen(false);
  375. };
  376. const handleSubmitReport = async (debugLogs: string) => {
  377. setViewState('submitting');
  378. try {
  379. const result = await bugReportApi.submit({
  380. description: description.trim(),
  381. email: email.trim() || undefined,
  382. screenshot_base64: screenshot || undefined,
  383. include_support_info: true,
  384. debug_logs: debugLogs || undefined,
  385. });
  386. if (result.success) {
  387. setIssueUrl(result.issue_url || null);
  388. setIssueNumber(result.issue_number || null);
  389. setHeldLogs(null);
  390. setViewState('success');
  391. } else {
  392. setErrorMessage(result.message);
  393. setViewState('error');
  394. }
  395. } catch (err) {
  396. setErrorMessage(err instanceof Error ? err.message : t('bugReport.unexpectedError'));
  397. setViewState('error');
  398. }
  399. };
  400. return (
  401. <>
  402. {/* Floating bubble. Absent below the sidebar-compact breakpoint, where
  403. the compact header carries the trigger instead — see Layout. */}
  404. {showTrigger && (
  405. <button
  406. onClick={handleOpen}
  407. className={`fixed bottom-4 right-4 z-40 w-12 h-12 rounded-full text-white shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-110 flex items-center justify-center ${
  408. // Amber while a run is going, matching the debug-logging banner, so
  409. // a closed panel still says the recording is live and clickable.
  410. isLogging ? 'bg-amber-500 hover:bg-amber-600' : 'bg-red-500 hover:bg-red-600'
  411. }`}
  412. title={isLogging ? t('bugReport.resumeRecording', { elapsed: formatElapsed(elapsedSeconds) }) : t('bugReport.title')}
  413. >
  414. {isLogging && (
  415. <span className="absolute inset-0 rounded-full bg-amber-400 opacity-75 animate-ping" />
  416. )}
  417. <Bug className="w-5 h-5 relative" />
  418. </button>
  419. )}
  420. {/* Slide-in panel anchored to bottom-right; a bottom sheet on phones.
  421. The desktop geometry cannot be reused there: `w-full` resolves against
  422. the viewport for a fixed element, so on a 375px screen the panel was
  423. 375px wide and then pushed 16px in from the right, putting its left
  424. edge at -16px and cutting a strip of the form off-screen. `max-w-md`
  425. hid this on anything above ~464px wide. */}
  426. {isOpen && (
  427. <div
  428. id="bug-report-modal"
  429. className={
  430. isMobile
  431. ? 'fixed inset-x-0 bottom-0 z-50'
  432. : showTrigger
  433. ? 'fixed bottom-20 right-4 z-50 w-full max-w-md'
  434. // Trigger is in the compact header, so anchor under it rather
  435. // than to a corner the user did not touch. Only reachable
  436. // between the mobile and sidebar-compact breakpoints — below
  437. // that it is a bottom sheet, above it the disc is back.
  438. : 'fixed top-16 right-4 z-50 w-full max-w-md'
  439. }
  440. onPaste={handlePaste}
  441. >
  442. <div
  443. ref={modalRef}
  444. className={`bg-white dark:bg-gray-800 shadow-2xl border border-gray-200 dark:border-gray-700 overflow-y-auto ${
  445. isMobile
  446. ? 'rounded-t-2xl max-h-[85vh] pb-[env(safe-area-inset-bottom)]'
  447. : 'rounded-lg max-h-[80vh]'
  448. }`}
  449. >
  450. {/* Header */}
  451. <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 sticky top-0 bg-white dark:bg-gray-800 z-10">
  452. <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
  453. <Bug className="w-5 h-5 text-red-500" />
  454. {t('bugReport.title')}
  455. </h2>
  456. <button
  457. onClick={handleClose}
  458. className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
  459. >
  460. <X className="w-5 h-5" />
  461. </button>
  462. </div>
  463. <div className="p-4 space-y-4">
  464. {viewState === 'form' && (
  465. <>
  466. {/* Connection diagnostic — scanned on form-open. A healthy
  467. fleet shows a single confirmation line. When printers
  468. have problems, each is a collapsed row (auto-expanded
  469. when only one) so the form stays reachable regardless
  470. of how many printers are configured. */}
  471. {diagnosticScan.isLoading && (
  472. <div className="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
  473. <Loader2 className="w-3.5 h-3.5 animate-spin" />
  474. {t('bugReport.diagnosticChecking')}
  475. </div>
  476. )}
  477. {!diagnosticScan.isLoading && diagnosticProblems.length > 0 && (
  478. <div className="rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3 space-y-3">
  479. <div className="flex items-start gap-2">
  480. <Stethoscope className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  481. <div>
  482. <p className="text-sm font-medium text-amber-700 dark:text-amber-300">
  483. {t('bugReport.diagnosticSummary', {
  484. problems: diagnosticProblems.length,
  485. total: diagnosticEntries.length,
  486. })}
  487. </p>
  488. <p className="text-xs text-amber-800 dark:text-amber-200 mt-0.5">
  489. {t('bugReport.diagnosticIntro')}
  490. </p>
  491. </div>
  492. </div>
  493. <div className="space-y-2">
  494. {diagnosticProblems.map((entry) => (
  495. <Collapsible
  496. key={entry.result.printer_id ?? entry.result.ip_address}
  497. defaultOpen={diagnosticProblems.length === 1}
  498. className="rounded-lg bg-amber-100/60 dark:bg-amber-900/30 px-3 py-2"
  499. summary={
  500. <div className="flex items-center gap-2 min-w-0">
  501. <AlertTriangle className="w-4 h-4 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  502. <span className="text-sm font-medium text-amber-800 dark:text-amber-200 truncate">
  503. {entry.name}
  504. </span>
  505. </div>
  506. }
  507. >
  508. <DiagnosticChecklist result={entry.result} />
  509. </Collapsible>
  510. ))}
  511. </div>
  512. </div>
  513. )}
  514. {!diagnosticScan.isLoading &&
  515. diagnosticEntries.length > 0 &&
  516. diagnosticProblems.length === 0 && (
  517. <div className="flex items-start gap-2 rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3">
  518. <CheckCircle className="w-4 h-4 mt-0.5 flex-shrink-0 text-green-600 dark:text-green-400" />
  519. <p className="text-xs text-green-800 dark:text-green-200">
  520. {t('bugReport.diagnosticHealthy')}
  521. </p>
  522. </div>
  523. )}
  524. {/* Log-health scan — known issues found in recent logs.
  525. Shown only when something matched. */}
  526. {!logHealthScan.isLoading && logFindings.length > 0 && logHealthScan.data && (
  527. <div className="rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3 space-y-3">
  528. <div className="flex items-start gap-2">
  529. <Stethoscope className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  530. <div>
  531. <p className="text-sm font-medium text-amber-700 dark:text-amber-300">
  532. {t('bugReport.logHealthSummary')}
  533. </p>
  534. <p className="text-xs text-amber-800 dark:text-amber-200 mt-0.5">
  535. {t('bugReport.logHealthIntro')}
  536. </p>
  537. </div>
  538. </div>
  539. <SystemHealthPanel result={logHealthScan.data} />
  540. </div>
  541. )}
  542. {/* Description */}
  543. <div>
  544. <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
  545. {t('bugReport.description')} *
  546. </label>
  547. <textarea
  548. value={description}
  549. onChange={(e) => setDescription(e.target.value)}
  550. placeholder={t('bugReport.descriptionPlaceholder')}
  551. rows={3}
  552. className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-vertical"
  553. />
  554. </div>
  555. {/* Email (optional) */}
  556. <div>
  557. <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
  558. {t('bugReport.email')}
  559. </label>
  560. <input
  561. type="email"
  562. value={email}
  563. onChange={(e) => setEmail(e.target.value)}
  564. placeholder={t('bugReport.emailPlaceholder')}
  565. className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
  566. />
  567. <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
  568. {t('bugReport.emailPrivacy')}
  569. </p>
  570. </div>
  571. {/* Screenshot — upload, paste, or drag */}
  572. <div>
  573. <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
  574. {t('bugReport.screenshot')}
  575. </label>
  576. {screenshot ? (
  577. <div className="relative">
  578. <img
  579. src={`data:image/jpeg;base64,${screenshot}`}
  580. alt={t('bugReport.screenshot')}
  581. className="w-full max-h-40 object-contain rounded-lg border border-gray-200 dark:border-gray-600"
  582. />
  583. <button
  584. onClick={() => setScreenshot(null)}
  585. className="absolute top-2 right-2 p-1 bg-red-500 hover:bg-red-600 text-white rounded-full shadow"
  586. title={t('common.delete')}
  587. >
  588. <Trash2 className="w-3 h-3" />
  589. </button>
  590. </div>
  591. ) : (
  592. <button
  593. type="button"
  594. onClick={() => fileInputRef.current?.click()}
  595. onDragOver={handleDragOver}
  596. onDragLeave={handleDragLeave}
  597. onDrop={handleDrop}
  598. className={`w-full flex flex-col items-center gap-2 px-4 py-4 border-2 border-dashed rounded-lg transition-colors cursor-pointer ${
  599. isDragging
  600. ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-500'
  601. : 'border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:border-gray-400 dark:hover:border-gray-500 hover:text-gray-600 dark:hover:text-gray-300'
  602. }`}
  603. >
  604. <Upload className="w-5 h-5" />
  605. <span className="text-sm">{t('bugReport.uploadOrPaste')}</span>
  606. </button>
  607. )}
  608. <input
  609. ref={fileInputRef}
  610. type="file"
  611. accept="image/*"
  612. className="hidden"
  613. onChange={(e) => {
  614. const file = e.target.files?.[0];
  615. if (file) handleFile(file);
  616. e.target.value = '';
  617. }}
  618. />
  619. </div>
  620. {/* Data collection notice */}
  621. <details className="text-xs bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3">
  622. <summary className="cursor-pointer font-medium text-amber-700 dark:text-amber-300 hover:text-amber-800 dark:hover:text-amber-200">
  623. {t('bugReport.dataCollectedSummary')}
  624. </summary>
  625. <div className="mt-2 space-y-2 pl-2 border-l-2 border-amber-300 dark:border-amber-700 text-amber-800 dark:text-amber-200">
  626. <p className="font-medium">{t('bugReport.dataIncluded')}</p>
  627. <p>{t('bugReport.dataIncludedList')}</p>
  628. <p className="font-medium">{t('bugReport.dataNeverIncluded')}</p>
  629. <p>{t('bugReport.dataNeverIncludedList')}</p>
  630. </div>
  631. </details>
  632. {/* Buttons */}
  633. <div className="flex justify-end gap-2 pt-2">
  634. <button
  635. onClick={handleClose}
  636. className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
  637. >
  638. {t('common.cancel')}
  639. </button>
  640. <button
  641. onClick={handleStartLogging}
  642. disabled={!description.trim()}
  643. className="px-4 py-2 text-sm font-medium text-white bg-red-500 hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg transition-colors"
  644. >
  645. {t('bugReport.startLogging')}
  646. </button>
  647. </div>
  648. </>
  649. )}
  650. {viewState === 'logging' && (
  651. <div className="py-6 space-y-6">
  652. {/* 3-step progress indicator */}
  653. <div className="space-y-3 px-2">
  654. {/* Step 1: Completed */}
  655. <div className="flex items-center gap-3">
  656. <CheckCircle2 className="w-5 h-5 text-green-500 flex-shrink-0" />
  657. <span className="text-sm text-green-700 dark:text-green-400">{t('bugReport.stepEnableLogging')}</span>
  658. </div>
  659. {/* Step 2: Active */}
  660. <div className="flex items-center gap-3">
  661. <span className="relative flex h-5 w-5 flex-shrink-0 items-center justify-center">
  662. <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"></span>
  663. <span className="relative inline-flex rounded-full h-3 w-3 bg-blue-500"></span>
  664. </span>
  665. <span data-testid="bug-report-step-reproduce" className="text-sm font-medium text-blue-700 dark:text-blue-300">{t('bugReport.stepReproduce')}</span>
  666. </div>
  667. {/* Step 3: Upcoming */}
  668. <div className="flex items-center gap-3">
  669. <Circle className="w-5 h-5 text-gray-300 dark:text-gray-600 flex-shrink-0" />
  670. <span className="text-sm text-gray-400 dark:text-gray-500">{t('bugReport.stepReview')}</span>
  671. </div>
  672. </div>
  673. {/* Elapsed timer */}
  674. <div className="text-center">
  675. <p className="text-3xl font-mono text-blue-500">{formatElapsed(elapsedSeconds)}</p>
  676. <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">{t('bugReport.maxDuration', { minutes: 5 })}</p>
  677. {/* The panel covers whatever has to be clicked to reproduce
  678. the problem, so say plainly that closing it is fine. */}
  679. <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">{t('bugReport.closeKeepsRecording')}</p>
  680. </div>
  681. {/* Stop button */}
  682. <div className="flex justify-center">
  683. <button
  684. onClick={handleStopLogging}
  685. className="px-6 py-2.5 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors"
  686. >
  687. {t('bugReport.stopLogging')}
  688. </button>
  689. </div>
  690. </div>
  691. )}
  692. {viewState === 'review' && heldLogs !== null && (
  693. <div data-testid="bug-report-review" className="py-4 space-y-4">
  694. <div className="space-y-2">
  695. <p className="text-sm font-semibold text-gray-900 dark:text-white">{t('bugReport.reviewTitle')}</p>
  696. <p className="text-sm text-gray-600 dark:text-gray-400">{t('bugReport.reviewBody')}</p>
  697. <p className="text-xs text-gray-500 dark:text-gray-400">
  698. {t('bugReport.reviewLogLines', { lines: heldLogs.split('\n').filter((l) => l.trim()).length })}
  699. </p>
  700. </div>
  701. <div className="flex justify-end gap-2">
  702. <button
  703. onClick={handleDiscard}
  704. className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
  705. >
  706. {t('bugReport.discard')}
  707. </button>
  708. <button
  709. onClick={() => handleSubmitReport(heldLogs)}
  710. className="px-4 py-2 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors"
  711. >
  712. {t('bugReport.submit')}
  713. </button>
  714. </div>
  715. </div>
  716. )}
  717. {(viewState === 'stopping' || viewState === 'submitting') && (
  718. <div className="flex flex-col items-center justify-center py-6 gap-3">
  719. <Loader2 className="w-8 h-8 animate-spin text-blue-500" />
  720. <p className="text-sm text-gray-600 dark:text-gray-400 text-center">
  721. {viewState === 'stopping' ? t('bugReport.collectingLogs') : t('bugReport.submitting')}
  722. </p>
  723. {viewState === 'submitting' && (
  724. // Diagnostics are run server-side inside the submit call
  725. // (#1506 follow-up): the bubble already displays current
  726. // results inline, but the submitted report now also
  727. // includes a snapshot. Wait is bounded but noticeable —
  728. // list what's running so the user knows why.
  729. <ul className="text-xs text-gray-500 dark:text-gray-400 list-disc list-inside space-y-0.5">
  730. <li>{t('bugReport.submittingStepConnection')}</li>
  731. <li>{t('bugReport.submittingStepVirtualPrinters')}</li>
  732. <li>{t('bugReport.submittingStepLogScan')}</li>
  733. <li>{t('bugReport.submittingStepSubmit')}</li>
  734. </ul>
  735. )}
  736. </div>
  737. )}
  738. {viewState === 'success' && (
  739. <div className="flex flex-col items-center justify-center py-8 gap-3">
  740. <CheckCircle className="w-12 h-12 text-green-500" />
  741. <p className="text-lg font-semibold text-gray-900 dark:text-white">{t('bugReport.thankYou')}</p>
  742. <p className="text-sm text-gray-600 dark:text-gray-400">{t('bugReport.submitted')}</p>
  743. {issueUrl && (
  744. <a
  745. href={issueUrl}
  746. target="_blank"
  747. rel="noopener noreferrer"
  748. className="text-sm text-blue-500 hover:text-blue-600 underline"
  749. >
  750. {t('bugReport.viewIssue')} #{issueNumber}
  751. </a>
  752. )}
  753. <button
  754. onClick={handleClose}
  755. className="mt-4 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
  756. >
  757. {t('common.close')}
  758. </button>
  759. </div>
  760. )}
  761. {viewState === 'error' && (
  762. <div className="flex flex-col items-center justify-center py-8 gap-3">
  763. <AlertCircle className="w-12 h-12 text-red-500" />
  764. <p className="text-lg font-semibold text-gray-900 dark:text-white">{t('bugReport.submitFailed')}</p>
  765. <p className="text-sm text-gray-600 dark:text-gray-400 text-center">{errorMessage}</p>
  766. <div className="flex gap-2 mt-4">
  767. <button
  768. // A failed send keeps its logs, so trying again goes back
  769. // to the review rather than to a new recording.
  770. onClick={() => setViewState(heldLogs !== null ? 'review' : 'form')}
  771. className="px-4 py-2 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors"
  772. >
  773. {t('bugReport.submit')}
  774. </button>
  775. <button
  776. onClick={handleClose}
  777. className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
  778. >
  779. {t('common.close')}
  780. </button>
  781. </div>
  782. </div>
  783. )}
  784. </div>
  785. </div>
  786. </div>
  787. )}
  788. </>
  789. );
  790. }