ConnectionDiagnostic.tsx 9.1 KB

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