RunWithPipelineModal.tsx 15 KB

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