RunWithPipelineModal.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import { useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
  4. import { AlertTriangle, Cog, Loader2, Play, Printer as PrinterIcon, X } from 'lucide-react';
  5. import {
  6. api,
  7. type PipelineEligibilityReport,
  8. type Printer as PrinterType,
  9. type SlicerPipeline,
  10. } from '../api/client';
  11. import { useToast } from '../contexts/ToastContext';
  12. import { useSliceJobTracker } from '../contexts/SliceJobTrackerContext';
  13. import { useUiSettings } from '../hooks/useUiSettings';
  14. // Same source-kind shape SliceModal uses, so the same library-file vs archive
  15. // distinction flows through eligibility-check, run dispatch, AND the progress
  16. // toast tracker.
  17. export type RunPipelineSource =
  18. | { kind: 'libraryFile'; id: number; filename: string }
  19. | { kind: 'archive'; id: number; filename: string };
  20. export interface RunWithPipelineModalProps {
  21. source: RunPipelineSource;
  22. onClose: () => void;
  23. }
  24. // Two-step modal. Step 1: pick a pipeline. Step 2: confirm eligibility
  25. // (skipped when ok=true) and run. Lives in two views in the same modal so
  26. // the user keeps context — most production runs hit the green path and
  27. // never see step 2.
  28. export function RunWithPipelineModal({ source, onClose }: RunWithPipelineModalProps) {
  29. const { t } = useTranslation();
  30. const queryClient = useQueryClient();
  31. const { showToast } = useToast();
  32. const [picked, setPicked] = useState<SlicerPipeline | null>(null);
  33. const [report, setReport] = useState<PipelineEligibilityReport | null>(null);
  34. const [copies, setCopies] = useState<number>(1);
  35. const { trackJob } = useSliceJobTracker();
  36. const { data: list, isLoading: pipelinesLoading } = useQuery({
  37. queryKey: ['slicer-pipelines'],
  38. queryFn: () => api.listSlicerPipelines(),
  39. });
  40. const { data: printers } = useQuery({
  41. queryKey: ['printers'],
  42. queryFn: () => api.getPrinters(),
  43. });
  44. // Cap from settings (PR C). Falls back to 50 when the fetch is in-flight or
  45. // missing — same default the backend writes.
  46. const { data: settings } = useUiSettings();
  47. const maxCopies = settings?.pipeline_max_copies ?? 50;
  48. const sourceRef = { kind: source.kind, id: source.id } as const;
  49. const checkMutation = useMutation({
  50. mutationFn: (pipelineId: number) =>
  51. api.checkPipelineEligibility(pipelineId, sourceRef),
  52. });
  53. const runMutation = useMutation({
  54. mutationFn: ({ pipelineId, force }: { pipelineId: number; force: boolean }) =>
  55. api.runPipeline(pipelineId, sourceRef, force, copies),
  56. onSuccess: (run) => {
  57. queryClient.invalidateQueries({ queryKey: ['slicer-pipelines'] });
  58. queryClient.invalidateQueries({ queryKey: ['pipeline-runs'] });
  59. // Hand the slice job off to the existing tracker so the same persistent
  60. // progress toast renders for pipeline runs as for manual SliceModal
  61. // slices — no separate notification surface.
  62. if (run.slice_job_id) {
  63. trackJob(run.slice_job_id, source.kind, source.filename);
  64. }
  65. showToast(t('library.runWithPipeline.toast.started', 'Pipeline run started'), 'success');
  66. onClose();
  67. },
  68. onError: (err: Error) => {
  69. showToast(err.message || t('library.runWithPipeline.toast.failed', 'Could not start run'), 'error');
  70. },
  71. });
  72. const pipelines = list?.pipelines ?? [];
  73. const printerById: Record<number, PrinterType> = (printers ?? []).reduce((acc, p) => {
  74. acc[p.id] = p;
  75. return acc;
  76. }, {} as Record<number, PrinterType>);
  77. const handlePick = async (pipeline: SlicerPipeline) => {
  78. const hasTarget =
  79. pipeline.target_printer_id ||
  80. (pipeline.target_kind === 'printer_class' && pipeline.target_model_class);
  81. if (!hasTarget) {
  82. showToast(
  83. t('library.runWithPipeline.noTargetMessage', 'This pipeline has no target printer set. Open it in Settings to pick one.'),
  84. 'error',
  85. );
  86. return;
  87. }
  88. setPicked(pipeline);
  89. try {
  90. const result = await checkMutation.mutateAsync(pipeline.id);
  91. setReport(result);
  92. if (result.ok) {
  93. runMutation.mutate({ pipelineId: pipeline.id, force: false });
  94. }
  95. } catch (err) {
  96. // Refused or unreachable: say why and keep the user on step 1.
  97. showToast(
  98. (err instanceof Error && err.message) || t('library.runWithPipeline.toast.failed', 'Could not start run'),
  99. 'error',
  100. );
  101. setPicked(null);
  102. }
  103. };
  104. const handleConfirm = () => {
  105. if (!picked) return;
  106. runMutation.mutate({ pipelineId: picked.id, force: true });
  107. };
  108. const handleBack = () => {
  109. setPicked(null);
  110. setReport(null);
  111. };
  112. return (
  113. <div
  114. className="fixed inset-0 z-50 bg-black/60 flex items-center justify-center p-4"
  115. onClick={onClose}
  116. role="dialog"
  117. aria-modal="true"
  118. aria-label={t('library.runWithPipeline.modalTitle', 'Run with pipeline')}
  119. >
  120. <div
  121. className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-2xl w-full max-w-md max-h-[80vh] flex flex-col overflow-hidden"
  122. onClick={(e) => e.stopPropagation()}
  123. >
  124. <div className="flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary">
  125. <h3 className="text-sm font-semibold text-white flex items-center gap-2">
  126. <Play className="w-4 h-4 text-bambu-green" />
  127. {picked && report
  128. ? t('library.runWithPipeline.confirmTitle', 'Confirm run')
  129. : t('library.runWithPipeline.modalTitle', 'Run with pipeline')}
  130. </h3>
  131. <button
  132. type="button"
  133. onClick={onClose}
  134. aria-label={t('common.close', 'Close')}
  135. className="text-bambu-gray hover:text-white"
  136. >
  137. <X className="w-4 h-4" />
  138. </button>
  139. </div>
  140. <div className="flex-1 overflow-y-auto p-4 space-y-3">
  141. {picked && report ? (
  142. <ConfirmStep
  143. pipeline={picked}
  144. report={report}
  145. source={source}
  146. onBack={handleBack}
  147. onConfirm={handleConfirm}
  148. running={runMutation.isPending}
  149. />
  150. ) : (
  151. <PickStep
  152. source={source}
  153. pipelines={pipelines}
  154. printerById={printerById}
  155. loading={pipelinesLoading || checkMutation.isPending}
  156. onPick={handlePick}
  157. copies={copies}
  158. maxCopies={maxCopies}
  159. onCopiesChange={setCopies}
  160. />
  161. )}
  162. </div>
  163. </div>
  164. </div>
  165. );
  166. }
  167. function PickStep({
  168. source,
  169. pipelines,
  170. printerById,
  171. loading,
  172. onPick,
  173. copies,
  174. maxCopies,
  175. onCopiesChange,
  176. }: {
  177. source: { filename: string };
  178. pipelines: SlicerPipeline[];
  179. printerById: Record<number, { name: string }>;
  180. loading: boolean;
  181. onPick: (p: SlicerPipeline) => void;
  182. copies: number;
  183. maxCopies: number;
  184. onCopiesChange: (n: number) => void;
  185. }) {
  186. const { t } = useTranslation();
  187. return (
  188. <>
  189. <p className="text-xs text-bambu-gray">
  190. {t('library.runWithPipeline.sourceHint', 'Source')}:{' '}
  191. <span className="text-white">{source.filename}</span>
  192. </p>
  193. <div className="flex items-center gap-2">
  194. <label className="text-xs text-bambu-gray" htmlFor="run-pipeline-copies">
  195. {t('library.runWithPipeline.copies', 'Copies')}:
  196. </label>
  197. <input
  198. id="run-pipeline-copies"
  199. type="number"
  200. min={1}
  201. max={maxCopies}
  202. value={copies}
  203. onChange={(e) => {
  204. const n = parseInt(e.target.value, 10);
  205. if (Number.isNaN(n)) return;
  206. onCopiesChange(Math.max(1, Math.min(maxCopies, n)));
  207. }}
  208. aria-label={t('library.runWithPipeline.copies', 'Copies')}
  209. className="w-20 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded text-white"
  210. />
  211. <span className="text-xs text-bambu-gray/60">
  212. {t('library.runWithPipeline.copiesHint', 'max {{n}}', { n: maxCopies })}
  213. </span>
  214. </div>
  215. {loading && (
  216. <div className="flex items-center gap-2 text-sm text-bambu-gray">
  217. <Loader2 className="w-4 h-4 animate-spin" />
  218. {t('library.runWithPipeline.loading', 'Loading…')}
  219. </div>
  220. )}
  221. {!loading && pipelines.length === 0 && (
  222. <p className="text-sm text-bambu-gray">
  223. {t(
  224. 'library.runWithPipeline.empty',
  225. 'No pipelines saved yet. Open the Slice dialog and click "Save as pipeline" to create one.',
  226. )}
  227. </p>
  228. )}
  229. {!loading && pipelines.length > 0 && (
  230. <ul className="space-y-1.5" aria-label={t('library.runWithPipeline.pipelineListAria', 'Available pipelines')}>
  231. {pipelines.map((p) => {
  232. const isClass = p.target_kind === 'printer_class';
  233. const targetName = p.target_printer_id ? printerById[p.target_printer_id]?.name : null;
  234. const classLabel = isClass && p.target_model_class
  235. ? t('library.runWithPipeline.classTarget', 'Any {{model}}', { model: p.target_model_class })
  236. : null;
  237. const hasTarget = !!(p.target_printer_id || (isClass && p.target_model_class));
  238. return (
  239. <li key={p.id}>
  240. <button
  241. type="button"
  242. onClick={() => onPick(p)}
  243. disabled={!hasTarget}
  244. className="w-full text-left px-3 py-2 rounded-md border border-bambu-dark-tertiary bg-bambu-dark/40 hover:bg-bambu-dark-tertiary disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
  245. >
  246. <div className="flex items-center gap-2">
  247. <Cog className="w-3.5 h-3.5 text-bambu-green flex-shrink-0" />
  248. <span className="text-sm font-medium text-white truncate">{p.name}</span>
  249. </div>
  250. <div className="mt-1 text-xs text-bambu-gray flex items-center gap-1">
  251. <PrinterIcon className="w-3 h-3" />
  252. {classLabel ? (
  253. <span>{classLabel}</span>
  254. ) : targetName ? (
  255. <span>{targetName}</span>
  256. ) : (
  257. <span className="text-amber-700 dark:text-amber-400">
  258. {t('library.runWithPipeline.noTarget', 'No target printer set')}
  259. </span>
  260. )}
  261. </div>
  262. </button>
  263. </li>
  264. );
  265. })}
  266. </ul>
  267. )}
  268. </>
  269. );
  270. }
  271. function ConfirmStep({
  272. pipeline,
  273. report,
  274. source,
  275. onBack,
  276. onConfirm,
  277. running,
  278. }: {
  279. pipeline: SlicerPipeline;
  280. report: PipelineEligibilityReport;
  281. source: { filename: string };
  282. onBack: () => void;
  283. onConfirm: () => void;
  284. running: boolean;
  285. }) {
  286. const { t } = useTranslation();
  287. return (
  288. <>
  289. <div className="text-xs text-bambu-gray">
  290. <p>
  291. {t('library.runWithPipeline.confirmIntro', 'Pre-flight found issues with this run')}:
  292. </p>
  293. <p className="mt-1">
  294. <span className="text-bambu-gray/70">{t('library.runWithPipeline.sourceHint', 'Source')}: </span>
  295. <span className="text-white">{source.filename}</span>
  296. </p>
  297. <p>
  298. <span className="text-bambu-gray/70">{t('library.runWithPipeline.pipelineHint', 'Pipeline')}: </span>
  299. <span className="text-white">{pipeline.name}</span>
  300. </p>
  301. {report.target_printer_name && (
  302. <p>
  303. <span className="text-bambu-gray/70">{t('library.runWithPipeline.targetHint', 'Target')}: </span>
  304. <span className="text-white">{report.target_printer_name}</span>
  305. </p>
  306. )}
  307. </div>
  308. <ul className="space-y-1.5">
  309. {report.issues.map((issue, idx) => (
  310. <li key={idx} className="flex items-start gap-2 text-xs">
  311. <AlertTriangle className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5" />
  312. <span className="text-bambu-gray">
  313. <IssueText issue={issue} />
  314. </span>
  315. </li>
  316. ))}
  317. </ul>
  318. <div className="flex items-center justify-end gap-2 pt-2 border-t border-bambu-dark-tertiary">
  319. <button
  320. type="button"
  321. onClick={onBack}
  322. disabled={running}
  323. className="px-3 py-1.5 text-xs text-bambu-gray hover:text-white"
  324. >
  325. {t('common.back', 'Back')}
  326. </button>
  327. <button
  328. type="button"
  329. onClick={onConfirm}
  330. disabled={running}
  331. className="px-3 py-1.5 text-xs bg-amber-500 hover:bg-amber-600 text-white rounded disabled:opacity-50 flex items-center gap-1"
  332. >
  333. {running ? (
  334. <Loader2 className="w-3 h-3 animate-spin" />
  335. ) : (
  336. <Play className="w-3 h-3" />
  337. )}
  338. {t('library.runWithPipeline.runAnyway', 'Run anyway')}
  339. </button>
  340. </div>
  341. </>
  342. );
  343. }
  344. function IssueText({ issue }: { issue: PipelineEligibilityReport['issues'][number] }) {
  345. const { t } = useTranslation();
  346. switch (issue.kind) {
  347. case 'printer_not_set':
  348. return <>{t('library.runWithPipeline.issue.printerNotSet', 'No target printer set on this pipeline.')}</>;
  349. case 'printer_not_found':
  350. return <>{t('library.runWithPipeline.issue.printerNotFound', 'Target printer no longer exists.')}</>;
  351. case 'printer_disabled':
  352. return <>{t('library.runWithPipeline.issue.printerDisabled', 'Target printer is disabled.')}</>;
  353. case 'printer_offline':
  354. return <>{t('library.runWithPipeline.issue.printerOffline', 'Target printer is offline.')}</>;
  355. case 'filament_type_mismatch':
  356. return (
  357. <>
  358. {t('library.runWithPipeline.issue.filamentType', 'Filament slot {{slot}}: expected {{expected}}, AMS has {{actual}}', {
  359. slot: (issue.slot_index ?? 0) + 1,
  360. expected: issue.expected ?? '?',
  361. actual: issue.actual ?? '?',
  362. })}
  363. </>
  364. );
  365. case 'filament_color_mismatch':
  366. return (
  367. <>
  368. {t('library.runWithPipeline.issue.filamentColor', 'Filament slot {{slot}}: colour differs (expected {{expected}}, AMS has {{actual}})', {
  369. slot: (issue.slot_index ?? 0) + 1,
  370. expected: issue.expected ?? '?',
  371. actual: issue.actual ?? '?',
  372. })}
  373. </>
  374. );
  375. case 'ams_slot_missing':
  376. return (
  377. <>
  378. {t('library.runWithPipeline.issue.amsSlotMissing', 'AMS slot {{slot}} not available on this printer', {
  379. slot: (issue.slot_index ?? 0) + 1,
  380. })}
  381. </>
  382. );
  383. case 'filament_unverified':
  384. return (
  385. <>
  386. {t('library.runWithPipeline.issue.filamentUnverified', 'Filament slot {{slot}} comes from a cloud / standard preset and could not be statically verified.', {
  387. slot: (issue.slot_index ?? 0) + 1,
  388. })}
  389. </>
  390. );
  391. default:
  392. return <>{issue.kind}</>;
  393. }
  394. }