ConnectionDiagnostic.tsx 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import { useEffect, useState } from 'react';
  2. import { useMutation } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import {
  5. X,
  6. Stethoscope,
  7. CheckCircle2,
  8. XCircle,
  9. AlertTriangle,
  10. MinusCircle,
  11. Loader2,
  12. } from 'lucide-react';
  13. import {
  14. api,
  15. type DiagnosticCheck,
  16. type DiagnosticStatus,
  17. type PrinterDiagnosticResult,
  18. } from '../api/client';
  19. function StatusIcon({ status }: { status: DiagnosticStatus }) {
  20. if (status === 'pass') return <CheckCircle2 className="w-5 h-5 text-bambu-green flex-shrink-0" />;
  21. if (status === 'fail') return <XCircle className="w-5 h-5 text-red-400 flex-shrink-0" />;
  22. if (status === 'warn') return <AlertTriangle className="w-5 h-5 text-amber-400 flex-shrink-0" />;
  23. return <MinusCircle className="w-5 h-5 text-bambu-gray flex-shrink-0" />;
  24. }
  25. /**
  26. * Presentational checklist — renders one row per diagnostic check plus an
  27. * overall banner. Shared by the modal and the bug-report panel. The title
  28. * and per-status detail text are localized via `diagnostic.check.<id>.*`.
  29. */
  30. export function DiagnosticChecklist({ result }: { result: PrinterDiagnosticResult }) {
  31. const { t } = useTranslation();
  32. const overallClass =
  33. result.overall === 'ok'
  34. ? 'bg-bambu-green/10 border-bambu-green/30 text-bambu-green'
  35. : result.overall === 'warnings'
  36. ? 'bg-amber-500/10 border-amber-500/30 text-amber-300'
  37. : 'bg-red-500/10 border-red-500/30 text-red-300';
  38. const renderCheck = (check: DiagnosticCheck) => {
  39. const detail = t(`diagnostic.check.${check.id}.${check.status}`, {
  40. ...check.params,
  41. defaultValue: '',
  42. });
  43. return (
  44. <li
  45. key={check.id}
  46. className={`flex items-start gap-3 bg-bambu-dark rounded-lg px-4 py-2.5 ${
  47. check.status === 'skip' ? 'opacity-60' : ''
  48. }`}
  49. >
  50. <div className="mt-0.5">
  51. <StatusIcon status={check.status} />
  52. </div>
  53. <div className="flex-1 min-w-0">
  54. <div className="text-sm text-white">{t(`diagnostic.check.${check.id}.title`)}</div>
  55. {detail && <div className="text-xs text-bambu-gray mt-0.5">{detail}</div>}
  56. </div>
  57. </li>
  58. );
  59. };
  60. return (
  61. <div className="space-y-4">
  62. <ol className="space-y-2">{result.checks.map(renderCheck)}</ol>
  63. <div className={`rounded-lg border px-4 py-3 text-sm ${overallClass}`}>
  64. {t(`diagnostic.overall.${result.overall}`)}
  65. </div>
  66. </div>
  67. );
  68. }
  69. type Connection = {
  70. ip_address: string;
  71. serial_number?: string;
  72. access_code?: string;
  73. };
  74. // Keep in sync with backend `PUBLISH_WAIT_DEFAULT` in
  75. // backend/app/services/printer_diagnostic.py — that's the upper bound on how
  76. // long the existing-printer route waits for the printer's first status report
  77. // after a bridge reconnect. The countdown is purely cosmetic; if the two
  78. // drift the worst case is the hint text being off by a couple of seconds.
  79. const PUBLISH_WAIT_DEFAULT_SECONDS = 10;
  80. type ConnectionDiagnosticModalProps = {
  81. onClose: () => void;
  82. printerName?: string | null;
  83. } & ({ printerId: number } | { connection: Connection });
  84. /**
  85. * Connection diagnostic modal. Opens straight into the test — used from the
  86. * printer card, the System page, and the Add-Printer flow on failure.
  87. */
  88. export function ConnectionDiagnosticModal(props: ConnectionDiagnosticModalProps) {
  89. const { onClose, printerName } = props;
  90. const { t } = useTranslation();
  91. const printerId = 'printerId' in props ? props.printerId : undefined;
  92. const connection = 'connection' in props ? props.connection : undefined;
  93. const diagnose = useMutation({
  94. mutationFn: (): Promise<PrinterDiagnosticResult> =>
  95. printerId !== undefined
  96. ? api.diagnosePrinter(printerId)
  97. : api.diagnoseConnection(connection as Connection),
  98. });
  99. useEffect(() => {
  100. diagnose.mutate();
  101. // Run once on mount — re-running is the explicit "Retry" button.
  102. // eslint-disable-next-line react-hooks/exhaustive-deps
  103. }, []);
  104. useEffect(() => {
  105. const handleKeyDown = (e: KeyboardEvent) => {
  106. if (e.key === 'Escape') onClose();
  107. };
  108. window.addEventListener('keydown', handleKeyDown);
  109. return () => window.removeEventListener('keydown', handleKeyDown);
  110. }, [onClose]);
  111. // Tick an elapsed-seconds counter while the diagnostic is running so the
  112. // existing-printer flow (which waits up to PUBLISH_WAIT_DEFAULT_SECONDS for
  113. // the printer's first status report) doesn't look hung. Resets on each
  114. // (re)run. No effect on the pre-add flow other than a ticking counter,
  115. // which is still useful feedback.
  116. const [elapsedSeconds, setElapsedSeconds] = useState(0);
  117. useEffect(() => {
  118. if (!diagnose.isPending) {
  119. setElapsedSeconds(0);
  120. return;
  121. }
  122. const startedAt = Date.now();
  123. const interval = window.setInterval(() => {
  124. setElapsedSeconds(Math.floor((Date.now() - startedAt) / 1000));
  125. }, 500);
  126. return () => window.clearInterval(interval);
  127. }, [diagnose.isPending]);
  128. const result = diagnose.data as PrinterDiagnosticResult | undefined;
  129. return (
  130. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4" onClick={onClose}>
  131. <div
  132. className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg flex flex-col max-h-[85vh]"
  133. onClick={(e) => e.stopPropagation()}
  134. >
  135. <div className="flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary">
  136. <div className="flex items-center gap-2 min-w-0">
  137. <Stethoscope className="w-5 h-5 text-bambu-green flex-shrink-0" />
  138. <h2 className="text-lg font-semibold text-white truncate">
  139. {t('diagnostic.modalTitle', { name: printerName || '' })}
  140. </h2>
  141. </div>
  142. <button
  143. onClick={onClose}
  144. className="text-bambu-gray hover:text-white transition-colors"
  145. title={t('common.close')}
  146. >
  147. <X className="w-5 h-5" />
  148. </button>
  149. </div>
  150. <div className="p-6 space-y-4 overflow-y-auto">
  151. {diagnose.isPending && (
  152. <div className="space-y-1.5">
  153. <div className="flex items-center gap-2 text-bambu-gray">
  154. <Loader2 className="w-4 h-4 animate-spin" />
  155. <span>
  156. {elapsedSeconds > 0
  157. ? t('diagnostic.runningElapsed', { elapsed: elapsedSeconds })
  158. : t('diagnostic.running')}
  159. </span>
  160. </div>
  161. {printerId !== undefined && (
  162. <p className="text-xs text-bambu-gray-light pl-6">
  163. {t('diagnostic.waitingForReportHint', { max: PUBLISH_WAIT_DEFAULT_SECONDS })}
  164. </p>
  165. )}
  166. </div>
  167. )}
  168. {diagnose.isError && (
  169. <div className="rounded-lg bg-red-500/10 border border-red-500/30 px-4 py-3 text-sm text-red-300">
  170. {t('diagnostic.runFailed', { error: (diagnose.error as Error).message })}
  171. </div>
  172. )}
  173. {result && <DiagnosticChecklist result={result} />}
  174. </div>
  175. <div className="px-6 py-4 border-t border-bambu-dark-tertiary flex justify-end gap-2">
  176. <button
  177. onClick={() => diagnose.mutate()}
  178. disabled={diagnose.isPending}
  179. className="px-4 py-2 bg-bambu-dark hover:bg-bambu-dark-tertiary disabled:opacity-50 text-white text-sm rounded-lg transition-colors"
  180. >
  181. {t('diagnostic.retry')}
  182. </button>
  183. <button
  184. onClick={onClose}
  185. className="px-4 py-2 bg-bambu-green hover:bg-bambu-green/90 text-white text-sm rounded-lg transition-colors"
  186. >
  187. {t('common.close')}
  188. </button>
  189. </div>
  190. </div>
  191. </div>
  192. );
  193. }