ConnectionDiagnostic.tsx 8.5 KB

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