SliceJobTrackerContext.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /**
  2. * Background slice-job tracker.
  3. *
  4. * SliceModal calls `trackJob(id, kind)` after enqueuing and closes
  5. * immediately. This context keeps the job-id list, polls each one, and
  6. * shows toasts on terminal state. Lives at app level so polling continues
  7. * across navigation — slice can run in the background while the user does
  8. * other things.
  9. *
  10. * Each tracked job also gets a persistent toast (`slice-job-{id}`) with a
  11. * spinner + elapsed-time counter that updates every second so the user has
  12. * a continuous visual indicator while a long slice is running. The toast
  13. * is replaced by a transient success/error toast on terminal state.
  14. */
  15. import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react';
  16. import { useTranslation } from 'react-i18next';
  17. import { useQueryClient } from '@tanstack/react-query';
  18. import { api, type SliceJobProgress, type SliceJobState, type SliceJobStatus } from '../api/client';
  19. import { useToast } from './ToastContext';
  20. import { AlertModal } from '../components/AlertModal';
  21. interface TrackedJob {
  22. id: number;
  23. kind: 'libraryFile' | 'archive';
  24. sourceName: string;
  25. }
  26. interface SliceJobTrackerContextValue {
  27. trackJob: (id: number, kind: 'libraryFile' | 'archive', sourceName: string) => void;
  28. activeJobs: TrackedJob[];
  29. }
  30. const SliceJobTrackerContext = createContext<SliceJobTrackerContextValue | null>(null);
  31. const POLL_INTERVAL_MS = 1500;
  32. const TICK_INTERVAL_MS = 1000;
  33. const toastIdFor = (jobId: number) => `slice-job-${jobId}`;
  34. /** Decode percent-encoded characters in a filename so the toast doesn't
  35. * show `stormtrooper-helmet%20h2d.3mf` for files that came from a source
  36. * with URL-encoded names (MakerWorld API, S3 path tails, etc.). The
  37. * MakerWorld import path now decodes at persist time, but already-imported
  38. * rows still carry the encoded form — this is a belt-and-suspenders
  39. * decode at display time so old rows look right too. Wrapped in try/catch
  40. * because malformed encodings (`%XY` where XY isn't hex) throw URIError. */
  41. function prettifyFilename(name: string): string {
  42. try {
  43. return decodeURIComponent(name);
  44. } catch {
  45. return name;
  46. }
  47. }
  48. function formatElapsed(seconds: number): string {
  49. const s = Math.max(0, Math.floor(seconds));
  50. if (s < 60) return `${s}s`;
  51. const m = Math.floor(s / 60);
  52. const remS = s % 60;
  53. if (m < 60) return `${m}m ${remS}s`;
  54. const h = Math.floor(m / 60);
  55. const remM = m % 60;
  56. return `${h}h ${remM}m`;
  57. }
  58. export function SliceJobTrackerProvider({ children }: { children: ReactNode }) {
  59. const { t } = useTranslation();
  60. const { showToast, showPersistentToast, dismissToast } = useToast();
  61. const queryClient = useQueryClient();
  62. const [activeJobs, setActiveJobs] = useState<TrackedJob[]>([]);
  63. // A failed slice surfaces as an acknowledge-only modal, not a toast: the
  64. // slicer's reason (e.g. "objects over the bed boundary") is actionable and
  65. // a 3s toast hides it before it can be read.
  66. const [sliceError, setSliceError] = useState<{ name: string; detail: string } | null>(null);
  67. // Stable mutable ref so the polling effect can read the current list
  68. // without re-subscribing every time it changes.
  69. const activeJobsRef = useRef<TrackedJob[]>([]);
  70. activeJobsRef.current = activeJobs;
  71. // Per-job start time, latest phase, and latest progress snapshot,
  72. // kept in refs so the 1s tick doesn't need to re-render on every
  73. // update. Keyed by job id.
  74. const startedAtRef = useRef<Map<number, number>>(new Map());
  75. const phaseRef = useRef<Map<number, SliceJobStatus>>(new Map());
  76. const progressRef = useRef<Map<number, SliceJobProgress | null>>(new Map());
  77. const renderProgressToast = useCallback(
  78. (job: TrackedJob) => {
  79. const startedAt = startedAtRef.current.get(job.id);
  80. if (startedAt == null) return;
  81. const elapsedSecs = (Date.now() - startedAt) / 1000;
  82. const phase = phaseRef.current.get(job.id) ?? 'pending';
  83. const elapsedStr = formatElapsed(elapsedSecs);
  84. const progress = progressRef.current.get(job.id) ?? null;
  85. // When the sidecar has emitted at least one progress frame, weave
  86. // the stage label + percent into the toast — that's what makes the
  87. // wait feel professional ("Generating G-code 75%" beats "Slicing X
  88. // — 47s"). Falls back to the elapsed-time-only message in three
  89. // cases: queued/pending phase before the slicer has started,
  90. // missing or zero progress (Initializing), or sidecar without
  91. // --pipe support.
  92. const hasUseful = progress && progress.stage && progress.total_percent > 0;
  93. if (phase === 'running' && hasUseful) {
  94. const name = prettifyFilename(job.sourceName);
  95. const stage = progress.stage;
  96. const percent = Math.min(100, Math.max(0, Math.round(progress.total_percent)));
  97. // Cross-class slice-all (#1493) feeds the same toast through N
  98. // sequential per-plate slices; the augmented snapshot tells us
  99. // which plate is currently running so the user sees the loop
  100. // progress, not just a single repeating bar.
  101. const isMultiPlateLoop =
  102. typeof progress.multi_plate_index === 'number' &&
  103. typeof progress.multi_plate_count === 'number' &&
  104. progress.multi_plate_count > 1;
  105. const message = isMultiPlateLoop
  106. ? t(
  107. 'slice.runningWithProgressMultiPlate',
  108. 'Plate {{plateIndex}} of {{plateCount}} • {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}',
  109. {
  110. plateIndex: progress.multi_plate_index,
  111. plateCount: progress.multi_plate_count,
  112. name,
  113. stage,
  114. percent,
  115. elapsed: elapsedStr,
  116. },
  117. )
  118. : t(
  119. 'slice.runningWithProgress',
  120. '{{name}} — {{stage}} ({{percent}}%) — {{elapsed}}',
  121. { name, stage, percent, elapsed: elapsedStr },
  122. );
  123. showPersistentToast(toastIdFor(job.id), message, 'loading');
  124. return;
  125. }
  126. const messageKey = phase === 'pending' ? 'slice.queuedToast' : 'slice.runningToast';
  127. const fallback =
  128. phase === 'pending'
  129. ? 'Queued: {{name}} — {{elapsed}}'
  130. : 'Slicing {{name}} — {{elapsed}}';
  131. showPersistentToast(
  132. toastIdFor(job.id),
  133. t(messageKey, fallback, { name: prettifyFilename(job.sourceName), elapsed: elapsedStr }),
  134. 'loading',
  135. );
  136. },
  137. [showPersistentToast, t],
  138. );
  139. const trackJob = useCallback(
  140. (id: number, kind: 'libraryFile' | 'archive', sourceName: string) => {
  141. setActiveJobs((prev) => (prev.some((j) => j.id === id) ? prev : [...prev, { id, kind, sourceName }]));
  142. startedAtRef.current.set(id, Date.now());
  143. phaseRef.current.set(id, 'pending');
  144. progressRef.current.set(id, null);
  145. // Render the initial frame immediately so the user sees the toast
  146. // before the first tick lands (~1s delay otherwise).
  147. renderProgressToast({ id, kind, sourceName });
  148. },
  149. [renderProgressToast],
  150. );
  151. const completeJob = useCallback(
  152. (job: TrackedJob, state: SliceJobState) => {
  153. setActiveJobs((prev) => prev.filter((j) => j.id !== job.id));
  154. startedAtRef.current.delete(job.id);
  155. phaseRef.current.delete(job.id);
  156. progressRef.current.delete(job.id);
  157. // Replace the persistent progress toast with a transient
  158. // success/error toast (auto-dismisses after 3s, same as showToast).
  159. dismissToast(toastIdFor(job.id));
  160. if (state.status === 'completed') {
  161. // `used_embedded_settings` still comes back on the result for tests
  162. // and observability, but the warning toast that surfaced it was
  163. // firing on essentially every slice (3MF inputs trigger the
  164. // embedded-settings fallback as a normal path) and just added
  165. // noise — see the trailing yellow toast complaint, removed.
  166. showToast(
  167. t('slice.completedToast', 'Sliced {{name}}', { name: prettifyFilename(job.sourceName) }),
  168. 'success',
  169. );
  170. } else if (state.status === 'failed') {
  171. setSliceError({
  172. name: prettifyFilename(job.sourceName),
  173. detail: state.error_detail || t('slice.failed'),
  174. });
  175. }
  176. // Refresh whichever list owns the result. Both are cheap to invalidate.
  177. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  178. queryClient.invalidateQueries({ queryKey: ['archives'] });
  179. },
  180. [dismissToast, queryClient, showToast, t],
  181. );
  182. // Status polling. Updates phase on each successful poll and triggers
  183. // completeJob on terminal states.
  184. useEffect(() => {
  185. if (activeJobs.length === 0) return;
  186. let cancelled = false;
  187. const interval = setInterval(async () => {
  188. if (cancelled) return;
  189. const snapshot = [...activeJobsRef.current];
  190. for (const job of snapshot) {
  191. try {
  192. const state = await api.getSliceJob(job.id);
  193. phaseRef.current.set(job.id, state.status);
  194. // Capture the latest progress snapshot if the sidecar fed
  195. // one through. The 1s tick re-renders the toast off this ref.
  196. if (state.progress) {
  197. progressRef.current.set(job.id, state.progress);
  198. }
  199. if (state.status === 'completed' || state.status === 'failed') {
  200. completeJob(job, state);
  201. }
  202. } catch {
  203. // Transient poll failure — stay tracked, retry next tick.
  204. }
  205. }
  206. }, POLL_INTERVAL_MS);
  207. return () => {
  208. cancelled = true;
  209. clearInterval(interval);
  210. };
  211. }, [activeJobs.length, completeJob]);
  212. // 1Hz tick that re-renders each persistent progress toast with the
  213. // current elapsed time. Independent of the status poll so the counter
  214. // stays smooth even while the backend is slow to respond.
  215. useEffect(() => {
  216. if (activeJobs.length === 0) return;
  217. const tick = setInterval(() => {
  218. for (const job of activeJobsRef.current) {
  219. renderProgressToast(job);
  220. }
  221. }, TICK_INTERVAL_MS);
  222. return () => clearInterval(tick);
  223. }, [activeJobs.length, renderProgressToast]);
  224. return (
  225. <SliceJobTrackerContext.Provider value={{ trackJob, activeJobs }}>
  226. {children}
  227. {sliceError && (
  228. <AlertModal
  229. title={t('slice.failedTitle')}
  230. subtitle={sliceError.name}
  231. message={sliceError.detail}
  232. onClose={() => setSliceError(null)}
  233. />
  234. )}
  235. </SliceJobTrackerContext.Provider>
  236. );
  237. }
  238. export function useSliceJobTracker(): SliceJobTrackerContextValue {
  239. const ctx = useContext(SliceJobTrackerContext);
  240. if (!ctx) {
  241. throw new Error('useSliceJobTracker must be used inside SliceJobTrackerProvider');
  242. }
  243. return ctx;
  244. }