BugReportBubble.tsx 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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' | '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. const modalRef = useRef<HTMLDivElement>(null);
  151. const fileInputRef = useRef<HTMLInputElement>(null);
  152. const handleStopLoggingRef = useRef<() => void>(() => {});
  153. // Read inside effects that must not re-run when the view changes.
  154. const viewStateRef = useRef(viewState);
  155. viewStateRef.current = viewState;
  156. const isLogging = viewState === 'logging';
  157. useEffect(() => {
  158. onLoggingChange?.(isLogging);
  159. }, [isLogging, onLoggingChange]);
  160. // Before the user files a report, diagnose configured printers. Most bug
  161. // reports are setup issues — surfacing a connection problem inline lets the
  162. // user self-fix instead of waiting on a triage round-trip. The result is
  163. // always shown (healthy or not) so the user can see the check ran.
  164. const diagnosticScan = useQuery({
  165. queryKey: ['bugReportDiagnostic'],
  166. enabled: isOpen && viewState === 'form',
  167. staleTime: 30_000,
  168. queryFn: async (): Promise<DiagnosticEntry[]> => {
  169. const printers = await api.getPrinters();
  170. const entries = await Promise.all(
  171. printers.map(async (p) => {
  172. const result = await api.diagnosePrinter(p.id).catch(() => null);
  173. return result ? { name: p.name, result } : null;
  174. }),
  175. );
  176. return entries.filter((e): e is DiagnosticEntry => e !== null);
  177. },
  178. });
  179. const diagnosticEntries = diagnosticScan.data ?? [];
  180. const diagnosticProblems = diagnosticEntries.filter((e) => e.result.overall === 'problems');
  181. // Scan recent logs against the known-issue catalog. Like the diagnostic
  182. // above, this surfaces user-fixable ("layer 8") problems before a report is
  183. // filed. Only shown when something matched — a clean scan stays silent so
  184. // the form is uncluttered.
  185. const logHealthScan = useQuery({
  186. queryKey: ['bugReportLogHealth'],
  187. enabled: isOpen && viewState === 'form',
  188. staleTime: 30_000,
  189. queryFn: api.getSystemHealth,
  190. });
  191. const logFindings = logHealthScan.data?.findings ?? [];
  192. // Elapsed timer for logging phase — auto-stop at 5 minutes. Measured against
  193. // the run's start time rather than counted in ticks: the run continues while
  194. // the panel is closed and while the tab is in the background, where timers
  195. // are throttled hard enough that a tick count is not a clock.
  196. useEffect(() => {
  197. if (viewState !== 'logging' || startedAt === null) return;
  198. const tick = () => {
  199. const elapsed = Math.floor((Date.now() - startedAt) / 1000);
  200. setElapsedSeconds(elapsed);
  201. if (elapsed >= MAX_LOG_SECONDS) handleStopLoggingRef.current();
  202. };
  203. tick();
  204. const timer = setInterval(tick, 1000);
  205. return () => clearInterval(timer);
  206. }, [viewState, startedAt]);
  207. // Reset on open rather than in the click handler: the panel now has two
  208. // possible triggers (the floating disc here, and the compact header's button
  209. // which only flips the controlled flag), and a stale half-filled form
  210. // reappearing for one of them would be a nasty little inconsistency.
  211. //
  212. // A run in progress is the exception (#2847). Step 2 asks the user to
  213. // reproduce the problem, which usually means reaching a part of the app the
  214. // panel is sitting on top of, so closing it has to be allowed — and the only
  215. // thing that stops debug logging is the Stop & Submit button on the step this
  216. // reset used to throw away.
  217. useEffect(() => {
  218. if (!isOpen) return;
  219. if (viewStateRef.current === 'logging' || viewStateRef.current === 'stopping' || viewStateRef.current === 'submitting') return;
  220. setViewState('form');
  221. setDescription('');
  222. setEmail('');
  223. setScreenshot(null);
  224. setIssueUrl(null);
  225. setIssueNumber(null);
  226. setErrorMessage('');
  227. setElapsedSeconds(0);
  228. setStartedAt(null);
  229. setWasDebug(false);
  230. }, [isOpen]);
  231. // Pick a run back up after a reload. The panel's own state is gone by then,
  232. // but the server still has the log level raised, so without this the app is
  233. // left logging at DEBUG with nothing in the report flow still pointing at it.
  234. useEffect(() => {
  235. const session = readSession();
  236. if (!session) return;
  237. let cancelled = false;
  238. (async () => {
  239. let stillLogging: boolean;
  240. try {
  241. stillLogging = (await supportApi.getDebugLoggingState()).enabled;
  242. } catch {
  243. // Can't tell. Leave the session written down for the next load rather
  244. // than dropping a run that may well still be going.
  245. return;
  246. }
  247. if (cancelled || viewStateRef.current !== 'form') return;
  248. if (!stillLogging) {
  249. // Switched off from the System page, or the run was finished in another
  250. // tab. Either way there is nothing left to resume.
  251. clearSession();
  252. return;
  253. }
  254. const elapsed = Math.floor((Date.now() - session.startedAt) / 1000);
  255. if (elapsed >= MAX_LOG_SECONDS) {
  256. // Past the cap with nobody watching — the browser was closed, or the
  257. // tab sat elsewhere for an hour. Put the log level back, but do not
  258. // submit: a description written that long ago is not a report anyone is
  259. // still expecting to be filed, and no one is here to see it happen.
  260. try {
  261. await bugReportApi.stopLogging(session.wasDebug);
  262. } catch {
  263. // The banner in Layout still shows the raised level, and the System
  264. // page can lower it.
  265. }
  266. clearSession();
  267. return;
  268. }
  269. setDescription(session.description);
  270. setEmail(session.email);
  271. setWasDebug(session.wasDebug);
  272. setStartedAt(session.startedAt);
  273. setElapsedSeconds(elapsed);
  274. setViewState('logging');
  275. })();
  276. return () => { cancelled = true; };
  277. }, []);
  278. const handleOpen = () => setIsOpen(true);
  279. const handleClose = () => {
  280. setIsOpen(false);
  281. };
  282. const handleFile = useCallback(async (file: File) => {
  283. if (!file.type.startsWith('image/')) return;
  284. try {
  285. const b64 = await compressImage(file);
  286. setScreenshot(b64);
  287. } catch {
  288. // Ignore read errors
  289. }
  290. }, []);
  291. const handlePaste = useCallback((e: React.ClipboardEvent) => {
  292. const items = e.clipboardData?.items;
  293. if (!items) return;
  294. for (const item of items) {
  295. if (item.type.startsWith('image/')) {
  296. const file = item.getAsFile();
  297. if (file) handleFile(file);
  298. break;
  299. }
  300. }
  301. }, [handleFile]);
  302. const handleDragOver = useCallback((e: React.DragEvent) => {
  303. e.preventDefault();
  304. setIsDragging(true);
  305. }, []);
  306. const handleDragLeave = useCallback((e: React.DragEvent) => {
  307. e.preventDefault();
  308. setIsDragging(false);
  309. }, []);
  310. const handleDrop = useCallback((e: React.DragEvent) => {
  311. e.preventDefault();
  312. setIsDragging(false);
  313. const file = e.dataTransfer.files?.[0];
  314. if (file) handleFile(file);
  315. }, [handleFile]);
  316. const handleStartLogging = async () => {
  317. if (!description.trim()) return;
  318. try {
  319. const result = await bugReportApi.startLogging();
  320. const runStartedAt = Date.now();
  321. setWasDebug(result.was_debug);
  322. setStartedAt(runStartedAt);
  323. setElapsedSeconds(0);
  324. setViewState('logging');
  325. writeSession({
  326. description: description.trim(),
  327. email: email.trim(),
  328. wasDebug: result.was_debug,
  329. startedAt: runStartedAt,
  330. });
  331. } catch (err) {
  332. setErrorMessage(err instanceof Error ? err.message : t('bugReport.unexpectedError'));
  333. setViewState('error');
  334. }
  335. };
  336. const handleStopLogging = async () => {
  337. // The cap can fire while the panel is closed, and stopping submits. Show
  338. // the panel so that happens in front of the user instead of behind them.
  339. setIsOpen(true);
  340. // The run is over from here whichever way it goes, so there is nothing left
  341. // to resume — including when stopping fails, where the banner in Layout is
  342. // what surfaces a log level that did not come back down.
  343. clearSession();
  344. setStartedAt(null);
  345. setViewState('stopping');
  346. try {
  347. const stopResult = await bugReportApi.stopLogging(wasDebug);
  348. await handleSubmitReport(stopResult.logs);
  349. } catch (err) {
  350. setErrorMessage(err instanceof Error ? err.message : t('bugReport.unexpectedError'));
  351. setViewState('error');
  352. }
  353. };
  354. handleStopLoggingRef.current = handleStopLogging;
  355. const handleSubmitReport = async (debugLogs: string) => {
  356. setViewState('submitting');
  357. try {
  358. const result = await bugReportApi.submit({
  359. description: description.trim(),
  360. email: email.trim() || undefined,
  361. screenshot_base64: screenshot || undefined,
  362. include_support_info: true,
  363. debug_logs: debugLogs || undefined,
  364. });
  365. if (result.success) {
  366. setIssueUrl(result.issue_url || null);
  367. setIssueNumber(result.issue_number || null);
  368. setViewState('success');
  369. } else {
  370. setErrorMessage(result.message);
  371. setViewState('error');
  372. }
  373. } catch (err) {
  374. setErrorMessage(err instanceof Error ? err.message : t('bugReport.unexpectedError'));
  375. setViewState('error');
  376. }
  377. };
  378. return (
  379. <>
  380. {/* Floating bubble. Absent below the sidebar-compact breakpoint, where
  381. the compact header carries the trigger instead — see Layout. */}
  382. {showTrigger && (
  383. <button
  384. onClick={handleOpen}
  385. 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 ${
  386. // Amber while a run is going, matching the debug-logging banner, so
  387. // a closed panel still says the recording is live and clickable.
  388. isLogging ? 'bg-amber-500 hover:bg-amber-600' : 'bg-red-500 hover:bg-red-600'
  389. }`}
  390. title={isLogging ? t('bugReport.resumeRecording', { elapsed: formatElapsed(elapsedSeconds) }) : t('bugReport.title')}
  391. >
  392. {isLogging && (
  393. <span className="absolute inset-0 rounded-full bg-amber-400 opacity-75 animate-ping" />
  394. )}
  395. <Bug className="w-5 h-5 relative" />
  396. </button>
  397. )}
  398. {/* Slide-in panel anchored to bottom-right; a bottom sheet on phones.
  399. The desktop geometry cannot be reused there: `w-full` resolves against
  400. the viewport for a fixed element, so on a 375px screen the panel was
  401. 375px wide and then pushed 16px in from the right, putting its left
  402. edge at -16px and cutting a strip of the form off-screen. `max-w-md`
  403. hid this on anything above ~464px wide. */}
  404. {isOpen && (
  405. <div
  406. id="bug-report-modal"
  407. className={
  408. isMobile
  409. ? 'fixed inset-x-0 bottom-0 z-50'
  410. : showTrigger
  411. ? 'fixed bottom-20 right-4 z-50 w-full max-w-md'
  412. // Trigger is in the compact header, so anchor under it rather
  413. // than to a corner the user did not touch. Only reachable
  414. // between the mobile and sidebar-compact breakpoints — below
  415. // that it is a bottom sheet, above it the disc is back.
  416. : 'fixed top-16 right-4 z-50 w-full max-w-md'
  417. }
  418. onPaste={handlePaste}
  419. >
  420. <div
  421. ref={modalRef}
  422. className={`bg-white dark:bg-gray-800 shadow-2xl border border-gray-200 dark:border-gray-700 overflow-y-auto ${
  423. isMobile
  424. ? 'rounded-t-2xl max-h-[85vh] pb-[env(safe-area-inset-bottom)]'
  425. : 'rounded-lg max-h-[80vh]'
  426. }`}
  427. >
  428. {/* Header */}
  429. <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">
  430. <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
  431. <Bug className="w-5 h-5 text-red-500" />
  432. {t('bugReport.title')}
  433. </h2>
  434. <button
  435. onClick={handleClose}
  436. className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
  437. >
  438. <X className="w-5 h-5" />
  439. </button>
  440. </div>
  441. <div className="p-4 space-y-4">
  442. {viewState === 'form' && (
  443. <>
  444. {/* Connection diagnostic — scanned on form-open. A healthy
  445. fleet shows a single confirmation line. When printers
  446. have problems, each is a collapsed row (auto-expanded
  447. when only one) so the form stays reachable regardless
  448. of how many printers are configured. */}
  449. {diagnosticScan.isLoading && (
  450. <div className="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
  451. <Loader2 className="w-3.5 h-3.5 animate-spin" />
  452. {t('bugReport.diagnosticChecking')}
  453. </div>
  454. )}
  455. {!diagnosticScan.isLoading && diagnosticProblems.length > 0 && (
  456. <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">
  457. <div className="flex items-start gap-2">
  458. <Stethoscope className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  459. <div>
  460. <p className="text-sm font-medium text-amber-700 dark:text-amber-300">
  461. {t('bugReport.diagnosticSummary', {
  462. problems: diagnosticProblems.length,
  463. total: diagnosticEntries.length,
  464. })}
  465. </p>
  466. <p className="text-xs text-amber-800 dark:text-amber-200 mt-0.5">
  467. {t('bugReport.diagnosticIntro')}
  468. </p>
  469. </div>
  470. </div>
  471. <div className="space-y-2">
  472. {diagnosticProblems.map((entry) => (
  473. <Collapsible
  474. key={entry.result.printer_id ?? entry.result.ip_address}
  475. defaultOpen={diagnosticProblems.length === 1}
  476. className="rounded-lg bg-amber-100/60 dark:bg-amber-900/30 px-3 py-2"
  477. summary={
  478. <div className="flex items-center gap-2 min-w-0">
  479. <AlertTriangle className="w-4 h-4 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  480. <span className="text-sm font-medium text-amber-800 dark:text-amber-200 truncate">
  481. {entry.name}
  482. </span>
  483. </div>
  484. }
  485. >
  486. <DiagnosticChecklist result={entry.result} />
  487. </Collapsible>
  488. ))}
  489. </div>
  490. </div>
  491. )}
  492. {!diagnosticScan.isLoading &&
  493. diagnosticEntries.length > 0 &&
  494. diagnosticProblems.length === 0 && (
  495. <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">
  496. <CheckCircle className="w-4 h-4 mt-0.5 flex-shrink-0 text-green-600 dark:text-green-400" />
  497. <p className="text-xs text-green-800 dark:text-green-200">
  498. {t('bugReport.diagnosticHealthy')}
  499. </p>
  500. </div>
  501. )}
  502. {/* Log-health scan — known issues found in recent logs.
  503. Shown only when something matched. */}
  504. {!logHealthScan.isLoading && logFindings.length > 0 && logHealthScan.data && (
  505. <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">
  506. <div className="flex items-start gap-2">
  507. <Stethoscope className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  508. <div>
  509. <p className="text-sm font-medium text-amber-700 dark:text-amber-300">
  510. {t('bugReport.logHealthSummary')}
  511. </p>
  512. <p className="text-xs text-amber-800 dark:text-amber-200 mt-0.5">
  513. {t('bugReport.logHealthIntro')}
  514. </p>
  515. </div>
  516. </div>
  517. <SystemHealthPanel result={logHealthScan.data} />
  518. </div>
  519. )}
  520. {/* Description */}
  521. <div>
  522. <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
  523. {t('bugReport.description')} *
  524. </label>
  525. <textarea
  526. value={description}
  527. onChange={(e) => setDescription(e.target.value)}
  528. placeholder={t('bugReport.descriptionPlaceholder')}
  529. rows={3}
  530. 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"
  531. />
  532. </div>
  533. {/* Email (optional) */}
  534. <div>
  535. <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
  536. {t('bugReport.email')}
  537. </label>
  538. <input
  539. type="email"
  540. value={email}
  541. onChange={(e) => setEmail(e.target.value)}
  542. placeholder={t('bugReport.emailPlaceholder')}
  543. 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"
  544. />
  545. <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
  546. {t('bugReport.emailPrivacy')}
  547. </p>
  548. </div>
  549. {/* Screenshot — upload, paste, or drag */}
  550. <div>
  551. <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
  552. {t('bugReport.screenshot')}
  553. </label>
  554. {screenshot ? (
  555. <div className="relative">
  556. <img
  557. src={`data:image/jpeg;base64,${screenshot}`}
  558. alt={t('bugReport.screenshot')}
  559. className="w-full max-h-40 object-contain rounded-lg border border-gray-200 dark:border-gray-600"
  560. />
  561. <button
  562. onClick={() => setScreenshot(null)}
  563. className="absolute top-2 right-2 p-1 bg-red-500 hover:bg-red-600 text-white rounded-full shadow"
  564. title={t('common.delete')}
  565. >
  566. <Trash2 className="w-3 h-3" />
  567. </button>
  568. </div>
  569. ) : (
  570. <button
  571. type="button"
  572. onClick={() => fileInputRef.current?.click()}
  573. onDragOver={handleDragOver}
  574. onDragLeave={handleDragLeave}
  575. onDrop={handleDrop}
  576. className={`w-full flex flex-col items-center gap-2 px-4 py-4 border-2 border-dashed rounded-lg transition-colors cursor-pointer ${
  577. isDragging
  578. ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-500'
  579. : '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'
  580. }`}
  581. >
  582. <Upload className="w-5 h-5" />
  583. <span className="text-sm">{t('bugReport.uploadOrPaste')}</span>
  584. </button>
  585. )}
  586. <input
  587. ref={fileInputRef}
  588. type="file"
  589. accept="image/*"
  590. className="hidden"
  591. onChange={(e) => {
  592. const file = e.target.files?.[0];
  593. if (file) handleFile(file);
  594. e.target.value = '';
  595. }}
  596. />
  597. </div>
  598. {/* Data collection notice */}
  599. <details className="text-xs bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3">
  600. <summary className="cursor-pointer font-medium text-amber-700 dark:text-amber-300 hover:text-amber-800 dark:hover:text-amber-200">
  601. {t('bugReport.dataCollectedSummary')}
  602. </summary>
  603. <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">
  604. <p className="font-medium">{t('bugReport.dataIncluded')}</p>
  605. <p>{t('bugReport.dataIncludedList')}</p>
  606. <p className="font-medium">{t('bugReport.dataNeverIncluded')}</p>
  607. <p>{t('bugReport.dataNeverIncludedList')}</p>
  608. </div>
  609. </details>
  610. {/* Buttons */}
  611. <div className="flex justify-end gap-2 pt-2">
  612. <button
  613. onClick={handleClose}
  614. 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"
  615. >
  616. {t('common.cancel')}
  617. </button>
  618. <button
  619. onClick={handleStartLogging}
  620. disabled={!description.trim()}
  621. 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"
  622. >
  623. {t('bugReport.startLogging')}
  624. </button>
  625. </div>
  626. </>
  627. )}
  628. {viewState === 'logging' && (
  629. <div className="py-6 space-y-6">
  630. {/* 3-step progress indicator */}
  631. <div className="space-y-3 px-2">
  632. {/* Step 1: Completed */}
  633. <div className="flex items-center gap-3">
  634. <CheckCircle2 className="w-5 h-5 text-green-500 flex-shrink-0" />
  635. <span className="text-sm text-green-700 dark:text-green-400">{t('bugReport.stepEnableLogging')}</span>
  636. </div>
  637. {/* Step 2: Active */}
  638. <div className="flex items-center gap-3">
  639. <span className="relative flex h-5 w-5 flex-shrink-0 items-center justify-center">
  640. <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"></span>
  641. <span className="relative inline-flex rounded-full h-3 w-3 bg-blue-500"></span>
  642. </span>
  643. <span data-testid="bug-report-step-reproduce" className="text-sm font-medium text-blue-700 dark:text-blue-300">{t('bugReport.stepReproduce')}</span>
  644. </div>
  645. {/* Step 3: Upcoming */}
  646. <div className="flex items-center gap-3">
  647. <Circle className="w-5 h-5 text-gray-300 dark:text-gray-600 flex-shrink-0" />
  648. <span className="text-sm text-gray-400 dark:text-gray-500">{t('bugReport.stepStopLogging')}</span>
  649. </div>
  650. </div>
  651. {/* Elapsed timer */}
  652. <div className="text-center">
  653. <p className="text-3xl font-mono text-blue-500">{formatElapsed(elapsedSeconds)}</p>
  654. <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">{t('bugReport.maxDuration', { minutes: 5 })}</p>
  655. {/* The panel covers whatever has to be clicked to reproduce
  656. the problem, so say plainly that closing it is fine. */}
  657. <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">{t('bugReport.closeKeepsRecording')}</p>
  658. </div>
  659. {/* Stop & Submit button */}
  660. <div className="flex justify-center">
  661. <button
  662. onClick={handleStopLogging}
  663. className="px-6 py-2.5 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors"
  664. >
  665. {t('bugReport.stopAndSubmit')}
  666. </button>
  667. </div>
  668. </div>
  669. )}
  670. {(viewState === 'stopping' || viewState === 'submitting') && (
  671. <div className="flex flex-col items-center justify-center py-6 gap-3">
  672. <Loader2 className="w-8 h-8 animate-spin text-blue-500" />
  673. <p className="text-sm text-gray-600 dark:text-gray-400 text-center">
  674. {viewState === 'stopping' ? t('bugReport.stoppingLogs') : t('bugReport.submitting')}
  675. </p>
  676. {viewState === 'submitting' && (
  677. // Diagnostics are run server-side inside the submit call
  678. // (#1506 follow-up): the bubble already displays current
  679. // results inline, but the submitted report now also
  680. // includes a snapshot. Wait is bounded but noticeable —
  681. // list what's running so the user knows why.
  682. <ul className="text-xs text-gray-500 dark:text-gray-400 list-disc list-inside space-y-0.5">
  683. <li>{t('bugReport.submittingStepConnection')}</li>
  684. <li>{t('bugReport.submittingStepVirtualPrinters')}</li>
  685. <li>{t('bugReport.submittingStepLogScan')}</li>
  686. <li>{t('bugReport.submittingStepSubmit')}</li>
  687. </ul>
  688. )}
  689. </div>
  690. )}
  691. {viewState === 'success' && (
  692. <div className="flex flex-col items-center justify-center py-8 gap-3">
  693. <CheckCircle className="w-12 h-12 text-green-500" />
  694. <p className="text-lg font-semibold text-gray-900 dark:text-white">{t('bugReport.thankYou')}</p>
  695. <p className="text-sm text-gray-600 dark:text-gray-400">{t('bugReport.submitted')}</p>
  696. {issueUrl && (
  697. <a
  698. href={issueUrl}
  699. target="_blank"
  700. rel="noopener noreferrer"
  701. className="text-sm text-blue-500 hover:text-blue-600 underline"
  702. >
  703. {t('bugReport.viewIssue')} #{issueNumber}
  704. </a>
  705. )}
  706. <button
  707. onClick={handleClose}
  708. 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"
  709. >
  710. {t('common.close')}
  711. </button>
  712. </div>
  713. )}
  714. {viewState === 'error' && (
  715. <div className="flex flex-col items-center justify-center py-8 gap-3">
  716. <AlertCircle className="w-12 h-12 text-red-500" />
  717. <p className="text-lg font-semibold text-gray-900 dark:text-white">{t('bugReport.submitFailed')}</p>
  718. <p className="text-sm text-gray-600 dark:text-gray-400 text-center">{errorMessage}</p>
  719. <div className="flex gap-2 mt-4">
  720. <button
  721. onClick={() => setViewState('form')}
  722. className="px-4 py-2 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors"
  723. >
  724. {t('bugReport.submit')}
  725. </button>
  726. <button
  727. onClick={handleClose}
  728. 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"
  729. >
  730. {t('common.close')}
  731. </button>
  732. </div>
  733. </div>
  734. )}
  735. </div>
  736. </div>
  737. </div>
  738. )}
  739. </>
  740. );
  741. }