ConnectionDiagnostic.tsx 7.9 KB

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