OctoEverywhereSettings.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. import { useState, useEffect, useMemo } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { Link } from 'react-router-dom';
  4. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  5. import { Loader2, ScanEye, Check, X, Info, AlertTriangle } from 'lucide-react';
  6. import { api, type OctoEverywhereConfidence } from '../api/client';
  7. import { Card, CardContent, CardHeader } from './Card';
  8. import { Button } from './Button';
  9. import { Toggle } from './Toggle';
  10. import { OctoEverywhereLimitNotice } from './OctoEverywhereLimitNotice';
  11. import { useToast } from '../contexts/ToastContext';
  12. import { useAuth } from '../contexts/AuthContext';
  13. import { aiDetectionClass, hasVerdict, OCTOEVERYWHERE_USAGE_LIMIT, type AiDetectionClass } from '../utils/aiDetection';
  14. type TestResult = { ok: boolean; message: string; errorCode?: string | null } | null;
  15. function detectionColor(cls: AiDetectionClass) {
  16. return cls === 'failure'
  17. ? 'text-red-700 dark:text-red-400'
  18. : cls === 'warning' || cls === 'error'
  19. ? 'text-amber-700 dark:text-amber-400'
  20. : cls === 'safe'
  21. ? 'text-green-700 dark:text-green-400'
  22. : 'text-bambu-gray';
  23. }
  24. export function OctoEverywhereSettings() {
  25. const { t } = useTranslation();
  26. const queryClient = useQueryClient();
  27. const { showToast } = useToast();
  28. const { hasPermission, loading: authLoading } = useAuth();
  29. const canUpdate = !authLoading && hasPermission('settings:update');
  30. const [enabled, setEnabled] = useState(false);
  31. const [apiKey, setApiKey] = useState('');
  32. // The server never returns a saved key, so the field keeps showing the key
  33. // this page saved (until the page is left) instead of clearing after a save.
  34. const [savedApiKey, setSavedApiKey] = useState('');
  35. const [editingApiKey, setEditingApiKey] = useState(false);
  36. const [confidence, setConfidence] = useState<OctoEverywhereConfidence>('medium');
  37. const [action, setAction] = useState<'notify' | 'pause' | 'pause_and_off'>('notify');
  38. const [pollInterval, setPollInterval] = useState(20);
  39. const [enabledPrinters, setEnabledPrinters] = useState<number[] | null>(null); // null = all
  40. const [testResult, setTestResult] = useState<TestResult>(null);
  41. const [testing, setTesting] = useState(false);
  42. const [initialized, setInitialized] = useState(false);
  43. const { data: settings } = useQuery({
  44. queryKey: ['settings'],
  45. queryFn: api.getSettings,
  46. });
  47. const { data: status, refetch: refetchStatus } = useQuery({
  48. queryKey: ['octoeverywhere-status'],
  49. queryFn: api.getOctoEverywhereStatus,
  50. refetchInterval: 10000,
  51. });
  52. const { data: printers } = useQuery({
  53. queryKey: ['printers'],
  54. queryFn: api.getPrinters,
  55. });
  56. useEffect(() => {
  57. if (!settings) return;
  58. setEnabled(settings.octoeverywhere_enabled ?? false);
  59. setConfidence(settings.octoeverywhere_confidence ?? 'medium');
  60. setAction(settings.octoeverywhere_action ?? 'notify');
  61. setPollInterval(settings.octoeverywhere_poll_interval ?? 20);
  62. try {
  63. const list = settings.octoeverywhere_enabled_printers
  64. ? (JSON.parse(settings.octoeverywhere_enabled_printers) as number[])
  65. : null;
  66. setEnabledPrinters(Array.isArray(list) ? list : null);
  67. } catch {
  68. setEnabledPrinters(null);
  69. }
  70. setInitialized(true);
  71. }, [settings]);
  72. const saveMutation = useMutation({
  73. mutationFn: api.updateSettings,
  74. onSuccess: (saved, update) => {
  75. if (update.octoeverywhere_api_key !== undefined) setSavedApiKey(update.octoeverywhere_api_key);
  76. queryClient.setQueryData(['settings'], saved);
  77. queryClient.invalidateQueries({ queryKey: ['settings'] });
  78. queryClient.invalidateQueries({ queryKey: ['octoeverywhere-status'] });
  79. queryClient.invalidateQueries({ queryKey: ['octoeverywhere-printer-status'] });
  80. queryClient.invalidateQueries({ queryKey: ['obico-status'] });
  81. queryClient.invalidateQueries({ queryKey: ['obico-printer-status'] });
  82. showToast(t('settings.toast.settingsSaved'));
  83. },
  84. onError: (error: Error) => showToast(error.message, 'error'),
  85. });
  86. // An empty field keeps the saved key, and a key already saved from this
  87. // field is not resent with every other change.
  88. const pendingApiKey = apiKey.trim() === savedApiKey ? '' : apiKey.trim();
  89. const settingsToSave = useMemo(() => ({
  90. octoeverywhere_enabled: enabled,
  91. ...(pendingApiKey ? { octoeverywhere_api_key: pendingApiKey } : {}),
  92. octoeverywhere_confidence: confidence,
  93. octoeverywhere_action: action,
  94. octoeverywhere_poll_interval: pollInterval,
  95. octoeverywhere_enabled_printers: enabledPrinters === null ? '' : JSON.stringify(enabledPrinters),
  96. }), [enabled, pendingApiKey, confidence, action, pollInterval, enabledPrinters]);
  97. const hasUnsavedChanges = useMemo(() => {
  98. if (!initialized || !settings) return false;
  99. return (
  100. (settings.octoeverywhere_enabled ?? false) !== enabled ||
  101. pendingApiKey.length > 0 ||
  102. (settings.octoeverywhere_confidence ?? 'medium') !== confidence ||
  103. (settings.octoeverywhere_action ?? 'notify') !== action ||
  104. (settings.octoeverywhere_poll_interval ?? 20) !== pollInterval ||
  105. (settings.octoeverywhere_enabled_printers ?? '') !== (enabledPrinters === null ? '' : JSON.stringify(enabledPrinters))
  106. );
  107. }, [settings, initialized, enabled, pendingApiKey, confidence, action, pollInterval, enabledPrinters]);
  108. // A failed payload waits for another edit or an explicit Test. Compare the
  109. // values so an equivalent payload recreated after a refetch cannot retry it.
  110. const currentSaveFailed = saveMutation.isError
  111. && JSON.stringify(saveMutation.variables) === JSON.stringify(settingsToSave);
  112. // Auto-save on change (debounced), matching the other detection provider.
  113. useEffect(() => {
  114. if (!hasUnsavedChanges || currentSaveFailed || testing || editingApiKey || saveMutation.isPending || !canUpdate) return;
  115. const id = setTimeout(() => saveMutation.mutate(settingsToSave), 500);
  116. return () => clearTimeout(id);
  117. // eslint-disable-next-line react-hooks/exhaustive-deps
  118. }, [hasUnsavedChanges, currentSaveFailed, settingsToSave, testing, editingApiKey, saveMutation.isPending, canUpdate]);
  119. const handleTest = async () => {
  120. if (!canUpdate) return;
  121. setTestResult(null);
  122. setTesting(true);
  123. try {
  124. // A successful test must describe the configuration used by the service,
  125. // including edits still inside the auto-save debounce.
  126. if (hasUnsavedChanges) {
  127. await saveMutation.mutateAsync(settingsToSave);
  128. }
  129. const res = await api.testOctoEverywhereConnection(undefined, confidence);
  130. setTestResult({
  131. ok: res.ok,
  132. message: res.ok ? t('octoeverywhere.testSuccess') : res.error || t('failureDetection.testFailed'),
  133. errorCode: res.error_code,
  134. });
  135. } catch (e: unknown) {
  136. setTestResult({ ok: false, message: e instanceof Error ? e.message : String(e) });
  137. } finally {
  138. setTesting(false);
  139. }
  140. };
  141. const togglePrinter = (printerId: number, checked: boolean) => {
  142. const selected = enabledPrinters ?? printers?.map((p) => p.id) ?? [];
  143. setEnabledPrinters(checked ? [...selected, printerId] : selected.filter((id) => id !== printerId));
  144. };
  145. const keyConfigured = settings?.octoeverywhere_api_key_configured ?? false;
  146. const busy = testing || saveMutation.isPending;
  147. const monitoringState = !status?.enabled
  148. ? 'monitoringDisabled'
  149. : !status.api_key_configured
  150. ? 'monitoringMissingKey'
  151. : !status.is_running
  152. ? 'monitoringStopped'
  153. : status.last_error || status.last_error_code || Object.values(status.per_printer).some((info) => info.class === 'error')
  154. ? 'monitoringError'
  155. : Object.values(status.per_printer).some((info) => hasVerdict(aiDetectionClass(info)))
  156. ? 'monitoringObserved'
  157. : 'monitoringWaiting';
  158. const notifications = status?.notifications;
  159. const uncoveredPrinters = notifications?.uncovered_printers.map((id) => printers?.find((p) => p.id === id)?.name ?? `#${id}`);
  160. return (
  161. <div className="flex flex-col lg:flex-row gap-4 lg:gap-6">
  162. <div className="space-y-3 flex-1 lg:max-w-xl">
  163. <Card id="card-fd-ml">
  164. <CardHeader>
  165. <div className="flex items-center justify-between">
  166. <div className="flex items-center gap-2">
  167. <ScanEye className="w-5 h-5 text-bambu-green" />
  168. <h2 className="text-lg font-semibold text-white">{t('octoeverywhere.title')}</h2>
  169. </div>
  170. <Toggle checked={enabled} onChange={setEnabled} disabled={!initialized || busy || !canUpdate} />
  171. </div>
  172. <p className="text-sm text-bambu-gray mt-2">
  173. {t('octoeverywhere.description')}{' '}
  174. <a
  175. href="https://docs.octoeverywhere.com/ai-failure-detection-apis/overview/"
  176. target="_blank"
  177. rel="noopener noreferrer"
  178. className="text-bambu-green hover:underline"
  179. >
  180. {t('octoeverywhere.learnMore')}
  181. </a>
  182. </p>
  183. </CardHeader>
  184. <CardContent className="space-y-4">
  185. <div>
  186. <label htmlFor="oe-api-key" className="block text-sm text-bambu-gray mb-1">
  187. {t('octoeverywhere.apiKey')}
  188. </label>
  189. <div className="flex gap-2">
  190. <input
  191. id="oe-api-key"
  192. type="password"
  193. value={apiKey}
  194. onChange={(e) => { setApiKey(e.target.value); setTestResult(null); }}
  195. onFocus={() => setEditingApiKey(true)}
  196. onBlur={() => setEditingApiKey(false)}
  197. autoComplete="off"
  198. placeholder={t(keyConfigured ? 'octoeverywhere.apiKeyConfigured' : 'octoeverywhere.apiKeyPlaceholder')}
  199. className="flex-1 min-w-0 bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white text-sm"
  200. disabled={!initialized || busy || !canUpdate}
  201. />
  202. <Button
  203. onClick={handleTest}
  204. disabled={(!apiKey.trim() && !keyConfigured) || busy || !canUpdate}
  205. variant="secondary"
  206. >
  207. {testing && <Loader2 className="w-4 h-4 animate-spin" />}
  208. {t('failureDetection.test')}
  209. </Button>
  210. </div>
  211. <p className="text-xs text-bambu-gray mt-1">
  212. {t('octoeverywhere.apiKeyHint')}{' '}
  213. <a
  214. href="https://octoeverywhere.com/privacy#gadget-developer-api"
  215. target="_blank"
  216. rel="noopener noreferrer"
  217. className="text-bambu-green hover:underline"
  218. >
  219. {t('octoeverywhere.privacyPolicy')}
  220. </a>
  221. </p>
  222. <a
  223. href="https://octoeverywhere.com/gadgetapi"
  224. target="_blank"
  225. rel="noopener noreferrer"
  226. className="inline-block text-xs text-bambu-green hover:underline mt-1"
  227. >
  228. {t('octoeverywhere.getApiKey')}
  229. </a>
  230. {testResult?.errorCode === OCTOEVERYWHERE_USAGE_LIMIT ? (
  231. <div className="mt-2"><OctoEverywhereLimitNotice /></div>
  232. ) : testResult && (
  233. <div
  234. className={`flex items-start gap-2 mt-2 text-sm ${
  235. testResult.ok ? 'text-green-700 dark:text-green-400' : 'text-red-700 dark:text-red-400'
  236. }`}
  237. >
  238. {testResult.ok ? <Check className="w-4 h-4 mt-0.5" /> : <X className="w-4 h-4 mt-0.5" />}
  239. <span>{testResult.message}</span>
  240. </div>
  241. )}
  242. </div>
  243. <div>
  244. <label htmlFor="oe-confidence" className="block text-sm text-bambu-gray mb-1">
  245. {t('octoeverywhere.confidence')}
  246. </label>
  247. <select
  248. id="oe-confidence"
  249. value={confidence}
  250. onChange={(e) => { setConfidence(e.target.value as OctoEverywhereConfidence); setTestResult(null); }}
  251. disabled={!enabled || busy || !canUpdate}
  252. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white text-sm"
  253. >
  254. <option value="lowest">{t('octoeverywhere.confidenceLowest')}</option>
  255. <option value="low">{t('octoeverywhere.confidenceLow')}</option>
  256. <option value="medium">{t('octoeverywhere.confidenceMedium')}</option>
  257. <option value="high">{t('octoeverywhere.confidenceHigh')}</option>
  258. <option value="highest">{t('octoeverywhere.confidenceHighest')}</option>
  259. </select>
  260. <p className="text-xs text-bambu-gray mt-1">{t('octoeverywhere.confidenceHint')}</p>
  261. </div>
  262. <div>
  263. <label htmlFor="oe-action" className="block text-sm text-bambu-gray mb-1">
  264. {t('failureDetection.action')}
  265. </label>
  266. <select
  267. id="oe-action"
  268. value={action}
  269. onChange={(e) => setAction(e.target.value as 'notify' | 'pause' | 'pause_and_off')}
  270. disabled={!enabled || busy || !canUpdate}
  271. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white text-sm"
  272. >
  273. <option value="notify">{t('failureDetection.actionNotify')}</option>
  274. <option value="pause">{t('failureDetection.actionPause')}</option>
  275. <option value="pause_and_off">{t('failureDetection.actionPauseOff')}</option>
  276. </select>
  277. </div>
  278. <div>
  279. <div className="flex items-center justify-between gap-2 mb-2">
  280. <label htmlFor="oe-poll-interval" className="text-sm text-bambu-gray">
  281. {t('octoeverywhere.inspectionInterval')}
  282. </label>
  283. <span className="text-sm text-white tabular-nums">{pollInterval} {t('common.seconds')}</span>
  284. </div>
  285. <input
  286. id="oe-poll-interval"
  287. type="range"
  288. value={pollInterval}
  289. onChange={(e) => setPollInterval(Math.max(5, Math.min(30, Math.round(Number(e.target.value) || 20))))}
  290. min={5}
  291. max={30}
  292. step={1}
  293. aria-valuetext={`${pollInterval} ${t('common.seconds')}`}
  294. aria-describedby="oe-interval-hint"
  295. disabled={!enabled || busy || !canUpdate}
  296. className="w-full h-1 accent-bambu-green cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
  297. />
  298. <p id="oe-interval-hint" className="text-xs text-bambu-gray mt-2">
  299. {t('octoeverywhere.inspectionIntervalHint')}
  300. </p>
  301. </div>
  302. {notifications && (!notifications.configured || notifications.uncovered_printers.length > 0) && (
  303. <div className="flex items-start gap-2 p-3 bg-amber-50 dark:bg-amber-900/30 border border-amber-300 dark:border-amber-700 rounded text-sm text-amber-800 dark:text-amber-200">
  304. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0" />
  305. <div>
  306. <p>{notifications.configured
  307. ? t('octoeverywhere.notificationsUncovered', { printers: uncoveredPrinters?.join(', ') })
  308. : t('octoeverywhere.notificationsMissing')}</p>
  309. {hasPermission('notifications:read') && (
  310. <Link to="/settings?tab=notifications" className="inline-block mt-1 underline hover:no-underline">
  311. {t('octoeverywhere.configureNotifications')}
  312. </Link>
  313. )}
  314. </div>
  315. </div>
  316. )}
  317. </CardContent>
  318. </Card>
  319. <Card id="card-fd-perprinter">
  320. <CardHeader>
  321. <h2 className="text-lg font-semibold text-white">{t('failureDetection.perPrinterTitle')}</h2>
  322. <p className="text-sm text-bambu-gray mt-1">{t('failureDetection.perPrinterHint')}</p>
  323. </CardHeader>
  324. <CardContent className="space-y-2">
  325. <label className="flex items-center gap-2 text-sm">
  326. <input
  327. type="checkbox"
  328. checked={enabledPrinters === null}
  329. onChange={(e) => setEnabledPrinters(e.target.checked ? null : printers?.map((p) => p.id) ?? [])}
  330. disabled={!enabled || busy || !canUpdate}
  331. />
  332. <span className="text-white">{t('failureDetection.monitorAll')}</span>
  333. </label>
  334. {enabledPrinters !== null && printers && (
  335. <div className="pl-5 space-y-1 border-l border-gray-700">
  336. {printers.map((p) => (
  337. <label key={p.id} className="flex items-center gap-2 text-sm">
  338. <input
  339. type="checkbox"
  340. checked={enabledPrinters.includes(p.id)}
  341. onChange={(e) => togglePrinter(p.id, e.target.checked)}
  342. disabled={!enabled || busy || !canUpdate}
  343. />
  344. <span className="text-white">{p.name}</span>
  345. </label>
  346. ))}
  347. </div>
  348. )}
  349. </CardContent>
  350. </Card>
  351. </div>
  352. <div className="space-y-3 flex-1 lg:max-w-xl">
  353. <Card id="card-fd-status">
  354. <CardHeader>
  355. <h2 className="text-lg font-semibold text-white">{t('failureDetection.statusTitle')}</h2>
  356. </CardHeader>
  357. <CardContent>
  358. {!status ? (
  359. <div className="flex items-center gap-2 text-bambu-gray">
  360. <Loader2 className="w-4 h-4 animate-spin" />
  361. <span>{t('common.loading')}</span>
  362. </div>
  363. ) : (
  364. <div className="space-y-3 text-sm">
  365. <div className="flex justify-between">
  366. <span className="text-bambu-gray">{t('octoeverywhere.monitoringStatus')}</span>
  367. <span className={monitoringState === 'monitoringObserved' ? 'text-green-700 dark:text-green-400' : 'text-bambu-gray'}>
  368. {t(`octoeverywhere.${monitoringState}`)}
  369. </span>
  370. </div>
  371. {status.last_error_code === OCTOEVERYWHERE_USAGE_LIMIT ? (
  372. <OctoEverywhereLimitNotice />
  373. ) : status.last_error && (
  374. <div className="flex items-start gap-2 text-red-700 dark:text-red-400">
  375. <X className="w-4 h-4 mt-0.5 flex-shrink-0" />
  376. <span className="break-words">{status.last_error}</span>
  377. </div>
  378. )}
  379. <div>
  380. <div className="text-bambu-gray mb-1">{t('failureDetection.activePrinters')}</div>
  381. {Object.keys(status.per_printer).length === 0 ? (
  382. <div className="text-bambu-gray italic text-xs">{t('failureDetection.noActivePrints')}</div>
  383. ) : (
  384. <div className="space-y-2">
  385. {Object.entries(status.per_printer).map(([pid, info]) => {
  386. const printer = printers?.find((p) => String(p.id) === pid);
  387. const cls = aiDetectionClass(info);
  388. return (
  389. <div key={pid}>
  390. <div className="flex justify-between gap-2">
  391. <span className="text-white">{printer?.name ?? `#${pid}`}</span>
  392. <span className={detectionColor(cls)}>{t(`printers.aiDetection.${cls}`)}</span>
  393. </div>
  394. {hasVerdict(cls) && info.print_quality !== null && (
  395. <div className="text-xs text-bambu-gray">
  396. {t('octoeverywhere.printQuality')}: {info.print_quality}/10
  397. </div>
  398. )}
  399. {info.error_code === OCTOEVERYWHERE_USAGE_LIMIT ? (
  400. <OctoEverywhereLimitNotice />
  401. ) : info.error && <p className="text-xs text-amber-700 dark:text-amber-400 break-words">{info.error}</p>}
  402. </div>
  403. );
  404. })}
  405. </div>
  406. )}
  407. </div>
  408. </div>
  409. )}
  410. </CardContent>
  411. </Card>
  412. <Card id="card-fd-history">
  413. <CardHeader>
  414. <div className="flex items-center justify-between">
  415. <h2 className="text-lg font-semibold text-white">{t('failureDetection.historyTitle')}</h2>
  416. <button onClick={() => refetchStatus()} className="text-xs text-bambu-gray hover:text-white">
  417. {t('common.refresh')}
  418. </button>
  419. </div>
  420. </CardHeader>
  421. <CardContent>
  422. {!status || status.history.length === 0 ? (
  423. <div className="flex items-center gap-2 text-bambu-gray text-sm">
  424. <Info className="w-4 h-4" />
  425. <span>{t('failureDetection.noHistory')}</span>
  426. </div>
  427. ) : (
  428. <div className="space-y-1 max-h-96 overflow-y-auto text-xs font-mono">
  429. {status.history.map((ev, idx) => {
  430. const printer = printers?.find((p) => p.id === ev.printer_id);
  431. const cls = ev.class;
  432. return (
  433. <div key={idx} className="flex justify-between gap-2 py-1 border-b border-gray-800">
  434. <span className="text-bambu-gray">{new Date(ev.timestamp).toLocaleTimeString()}</span>
  435. <span className="text-white truncate">{printer?.name ?? `#${ev.printer_id}`}</span>
  436. <span className={detectionColor(cls)}>
  437. {t(`printers.aiDetection.${cls}`)}
  438. {hasVerdict(cls) && ev.print_quality !== null && ` ${ev.print_quality}/10`}
  439. </span>
  440. </div>
  441. );
  442. })}
  443. </div>
  444. )}
  445. </CardContent>
  446. </Card>
  447. </div>
  448. </div>
  449. );
  450. }