SliceJobTrackerContext.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. // Job ids whose terminal state has already been handled. `completeJob`
  78. // shows a toast and invalidates two query keys, so it has to be exactly
  79. // once per job no matter how many callers reach it — see the poll loop
  80. // below for how more than one used to.
  81. const finishedRef = useRef<Set<number>>(new Set());
  82. const renderProgressToast = useCallback(
  83. (job: TrackedJob) => {
  84. const startedAt = startedAtRef.current.get(job.id);
  85. if (startedAt == null) return;
  86. const elapsedSecs = (Date.now() - startedAt) / 1000;
  87. const phase = phaseRef.current.get(job.id) ?? 'pending';
  88. const elapsedStr = formatElapsed(elapsedSecs);
  89. const progress = progressRef.current.get(job.id) ?? null;
  90. // When the sidecar has emitted at least one progress frame, weave
  91. // the stage label + percent into the toast — that's what makes the
  92. // wait feel professional ("Generating G-code 75%" beats "Slicing X
  93. // — 47s"). Falls back to the elapsed-time-only message in three
  94. // cases: queued/pending phase before the slicer has started,
  95. // missing or zero progress (Initializing), or sidecar without
  96. // --pipe support.
  97. const hasUseful = progress && progress.stage && progress.total_percent > 0;
  98. if (phase === 'running' && hasUseful) {
  99. const name = prettifyFilename(job.sourceName);
  100. const stage = progress.stage;
  101. const percent = Math.min(100, Math.max(0, Math.round(progress.total_percent)));
  102. // Cross-class slice-all (#1493) feeds the same toast through N
  103. // sequential per-plate slices; the augmented snapshot tells us
  104. // which plate is currently running so the user sees the loop
  105. // progress, not just a single repeating bar.
  106. const isMultiPlateLoop =
  107. typeof progress.multi_plate_index === 'number' &&
  108. typeof progress.multi_plate_count === 'number' &&
  109. progress.multi_plate_count > 1;
  110. const message = isMultiPlateLoop
  111. ? t(
  112. 'slice.runningWithProgressMultiPlate',
  113. 'Plate {{plateIndex}} of {{plateCount}} • {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}',
  114. {
  115. plateIndex: progress.multi_plate_index,
  116. plateCount: progress.multi_plate_count,
  117. name,
  118. stage,
  119. percent,
  120. elapsed: elapsedStr,
  121. },
  122. )
  123. : t(
  124. 'slice.runningWithProgress',
  125. '{{name}} — {{stage}} ({{percent}}%) — {{elapsed}}',
  126. { name, stage, percent, elapsed: elapsedStr },
  127. );
  128. showPersistentToast(toastIdFor(job.id), message, 'loading');
  129. return;
  130. }
  131. const messageKey = phase === 'pending' ? 'slice.queuedToast' : 'slice.runningToast';
  132. const fallback =
  133. phase === 'pending'
  134. ? 'Queued: {{name}} — {{elapsed}}'
  135. : 'Slicing {{name}} — {{elapsed}}';
  136. showPersistentToast(
  137. toastIdFor(job.id),
  138. t(messageKey, fallback, { name: prettifyFilename(job.sourceName), elapsed: elapsedStr }),
  139. 'loading',
  140. );
  141. },
  142. [showPersistentToast, t],
  143. );
  144. const trackJob = useCallback(
  145. (id: number, kind: 'libraryFile' | 'archive', sourceName: string) => {
  146. setActiveJobs((prev) => (prev.some((j) => j.id === id) ? prev : [...prev, { id, kind, sourceName }]));
  147. // Re-tracking an id re-arms it. Ids come from a database sequence so
  148. // this can't collide in practice; clearing here is what keeps the set
  149. // from being a permanent record of every job the session ever saw.
  150. finishedRef.current.delete(id);
  151. startedAtRef.current.set(id, Date.now());
  152. phaseRef.current.set(id, 'pending');
  153. progressRef.current.set(id, null);
  154. // Render the initial frame immediately so the user sees the toast
  155. // before the first tick lands (~1s delay otherwise).
  156. renderProgressToast({ id, kind, sourceName });
  157. },
  158. [renderProgressToast],
  159. );
  160. const completeJob = useCallback(
  161. (job: TrackedJob, state: SliceJobState) => {
  162. // Guard, not an optimisation: everything below is a side effect the
  163. // user sees, and a second call would repeat all of it.
  164. if (finishedRef.current.has(job.id)) return;
  165. finishedRef.current.add(job.id);
  166. setActiveJobs((prev) => prev.filter((j) => j.id !== job.id));
  167. startedAtRef.current.delete(job.id);
  168. phaseRef.current.delete(job.id);
  169. progressRef.current.delete(job.id);
  170. // Replace the persistent progress toast with a transient
  171. // success/error toast (auto-dismisses after 3s, same as showToast).
  172. dismissToast(toastIdFor(job.id));
  173. if (state.status === 'completed') {
  174. // `used_embedded_settings` still comes back on the result for tests
  175. // and observability, but the warning toast that surfaced it was
  176. // firing on essentially every slice (3MF inputs trigger the
  177. // embedded-settings fallback as a normal path) and just added
  178. // noise — see the trailing yellow toast complaint, removed.
  179. showToast(
  180. t('slice.completedToast', 'Sliced {{name}}', { name: prettifyFilename(job.sourceName) }),
  181. 'success',
  182. );
  183. } else if (state.status === 'failed') {
  184. setSliceError({
  185. name: prettifyFilename(job.sourceName),
  186. detail: state.error_detail || t('slice.failed'),
  187. });
  188. }
  189. // Refresh whichever list owns the result. Both are cheap to invalidate.
  190. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  191. queryClient.invalidateQueries({ queryKey: ['archives'] });
  192. },
  193. [dismissToast, queryClient, showToast, t],
  194. );
  195. // Status polling. Updates phase on each successful poll and triggers
  196. // completeJob on terminal states.
  197. useEffect(() => {
  198. if (activeJobs.length === 0) return;
  199. let cancelled = false;
  200. // setInterval does not await an async callback, so a tick fires whether
  201. // or not the previous one came back. Slicing a large project blocks the
  202. // backend for seconds at a time (zip parsing and output assembly are
  203. // synchronous), and every tick that piled up during the stall had
  204. // already captured a snapshot naming the job as active. They all
  205. // resolved `completed` together and each called completeJob, which is
  206. // how one slice produced a stream of a dozen "Sliced X" toasts. Letting
  207. // only one poll round be in flight fixes that at the source, and stops
  208. // queueing requests against a backend that is already saturated.
  209. let polling = false;
  210. const interval = setInterval(async () => {
  211. if (cancelled || polling) return;
  212. polling = true;
  213. try {
  214. const snapshot = [...activeJobsRef.current];
  215. for (const job of snapshot) {
  216. try {
  217. const state = await api.getSliceJob(job.id);
  218. // The tracker may have been torn down while this was in flight.
  219. if (cancelled) return;
  220. phaseRef.current.set(job.id, state.status);
  221. // Capture the latest progress snapshot if the sidecar fed
  222. // one through. The 1s tick re-renders the toast off this ref.
  223. if (state.progress) {
  224. progressRef.current.set(job.id, state.progress);
  225. }
  226. if (state.status === 'completed' || state.status === 'failed') {
  227. completeJob(job, state);
  228. }
  229. } catch {
  230. // Transient poll failure — stay tracked, retry next tick.
  231. }
  232. }
  233. } finally {
  234. polling = false;
  235. }
  236. }, POLL_INTERVAL_MS);
  237. return () => {
  238. cancelled = true;
  239. clearInterval(interval);
  240. };
  241. }, [activeJobs.length, completeJob]);
  242. // 1Hz tick that re-renders each persistent progress toast with the
  243. // current elapsed time. Independent of the status poll so the counter
  244. // stays smooth even while the backend is slow to respond.
  245. useEffect(() => {
  246. if (activeJobs.length === 0) return;
  247. const tick = setInterval(() => {
  248. for (const job of activeJobsRef.current) {
  249. renderProgressToast(job);
  250. }
  251. }, TICK_INTERVAL_MS);
  252. return () => clearInterval(tick);
  253. }, [activeJobs.length, renderProgressToast]);
  254. return (
  255. <SliceJobTrackerContext.Provider value={{ trackJob, activeJobs }}>
  256. {children}
  257. {sliceError && (
  258. <AlertModal
  259. title={t('slice.failedTitle')}
  260. subtitle={sliceError.name}
  261. message={sliceError.detail}
  262. onClose={() => setSliceError(null)}
  263. />
  264. )}
  265. </SliceJobTrackerContext.Provider>
  266. );
  267. }
  268. export function useSliceJobTracker(): SliceJobTrackerContextValue {
  269. const ctx = useContext(SliceJobTrackerContext);
  270. if (!ctx) {
  271. throw new Error('useSliceJobTracker must be used inside SliceJobTrackerProvider');
  272. }
  273. return ctx;
  274. }