QueuePage.test.tsx 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329
  1. /**
  2. * Tests for the QueuePage component.
  3. */
  4. import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
  5. import { fireEvent, screen, waitFor, within } from '@testing-library/react';
  6. import userEvent from '@testing-library/user-event';
  7. import { render } from '../utils';
  8. import { QueuePage } from '../../pages/QueuePage';
  9. import { http, HttpResponse } from 'msw';
  10. import { server } from '../mocks/server';
  11. import { setAuthToken } from '../../api/client';
  12. import { setColorCatalog, __resetColorCatalogForTests } from '../../utils/colors';
  13. // Mock queue data
  14. const mockQueueItems = [
  15. {
  16. id: 1,
  17. printer_id: 1,
  18. archive_id: 1,
  19. position: 1,
  20. status: 'pending',
  21. scheduled_time: null,
  22. require_previous_success: false,
  23. auto_off_after: false,
  24. manual_start: false,
  25. ams_mapping: null,
  26. plate_id: null,
  27. bed_levelling: 'on',
  28. flow_cali: 'off',
  29. vibration_cali: true,
  30. layer_inspect: false,
  31. timelapse: false,
  32. use_ams: true,
  33. started_at: null,
  34. completed_at: null,
  35. error_message: null,
  36. created_at: '2024-01-01T00:00:00Z',
  37. archive_name: 'Test Print 1',
  38. archive_thumbnail: '/thumb1.png',
  39. printer_name: 'Test Printer',
  40. print_time_seconds: 3600,
  41. },
  42. {
  43. id: 2,
  44. printer_id: 1,
  45. archive_id: 2,
  46. position: 2,
  47. status: 'printing',
  48. scheduled_time: null,
  49. require_previous_success: false,
  50. auto_off_after: true,
  51. manual_start: false,
  52. ams_mapping: null,
  53. plate_id: null,
  54. bed_levelling: 'on',
  55. flow_cali: 'off',
  56. vibration_cali: true,
  57. layer_inspect: false,
  58. timelapse: false,
  59. use_ams: true,
  60. started_at: '2024-01-01T10:00:00Z',
  61. completed_at: null,
  62. error_message: null,
  63. created_at: '2024-01-01T00:00:00Z',
  64. archive_name: 'Active Print',
  65. archive_thumbnail: '/thumb2.png',
  66. printer_name: 'Test Printer',
  67. print_time_seconds: 7200,
  68. },
  69. {
  70. id: 3,
  71. printer_id: 1,
  72. archive_id: 3,
  73. position: 3,
  74. status: 'completed',
  75. scheduled_time: null,
  76. require_previous_success: false,
  77. auto_off_after: false,
  78. manual_start: false,
  79. ams_mapping: null,
  80. plate_id: null,
  81. bed_levelling: 'on',
  82. flow_cali: 'off',
  83. vibration_cali: true,
  84. layer_inspect: false,
  85. timelapse: false,
  86. use_ams: true,
  87. started_at: '2024-01-01T08:00:00Z',
  88. completed_at: '2024-01-01T09:00:00Z',
  89. error_message: null,
  90. created_at: '2024-01-01T00:00:00Z',
  91. archive_name: 'Completed Print',
  92. archive_thumbnail: '/thumb3.png',
  93. printer_name: 'Test Printer',
  94. print_time_seconds: 1800,
  95. },
  96. ];
  97. const mockPrinters = [
  98. {
  99. id: 1,
  100. name: 'Test Printer',
  101. ip_address: '192.168.1.100',
  102. serial_number: 'TESTSERIAL0001',
  103. access_code: '12345678',
  104. model: 'X1C',
  105. enabled: true,
  106. created_at: '2024-01-01T00:00:00Z',
  107. },
  108. ];
  109. const HISTORY_STATUSES = ['completed', 'failed', 'skipped', 'cancelled'];
  110. type MockItem = { id: number; status: string; completed_at?: string | null; created_at?: string | null };
  111. // Serves one list of items the way the backend splits it: the active list on
  112. // /queue/ (by its status filter) and the paged, newest-first history on
  113. // /queue/history.
  114. function serveQueue(items: MockItem[]) {
  115. return [
  116. http.get('/api/v1/queue/', ({ request }) => {
  117. const status = new URL(request.url).searchParams.get('status');
  118. const wanted = status ? status.split(',') : null;
  119. return HttpResponse.json(wanted ? items.filter((i) => wanted.includes(i.status)) : items);
  120. }),
  121. http.get('/api/v1/queue/history', ({ request }) => {
  122. const params = new URL(request.url).searchParams;
  123. const limit = Number(params.get('limit') ?? 50);
  124. const when = (i: MockItem) => Date.parse(i.completed_at || i.created_at || '') || 0;
  125. const history = items
  126. .filter((i) => HISTORY_STATUSES.includes(i.status))
  127. .sort((a, b) => when(b) - when(a));
  128. return HttpResponse.json({ items: history.slice(0, limit), total: history.length, locations: [] });
  129. }),
  130. ];
  131. }
  132. describe('QueuePage', () => {
  133. beforeEach(() => {
  134. // Mock localStorage.getItem to return expected defaults for queue page
  135. vi.mocked(localStorage.getItem).mockImplementation((key: string) => {
  136. if (key === 'queue.historyCollapsed') return 'false'; // expanded
  137. if (key === 'queue.viewMode') return 'list';
  138. return null;
  139. });
  140. // Setup MSW handlers for this test
  141. server.use(
  142. ...serveQueue(mockQueueItems),
  143. http.get('/api/v1/printers/', () => {
  144. return HttpResponse.json(mockPrinters);
  145. }),
  146. http.delete('/api/v1/queue/:id', () => {
  147. return HttpResponse.json({ success: true });
  148. }),
  149. http.post('/api/v1/queue/:id/cancel', () => {
  150. return HttpResponse.json({ success: true });
  151. }),
  152. http.post('/api/v1/queue/:id/start', () => {
  153. return HttpResponse.json({ success: true });
  154. }),
  155. http.post('/api/v1/queue/:id/stop', () => {
  156. return HttpResponse.json({ success: true });
  157. }),
  158. http.post('/api/v1/queue/reorder', () => {
  159. return HttpResponse.json({ success: true });
  160. })
  161. );
  162. });
  163. describe('rendering', () => {
  164. it('renders the page title', async () => {
  165. render(<QueuePage />);
  166. await waitFor(() => {
  167. expect(screen.getByText('Print Queue')).toBeInTheDocument();
  168. });
  169. });
  170. it('renders the page description', async () => {
  171. render(<QueuePage />);
  172. await waitFor(() => {
  173. expect(screen.getByText('Schedule and manage your print jobs')).toBeInTheDocument();
  174. });
  175. });
  176. it('shows summary cards', async () => {
  177. render(<QueuePage />);
  178. await waitFor(() => {
  179. // Check for the page title (Print Queue is the h1)
  180. expect(screen.getByText('Print Queue')).toBeInTheDocument();
  181. });
  182. });
  183. it('shows filter dropdowns', async () => {
  184. render(<QueuePage />);
  185. await waitFor(() => {
  186. expect(screen.getByText('All Printers')).toBeInTheDocument();
  187. expect(screen.getByText('All Status')).toBeInTheDocument();
  188. });
  189. });
  190. });
  191. describe('queue items display', () => {
  192. it('shows pending queue items', async () => {
  193. render(<QueuePage />);
  194. await waitFor(() => {
  195. expect(screen.getByText('Test Print 1')).toBeInTheDocument();
  196. });
  197. });
  198. it('shows active printing items', async () => {
  199. render(<QueuePage />);
  200. await waitFor(() => {
  201. expect(screen.getByText('Active Print')).toBeInTheDocument();
  202. expect(screen.getByText('Currently Printing')).toBeInTheDocument();
  203. });
  204. });
  205. it('says when a slot printed in another colour than the file asks for (#3279)', async () => {
  206. const printing = {
  207. ...mockQueueItems[1],
  208. id: 91,
  209. color_substitutions: [{ slot_id: 1, type: 'PLA', wanted: '#A4AAAC', got: '#000000', tray: 1 }],
  210. };
  211. const done = {
  212. ...mockQueueItems[0],
  213. id: 92,
  214. status: 'completed',
  215. completed_at: '2024-01-02T00:00:00Z',
  216. color_substitutions: [{ slot_id: 2, type: 'PLA', wanted: '#FFFFFF', got: '#FF0000', tray: 3 }],
  217. };
  218. server.use(...serveQueue([printing, done] as MockItem[]));
  219. render(<QueuePage />);
  220. const badge = await screen.findByText(/^Slot 1 printed in .*\(#000000\), the file asks for .*\(#A4AAAC\)$/);
  221. expect(badge.closest('p')).toHaveAttribute(
  222. 'title',
  223. expect.stringContaining('different colour than the one in the file'),
  224. );
  225. // The History tab draws finished jobs with the compact row.
  226. await userEvent.setup().click(await screen.findByRole('button', { name: /^History/ }));
  227. expect(await screen.findByText(/^Slot 2 printed in .*\(#FF0000\), the file asks for .*\(#FFFFFF\)$/)).toBeInTheDocument();
  228. });
  229. it('shows no colour note for a job that printed in its colours', async () => {
  230. render(<QueuePage />);
  231. await screen.findByText('Test Print 1');
  232. expect(screen.queryByText(/printed in .*, the file asks for/)).not.toBeInTheDocument();
  233. });
  234. it('links a File Manager job to the File Manager, pointing at the file (#3336)', async () => {
  235. server.use(
  236. http.get('/api/v1/queue/', () =>
  237. HttpResponse.json([
  238. { ...mockQueueItems[0], id: 90, archive_id: null, archive_name: null, library_file_id: 13, library_file_name: 'From the library' },
  239. ]),
  240. ),
  241. );
  242. render(<QueuePage />);
  243. await screen.findByText('From the library');
  244. // /library is no route at all: the page came up empty.
  245. expect(screen.getByTitle('View in File Manager')).toHaveAttribute('href', '/files?highlight=13');
  246. });
  247. it('links an archive job to its archive', async () => {
  248. render(<QueuePage />);
  249. await screen.findByText('Test Print 1');
  250. expect(screen.getAllByTitle('View archive').map((a) => a.getAttribute('href'))).toContain('/archives?highlight=1');
  251. });
  252. describe('larger thumbnail on hover (#3313)', () => {
  253. const realMatchMedia = window.matchMedia;
  254. beforeEach(() => {
  255. window.matchMedia = ((query: string) => ({ ...realMatchMedia(query), matches: true })) as typeof window.matchMedia;
  256. });
  257. afterEach(() => {
  258. window.matchMedia = realMatchMedia;
  259. });
  260. function hoverThumbnail(archiveId: number) {
  261. const thumb = document.querySelector(`img[src*="/archives/${archiveId}/thumbnail"]`) as HTMLElement;
  262. fireEvent.mouseEnter(thumb.parentElement as HTMLElement);
  263. }
  264. it('shows on a queue card', async () => {
  265. render(<QueuePage />);
  266. await screen.findByText('Test Print 1');
  267. hoverThumbnail(1);
  268. expect(screen.getByTestId('thumbnail-hover-preview').getAttribute('src')).toContain('/archives/1/thumbnail');
  269. });
  270. it('shows on a history row', async () => {
  271. render(<QueuePage />);
  272. await userEvent.setup().click(await screen.findByRole('button', { name: /^History/ }));
  273. await screen.findByText('Completed Print');
  274. hoverThumbnail(3);
  275. expect(screen.getByTestId('thumbnail-hover-preview').getAttribute('src')).toContain('/archives/3/thumbnail');
  276. });
  277. });
  278. it('shows the queue override colour instead of the original 3MF colour (#3132)', async () => {
  279. const item = {
  280. ...mockQueueItems[0],
  281. id: 82,
  282. printer_id: null,
  283. target_model: 'P2S',
  284. archive_id: null,
  285. library_file_id: 13,
  286. archive_name: null,
  287. library_file_name: 'Override colour test',
  288. plate_id: 1,
  289. filament_used_grams: 23.66,
  290. filament_type: 'PLA',
  291. filament_color: '#7C4B00',
  292. filament_overrides: [
  293. {
  294. slot_id: 1,
  295. type: 'PLA',
  296. color: '#C2BAA7FF',
  297. color_name: 'Bone White',
  298. force_color_match: false,
  299. },
  300. ],
  301. };
  302. server.use(
  303. http.get('/api/v1/queue/', () => HttpResponse.json([item])),
  304. http.get('/api/v1/library/files/13/plates', () =>
  305. HttpResponse.json({
  306. file_id: 13,
  307. filename: 'override-colour.3mf',
  308. plates: [
  309. {
  310. index: 1,
  311. name: 'Plate 1',
  312. objects: ['Part'],
  313. has_thumbnail: false,
  314. thumbnail_url: null,
  315. print_time_seconds: 3095,
  316. filament_used_grams: 23.66,
  317. filaments: [
  318. {
  319. slot_id: 1,
  320. type: 'PLA',
  321. color: '#7C4B00',
  322. used_grams: 23.7,
  323. used_meters: 7.93,
  324. },
  325. ],
  326. },
  327. ],
  328. is_multi_plate: false,
  329. }),
  330. ),
  331. );
  332. render(<QueuePage />);
  333. const colourName = await screen.findByText('Bone White');
  334. const row = colourName.closest('.group');
  335. expect(row).not.toBeNull();
  336. expect(within(row as HTMLElement).getByTestId('filament-swatch')).toHaveAttribute(
  337. 'title',
  338. '#C2BAA7',
  339. );
  340. });
  341. it('shows the resolved AMS slot and bound spool when a physical mapping is stored (#3132)', async () => {
  342. const item = {
  343. ...mockQueueItems[0],
  344. id: 85,
  345. printer_id: 1,
  346. printer_name: 'Test Printer',
  347. archive_id: null,
  348. library_file_id: 16,
  349. archive_name: null,
  350. library_file_name: 'Resolved AMS mapping test',
  351. plate_id: 1,
  352. ams_mapping: [1],
  353. filament_overrides: [
  354. {
  355. slot_id: 1,
  356. type: 'PLA',
  357. color: '#8E351BFF',
  358. color_name: 'Caramel',
  359. force_color_match: false,
  360. },
  361. ],
  362. };
  363. server.use(
  364. http.get('/api/v1/queue/', () => HttpResponse.json([item])),
  365. http.get('/api/v1/library/files/16/plates', () =>
  366. HttpResponse.json({
  367. file_id: 16,
  368. filename: 'resolved-mapping.3mf',
  369. plates: [
  370. {
  371. index: 1,
  372. name: 'Plate 1',
  373. objects: ['Part'],
  374. has_thumbnail: false,
  375. thumbnail_url: null,
  376. print_time_seconds: 3600,
  377. filament_used_grams: 20,
  378. filaments: [
  379. {
  380. slot_id: 1,
  381. type: 'PLA',
  382. color: '#7C4B00',
  383. used_grams: 20,
  384. used_meters: 6.7,
  385. },
  386. ],
  387. },
  388. ],
  389. is_multi_plate: false,
  390. }),
  391. ),
  392. http.get('/api/v1/printers/:id/status', () =>
  393. HttpResponse.json({
  394. id: 1,
  395. name: 'Test Printer',
  396. connected: true,
  397. state: 'IDLE',
  398. ams: [
  399. {
  400. id: 0,
  401. // Regular AMS units expose four tray records. Keeping all four
  402. // here matters because buildLoadedFilaments distinguishes a
  403. // regular AMS from a single-slot AMS-HT by tray count.
  404. tray: [
  405. { id: 0, tray_type: null },
  406. {
  407. id: 1,
  408. tray_type: 'PLA',
  409. tray_color: 'C2BAA7FF',
  410. tray_sub_brands: 'PLA Basic',
  411. tray_info_idx: 'GFA00',
  412. remain: 80,
  413. },
  414. { id: 2, tray_type: null },
  415. { id: 3, tray_type: null },
  416. ],
  417. },
  418. ],
  419. vt_tray: [],
  420. nozzles: [],
  421. ams_extruder_map: {},
  422. }),
  423. ),
  424. http.get('/api/v1/printers/:id/inventory-remain', () =>
  425. HttpResponse.json({
  426. inventory_remain_g: { '1': 800 },
  427. slot_materials: [
  428. {
  429. ams_id: 0,
  430. tray_id: 1,
  431. global_tray_id: 1,
  432. material_key: 'PLA|basic|bone-white',
  433. remaining_g: 800,
  434. extruder: 0,
  435. spool: {
  436. brand: 'eSUN',
  437. material: 'PLA',
  438. subtype: 'Basic',
  439. color_name: 'Bone White',
  440. rgba: 'C2BAA7FF',
  441. },
  442. },
  443. ],
  444. }),
  445. ),
  446. );
  447. render(<QueuePage />);
  448. const name = await screen.findByText('Resolved AMS mapping test');
  449. const row = name.closest('.group');
  450. expect(row).not.toBeNull();
  451. await waitFor(() => {
  452. expect(
  453. within(row as HTMLElement).getByText('A2 · eSUN PLA Basic · Bone White'),
  454. ).toBeInTheDocument();
  455. });
  456. expect(within(row as HTMLElement).queryByText('Caramel')).not.toBeInTheDocument();
  457. });
  458. it('resolves a mapped tray on a second regular AMS unit (#3132)', async () => {
  459. const item = {
  460. ...mockQueueItems[0],
  461. id: 86,
  462. printer_id: 1,
  463. printer_name: 'Test Printer',
  464. archive_id: null,
  465. library_file_id: 17,
  466. archive_name: null,
  467. library_file_name: 'Second AMS mapping test',
  468. plate_id: 1,
  469. ams_mapping: [5],
  470. filament_overrides: null,
  471. };
  472. server.use(
  473. http.get('/api/v1/queue/', () => HttpResponse.json([item])),
  474. http.get('/api/v1/library/files/17/plates', () =>
  475. HttpResponse.json({
  476. file_id: 17,
  477. filename: 'second-ams.3mf',
  478. plates: [
  479. {
  480. index: 1,
  481. name: 'Plate 1',
  482. objects: ['Part'],
  483. has_thumbnail: false,
  484. thumbnail_url: null,
  485. print_time_seconds: 3600,
  486. filament_used_grams: 20,
  487. filaments: [
  488. {
  489. slot_id: 1,
  490. type: 'PLA',
  491. color: '#111111',
  492. used_grams: 20,
  493. used_meters: 6.7,
  494. },
  495. ],
  496. },
  497. ],
  498. is_multi_plate: false,
  499. }),
  500. ),
  501. http.get('/api/v1/printers/:id/status', () =>
  502. HttpResponse.json({
  503. id: 1,
  504. name: 'Test Printer',
  505. connected: true,
  506. state: 'IDLE',
  507. ams: [
  508. {
  509. id: 1,
  510. tray: [
  511. { id: 0, tray_type: null },
  512. {
  513. id: 1,
  514. tray_type: 'PLA',
  515. tray_color: 'C2BAA7FF',
  516. tray_sub_brands: 'PLA Basic',
  517. tray_info_idx: 'GFA00',
  518. remain: 80,
  519. },
  520. { id: 2, tray_type: null },
  521. { id: 3, tray_type: null },
  522. ],
  523. },
  524. ],
  525. vt_tray: [],
  526. nozzles: [],
  527. ams_extruder_map: {},
  528. }),
  529. ),
  530. http.get('/api/v1/printers/:id/inventory-remain', () =>
  531. HttpResponse.json({
  532. inventory_remain_g: { '5': 800 },
  533. slot_materials: [
  534. {
  535. ams_id: 1,
  536. tray_id: 1,
  537. global_tray_id: 5,
  538. material_key: 'PLA|basic|bone-white',
  539. remaining_g: 800,
  540. extruder: 0,
  541. spool: {
  542. brand: 'eSUN',
  543. material: 'PLA',
  544. subtype: 'Basic',
  545. color_name: 'Bone White',
  546. rgba: 'C2BAA7FF',
  547. },
  548. },
  549. ],
  550. }),
  551. ),
  552. );
  553. render(<QueuePage />);
  554. const name = await screen.findByText('Second AMS mapping test');
  555. const row = name.closest('.group');
  556. expect(row).not.toBeNull();
  557. await waitFor(() => {
  558. expect(
  559. within(row as HTMLElement).getByText('B2 · eSUN PLA Basic · Bone White'),
  560. ).toBeInTheDocument();
  561. });
  562. });
  563. it('falls back to the selected plate 3MF colour when there is no override (#3132)', async () => {
  564. const item = {
  565. ...mockQueueItems[0],
  566. id: 83,
  567. printer_id: null,
  568. target_model: 'P2S',
  569. archive_id: null,
  570. library_file_id: 14,
  571. archive_name: null,
  572. library_file_name: 'Original colour test',
  573. plate_id: 1,
  574. filament_color: '#FFFFFF',
  575. filament_overrides: null,
  576. };
  577. server.use(
  578. http.get('/api/v1/queue/', () => HttpResponse.json([item])),
  579. http.get('/api/v1/library/files/14/plates', () =>
  580. HttpResponse.json({
  581. file_id: 14,
  582. filename: 'original-colour.3mf',
  583. plates: [
  584. {
  585. index: 1,
  586. name: 'Plate 1',
  587. objects: ['Part'],
  588. has_thumbnail: false,
  589. thumbnail_url: null,
  590. print_time_seconds: 3600,
  591. filament_used_grams: 20,
  592. filaments: [
  593. {
  594. slot_id: 1,
  595. type: 'PLA',
  596. color: '#7C4B00',
  597. used_grams: 20,
  598. used_meters: 6.7,
  599. },
  600. ],
  601. },
  602. ],
  603. is_multi_plate: false,
  604. }),
  605. ),
  606. );
  607. render(<QueuePage />);
  608. await screen.findByText('Original colour test');
  609. const row = screen.getByText('Original colour test').closest('.group');
  610. expect(row).not.toBeNull();
  611. await waitFor(() => {
  612. expect(within(row as HTMLElement).getByTestId('filament-swatch')).toHaveAttribute(
  613. 'title',
  614. '#7C4B00',
  615. );
  616. });
  617. });
  618. it('shows all used plate colours and only overrides the matching slot (#3132)', async () => {
  619. const item = {
  620. ...mockQueueItems[0],
  621. id: 84,
  622. printer_id: null,
  623. target_model: 'P2S',
  624. archive_id: null,
  625. library_file_id: 15,
  626. archive_name: null,
  627. library_file_name: 'Multi colour test',
  628. plate_id: 1,
  629. filament_overrides: [
  630. {
  631. slot_id: 2,
  632. type: 'PLA',
  633. color: '#C2BAA7FF',
  634. color_name: 'Bone White',
  635. force_color_match: false,
  636. },
  637. ],
  638. };
  639. server.use(
  640. http.get('/api/v1/queue/', () => HttpResponse.json([item])),
  641. http.get('/api/v1/library/files/15/plates', () =>
  642. HttpResponse.json({
  643. file_id: 15,
  644. filename: 'multi-colour.3mf',
  645. plates: [
  646. {
  647. index: 1,
  648. name: 'Plate 1',
  649. objects: ['Part'],
  650. has_thumbnail: false,
  651. thumbnail_url: null,
  652. print_time_seconds: 3600,
  653. filament_used_grams: 30,
  654. filaments: [
  655. {
  656. slot_id: 1,
  657. type: 'PLA',
  658. color: '#000000',
  659. used_grams: 20,
  660. used_meters: 6.7,
  661. },
  662. {
  663. slot_id: 2,
  664. type: 'PLA',
  665. color: '#7C4B00',
  666. used_grams: 10,
  667. used_meters: 3.35,
  668. },
  669. ],
  670. },
  671. ],
  672. is_multi_plate: false,
  673. }),
  674. ),
  675. );
  676. render(<QueuePage />);
  677. const overrideName = await screen.findByText('Bone White');
  678. const row = overrideName.closest('.group');
  679. expect(row).not.toBeNull();
  680. await waitFor(() => {
  681. const swatches = within(row as HTMLElement).getAllByTestId('filament-swatch');
  682. expect(swatches).toHaveLength(2);
  683. expect(swatches.map((swatch) => swatch.getAttribute('title'))).toEqual([
  684. '#000000',
  685. '#C2BAA7',
  686. ]);
  687. });
  688. });
  689. // The colour catalogue is keyed by product line: the same black is
  690. // "Charcoal" in PLA Matte and "Black" in PLA Basic. The plate's type is
  691. // only "PLA"; its slicer preset (tray_info_idx) names the line (SN-C9).
  692. describe('colour names by product line', () => {
  693. const plateWith = (filament: Record<string, unknown>) =>
  694. HttpResponse.json({
  695. file_id: 16,
  696. filename: 'matte.3mf',
  697. plates: [
  698. {
  699. index: 1,
  700. name: 'Plate 1',
  701. objects: ['Part'],
  702. has_thumbnail: false,
  703. thumbnail_url: null,
  704. print_time_seconds: 3600,
  705. filament_used_grams: 20,
  706. filaments: [{ slot_id: 1, type: 'PLA', color: '#000000', used_grams: 20, used_meters: 6.7, ...filament }],
  707. },
  708. ],
  709. is_multi_plate: false,
  710. });
  711. const show = async (plateFilament: Record<string, unknown> | null, overrides: unknown = null) => {
  712. const item = {
  713. ...mockQueueItems[0],
  714. id: 85,
  715. printer_id: null,
  716. target_model: 'P2S',
  717. archive_id: null,
  718. library_file_id: 16,
  719. archive_name: null,
  720. library_file_name: 'Product line test',
  721. plate_id: 1,
  722. filament_overrides: overrides,
  723. };
  724. server.use(
  725. http.get('/api/v1/queue/', () => HttpResponse.json([item])),
  726. http.get('/api/v1/library/files/16/plates', () =>
  727. plateFilament ? plateWith(plateFilament) : HttpResponse.json({ detail: 'Not found' }, { status: 404 }),
  728. ),
  729. http.get('/api/v1/cloud/builtin-filaments', () =>
  730. HttpResponse.json([
  731. { filament_id: 'GFA01', name: 'Bambu PLA Matte' },
  732. { filament_id: 'GFA00', name: 'Bambu PLA Basic' },
  733. ]),
  734. ),
  735. http.get('/api/v1/cloud/filament-id-map', () => HttpResponse.json({})),
  736. );
  737. render(<QueuePage />);
  738. await screen.findByText('Product line test');
  739. return screen.getByText('Product line test').closest('.group') as HTMLElement;
  740. };
  741. beforeEach(() => {
  742. setColorCatalog({ '000000': 'Black' }, { 'PLA Matte|000000': 'Charcoal' });
  743. });
  744. afterEach(() => {
  745. __resetColorCatalogForTests();
  746. });
  747. it("names the plate colour within the preset's product line", async () => {
  748. const row = await show({ tray_info_idx: 'GFA01' });
  749. expect(await within(row).findByText('Charcoal')).toBeInTheDocument();
  750. });
  751. it("names an override within the override's own preset", async () => {
  752. const row = await show({ tray_info_idx: 'GFA00' }, [
  753. { slot_id: 1, type: 'PLA', color: '#000000', tray_info_idx: 'GFA01', force_color_match: false },
  754. ]);
  755. expect(await within(row).findByText('Charcoal')).toBeInTheDocument();
  756. });
  757. it('names an override within its preset when the file has no plate listing', async () => {
  758. const row = await show(null, [
  759. { slot_id: 1, type: 'PLA', color: '#000000', tray_info_idx: 'GFA01', force_color_match: false },
  760. ]);
  761. expect(await within(row).findByText('Charcoal')).toBeInTheDocument();
  762. });
  763. it("does not lend the plate's preset to an override of another filament", async () => {
  764. const row = await show({ tray_info_idx: 'GFA01' }, [
  765. { slot_id: 1, type: 'PETG', color: '#000000', force_color_match: false },
  766. ]);
  767. expect(await within(row).findByText('Black')).toBeInTheDocument();
  768. expect(within(row).queryByText('Charcoal')).toBeNull();
  769. });
  770. });
  771. it('keeps an eight-colour job compact and exposes details in the tooltip (#3132)', async () => {
  772. const colours = [
  773. '#FF0000',
  774. '#00FF00',
  775. '#0000FF',
  776. '#FFFF00',
  777. '#FF00FF',
  778. '#00FFFF',
  779. '#FFFFFF',
  780. '#000000',
  781. ];
  782. const item = {
  783. ...mockQueueItems[0],
  784. id: 87,
  785. printer_id: null,
  786. target_model: 'P2S',
  787. archive_id: null,
  788. library_file_id: 18,
  789. archive_name: null,
  790. library_file_name: 'Eight colour test',
  791. plate_id: 1,
  792. filament_overrides: colours.map((color, index) => ({
  793. slot_id: index + 1,
  794. type: 'PLA',
  795. color,
  796. color_name: `Colour ${index + 1}`,
  797. force_color_match: false,
  798. })),
  799. };
  800. server.use(
  801. http.get('/api/v1/queue/', () => HttpResponse.json([item])),
  802. http.get('/api/v1/library/files/18/plates', () =>
  803. HttpResponse.json({
  804. file_id: 18,
  805. filename: 'eight-colour.3mf',
  806. plates: [
  807. {
  808. index: 1,
  809. name: 'Plate 1',
  810. objects: ['Part'],
  811. has_thumbnail: false,
  812. thumbnail_url: null,
  813. print_time_seconds: 3600,
  814. filament_used_grams: 40,
  815. filaments: colours.map((color, index) => ({
  816. slot_id: index + 1,
  817. type: 'PLA',
  818. color,
  819. used_grams: 5,
  820. used_meters: 1.7,
  821. })),
  822. },
  823. ],
  824. is_multi_plate: false,
  825. }),
  826. ),
  827. );
  828. render(<QueuePage />);
  829. const name = await screen.findByText('Eight colour test');
  830. const row = name.closest('.group');
  831. expect(row).not.toBeNull();
  832. await waitFor(() => {
  833. const compact = within(row as HTMLElement).getByTestId('queue-filament-compact');
  834. expect(compact).toHaveAttribute(
  835. 'title',
  836. colours.map((_, index) => `Colour ${index + 1}`).join('\n'),
  837. );
  838. expect(within(compact).getAllByTestId('filament-swatch')).toHaveLength(8);
  839. });
  840. // Touch screens never show the tooltip; the same lines are the group's
  841. // accessible name.
  842. expect(screen.getByRole('img', { name: /^Colour 1, Colour 2, .*Colour 8$/ })).toBe(
  843. within(row as HTMLElement).getByTestId('queue-filament-compact'),
  844. );
  845. // Compact mode keeps the long labels out of the metadata row itself.
  846. expect(within(row as HTMLElement).queryByText('Colour 1')).not.toBeInTheDocument();
  847. expect(within(row as HTMLElement).queryByText('Colour 8')).not.toBeInTheDocument();
  848. });
  849. describe('stored mapping on the live printer (#3132)', () => {
  850. const mappedItem = (amsMapping: number[], extra: Record<string, unknown> = {}) => ({
  851. ...mockQueueItems[0],
  852. id: 88,
  853. printer_id: 1,
  854. printer_name: 'Test Printer',
  855. archive_id: null,
  856. library_file_id: 19,
  857. archive_name: null,
  858. library_file_name: 'Mapped slot test',
  859. plate_id: 1,
  860. ams_mapping: amsMapping,
  861. filament_overrides: [
  862. {
  863. slot_id: 1,
  864. type: 'PLA',
  865. color: '#8E351BFF',
  866. color_name: 'Caramel',
  867. force_color_match: false,
  868. },
  869. ],
  870. ...extra,
  871. });
  872. const useMappedPrinter = (
  873. amsMapping: number[],
  874. status: Record<string, unknown>,
  875. item: Record<string, unknown> = {},
  876. ) => {
  877. server.use(
  878. http.get('/api/v1/queue/', () => HttpResponse.json([mappedItem(amsMapping, item)])),
  879. http.get('/api/v1/library/files/19/plates', () =>
  880. HttpResponse.json({
  881. file_id: 19,
  882. filename: 'mapped-slot.3mf',
  883. plates: [
  884. {
  885. index: 1,
  886. name: 'Plate 1',
  887. objects: ['Part'],
  888. has_thumbnail: false,
  889. thumbnail_url: null,
  890. print_time_seconds: 3600,
  891. filament_used_grams: 20,
  892. filaments: [
  893. { slot_id: 1, type: 'PLA', color: '#7C4B00', used_grams: 20, used_meters: 6.7 },
  894. ],
  895. },
  896. ],
  897. is_multi_plate: false,
  898. }),
  899. ),
  900. http.get('/api/v1/printers/:id/status', () =>
  901. HttpResponse.json({
  902. id: 1,
  903. name: 'Test Printer',
  904. state: 'IDLE',
  905. nozzles: [],
  906. ams_extruder_map: {},
  907. ...status,
  908. }),
  909. ),
  910. http.get('/api/v1/printers/:id/inventory-remain', () =>
  911. HttpResponse.json({ inventory_remain_g: {}, slot_materials: [] }),
  912. ),
  913. );
  914. };
  915. // Regular AMS units expose four tray records; slot A3 (global 2) is empty.
  916. const amsWithEmptyA3 = [
  917. {
  918. id: 0,
  919. tray: [
  920. { id: 0, tray_type: 'PLA', tray_color: 'FFFFFFFF', remain: 50 },
  921. { id: 1, tray_type: 'PLA', tray_color: 'C2BAA7FF', remain: 80 },
  922. // Firmware confirms A3 has no spool (tray_exist_bits bit clear).
  923. { id: 2, tray_type: null, exists: false, state: 9 },
  924. { id: 3, tray_type: null },
  925. ],
  926. },
  927. ];
  928. const mappedRow = async () => {
  929. render(<QueuePage />);
  930. const name = await screen.findByText('Mapped slot test');
  931. const row = name.closest('.group');
  932. expect(row).not.toBeNull();
  933. return row as HTMLElement;
  934. };
  935. it('resolves a mapping to the external spool', async () => {
  936. useMappedPrinter([254], {
  937. connected: true,
  938. ams: [],
  939. vt_tray: [{ id: 254, tray_type: 'PETG', tray_color: 'C2BAA7FF', remain: 60 }],
  940. });
  941. const row = await mappedRow();
  942. await waitFor(() => {
  943. expect(within(row).getByText(/^External · PETG · /)).toBeInTheDocument();
  944. });
  945. expect(within(row).queryByText('Caramel')).not.toBeInTheDocument();
  946. });
  947. it('says the mapped slot is empty, keeping the intended colour', async () => {
  948. useMappedPrinter([2], { connected: true, ams: amsWithEmptyA3, vt_tray: [] });
  949. const row = await mappedRow();
  950. await waitFor(() => {
  951. expect(within(row).getByText('A3 · Empty · Caramel')).toBeInTheDocument();
  952. });
  953. expect(within(row).getByTestId('filament-swatch')).toHaveAttribute('title', '#8E351B');
  954. });
  955. describe('AMS Filament Backup during the print', () => {
  956. const printing = { status: 'printing', started_at: '2024-01-01T10:00:00Z' };
  957. it('shows the backup spool the printer switched to', async () => {
  958. // A3 ran out at layer 350 and the printer carried on from A2.
  959. useMappedPrinter(
  960. [2],
  961. { connected: true, state: 'RUNNING', ams: amsWithEmptyA3, vt_tray: [], tray_change_log: [[2, 0], [1, 350]] },
  962. printing,
  963. );
  964. const row = await mappedRow();
  965. await waitFor(() => {
  966. expect(within(row).getByText(/^A2 · PLA · /)).toBeInTheDocument();
  967. });
  968. expect(within(row).queryByText(/Empty/)).not.toBeInTheDocument();
  969. });
  970. it('follows a backup that ran out in turn', async () => {
  971. useMappedPrinter(
  972. [2],
  973. {
  974. connected: true,
  975. state: 'RUNNING',
  976. ams: amsWithEmptyA3,
  977. vt_tray: [],
  978. tray_change_log: [[2, 0], [1, 120], [0, 400]],
  979. },
  980. printing,
  981. );
  982. const row = await mappedRow();
  983. await waitFor(() => {
  984. expect(within(row).getByText(/^A1 · PLA · /)).toBeInTheDocument();
  985. });
  986. expect(within(row).queryByText(/^A2 · /)).not.toBeInTheDocument();
  987. });
  988. it('does not take a change to another mapped slot for a backup', async () => {
  989. // Slot 2 of the job feeds from A2: switching there is a colour change.
  990. useMappedPrinter(
  991. [2, 1],
  992. { connected: true, state: 'RUNNING', ams: amsWithEmptyA3, vt_tray: [], tray_change_log: [[2, 0], [1, 30]] },
  993. printing,
  994. );
  995. const row = await mappedRow();
  996. await waitFor(() => {
  997. expect(within(row).getByText('A3 · Empty · Caramel')).toBeInTheDocument();
  998. });
  999. });
  1000. it('leaves a queued job pointed at its mapped slot', async () => {
  1001. // The log belongs to whatever the printer prints now, not this job.
  1002. useMappedPrinter([2], {
  1003. connected: true,
  1004. ams: amsWithEmptyA3,
  1005. vt_tray: [],
  1006. tray_change_log: [[2, 0], [1, 350]],
  1007. });
  1008. const row = await mappedRow();
  1009. await waitFor(() => {
  1010. expect(within(row).getByText('A3 · Empty · Caramel')).toBeInTheDocument();
  1011. });
  1012. });
  1013. });
  1014. it('never calls the external spool empty, having no presence signal', async () => {
  1015. // Shape the status route really sends: an external tray carries no
  1016. // state / exists, so an unconfigured spool and no spool look the same.
  1017. let statusServed = false;
  1018. useMappedPrinter([254], { connected: true, ams: [], vt_tray: [] });
  1019. server.use(
  1020. http.get('/api/v1/printers/:id/status', () => {
  1021. statusServed = true;
  1022. return HttpResponse.json({ id: 1, name: 'Test Printer', state: 'IDLE', connected: true, ams: [], vt_tray: [{ id: 254, tray_type: '' }], nozzles: [], ams_extruder_map: {} });
  1023. }),
  1024. );
  1025. const row = await mappedRow();
  1026. await waitFor(() => expect(statusServed).toBe(true));
  1027. expect(await within(row).findByText('Caramel')).toBeInTheDocument();
  1028. expect(within(row).queryByText(/Empty/)).not.toBeInTheDocument();
  1029. });
  1030. it('does not call a loaded but unconfigured spool empty (#2527)', async () => {
  1031. // A non-RFID spool the firmware can't identify has no tray_type but is
  1032. // physically present; the Printers page draws it as "?", not "Empty".
  1033. const ams = [
  1034. {
  1035. id: 0,
  1036. tray: [
  1037. { id: 0, tray_type: 'PLA', tray_color: 'FFFFFFFF', remain: 50 },
  1038. { id: 1, tray_type: 'PLA', tray_color: 'C2BAA7FF', remain: 80 },
  1039. { id: 2, tray_type: '', exists: true, state: 3 },
  1040. { id: 3, tray_type: null },
  1041. ],
  1042. },
  1043. ];
  1044. let statusServed = false;
  1045. useMappedPrinter([2], { connected: true, ams, vt_tray: [] });
  1046. server.use(
  1047. http.get('/api/v1/printers/:id/status', () => {
  1048. statusServed = true;
  1049. return HttpResponse.json({ id: 1, name: 'Test Printer', state: 'IDLE', connected: true, ams, vt_tray: [], nozzles: [], ams_extruder_map: {} });
  1050. }),
  1051. );
  1052. const row = await mappedRow();
  1053. await waitFor(() => expect(statusServed).toBe(true));
  1054. expect(await within(row).findByText('Caramel')).toBeInTheDocument();
  1055. expect(within(row).queryByText(/Empty/)).not.toBeInTheDocument();
  1056. });
  1057. it('does not call a slot empty while the printer is offline', async () => {
  1058. useMappedPrinter([2], { connected: false, ams: amsWithEmptyA3, vt_tray: [] });
  1059. const row = await mappedRow();
  1060. expect(await within(row).findByText('Caramel')).toBeInTheDocument();
  1061. expect(within(row).queryByText(/Empty/)).not.toBeInTheDocument();
  1062. });
  1063. });
  1064. it('shows one if-started-now ETA for an eligible pending item', async () => {
  1065. // Printer 1 is free: nothing is printing on it and nothing is queued ahead.
  1066. server.use(
  1067. http.get('/api/v1/queue/', () => {
  1068. return HttpResponse.json([mockQueueItems[0]]);
  1069. }),
  1070. );
  1071. render(<QueuePage />);
  1072. const name = await screen.findByText('Test Print 1');
  1073. const row = name.closest('.group');
  1074. expect(row).not.toBeNull();
  1075. const etaEl = within(row as HTMLElement).getAllByTestId('queue-item-eta');
  1076. expect(etaEl).toHaveLength(1);
  1077. // The tooltip must say what the number actually means, not reuse the
  1078. // printers-page "Estimated completion time" wording (which this is not).
  1079. expect(etaEl[0]).toHaveAttribute(
  1080. 'title',
  1081. 'Completion time if this job started now',
  1082. );
  1083. });
  1084. // The scheduler only writes waiting_reason on the model-based assignment
  1085. // path, so an item pinned to a specific printer carries no marker at all
  1086. // while it sits behind a running job. Without the printer-busy check every
  1087. // one of these quoted the same wrong "starts now" time.
  1088. it('does not show an ETA for an item pinned behind a running print', async () => {
  1089. render(<QueuePage />);
  1090. // mockQueueItems[1] ("Active Print") is printing on printer 1, and
  1091. // "Test Print 1" is pending on the same printer with waiting_reason null.
  1092. const name = await screen.findByText('Test Print 1');
  1093. const row = name.closest('.group');
  1094. expect(row).not.toBeNull();
  1095. expect(
  1096. within(row as HTMLElement).queryByTestId('queue-item-eta'),
  1097. ).not.toBeInTheDocument();
  1098. });
  1099. it('shows the ETA only on the next item up when several share an idle printer', async () => {
  1100. server.use(
  1101. http.get('/api/v1/queue/', () => {
  1102. return HttpResponse.json([
  1103. { ...mockQueueItems[0], id: 10, position: 1, archive_name: 'First up' },
  1104. { ...mockQueueItems[0], id: 11, position: 2, archive_name: 'Second up' },
  1105. { ...mockQueueItems[0], id: 12, position: 3, archive_name: 'Third up' },
  1106. ]);
  1107. }),
  1108. );
  1109. render(<QueuePage />);
  1110. await screen.findByText('Third up');
  1111. const etaRowNames = screen
  1112. .queryAllByTestId('queue-item-eta')
  1113. .map((el) => el.closest('.group')?.textContent);
  1114. expect(etaRowNames).toHaveLength(1);
  1115. expect(etaRowNames[0]).toContain('First up');
  1116. });
  1117. it('shows an ETA for a staged item queued behind others on an idle printer', async () => {
  1118. // The scheduler skips manual-start items without claiming the printer, so
  1119. // a staged job is startable whenever its printer is free — queue order
  1120. // does not gate it.
  1121. server.use(
  1122. http.get('/api/v1/queue/', () => {
  1123. return HttpResponse.json([
  1124. { ...mockQueueItems[0], id: 20, position: 1, archive_name: 'Auto first' },
  1125. {
  1126. ...mockQueueItems[0],
  1127. id: 21,
  1128. position: 2,
  1129. archive_name: 'Staged second',
  1130. manual_start: true,
  1131. },
  1132. ]);
  1133. }),
  1134. );
  1135. render(<QueuePage />);
  1136. const name = await screen.findByText('Staged second');
  1137. const row = name.closest('.group');
  1138. expect(row).not.toBeNull();
  1139. expect(
  1140. within(row as HTMLElement).getAllByTestId('queue-item-eta'),
  1141. ).toHaveLength(1);
  1142. });
  1143. it('does not show an ETA for an item conditional on a previous print', async () => {
  1144. server.use(
  1145. http.get('/api/v1/queue/', () => {
  1146. return HttpResponse.json([
  1147. {
  1148. ...mockQueueItems[0],
  1149. archive_name: 'Conditional Print',
  1150. require_previous_success: true,
  1151. },
  1152. ]);
  1153. }),
  1154. );
  1155. render(<QueuePage />);
  1156. const name = await screen.findByText('Conditional Print');
  1157. const row = name.closest('.group');
  1158. expect(row).not.toBeNull();
  1159. expect(
  1160. within(row as HTMLElement).queryByTestId('queue-item-eta'),
  1161. ).not.toBeInTheDocument();
  1162. });
  1163. it('advances the ETA as time passes', async () => {
  1164. vi.useFakeTimers({ shouldAdvanceTime: true });
  1165. vi.setSystemTime(new Date('2026-08-02T10:00:00Z'));
  1166. try {
  1167. server.use(
  1168. http.get('/api/v1/queue/', () => {
  1169. return HttpResponse.json([mockQueueItems[0]]);
  1170. }),
  1171. );
  1172. render(<QueuePage />);
  1173. const name = await screen.findByText('Test Print 1');
  1174. const row = name.closest('.group') as HTMLElement;
  1175. const before = within(row).getByTestId('queue-item-eta').textContent;
  1176. // The queue payload never changes, so react-query hands back the same
  1177. // object and nothing here re-renders on its own. Only the page's own
  1178. // clock can move this value.
  1179. await vi.advanceTimersByTimeAsync(45 * 60 * 1000);
  1180. await waitFor(() => {
  1181. expect(
  1182. within(row).getByTestId('queue-item-eta').textContent,
  1183. ).not.toBe(before);
  1184. });
  1185. } finally {
  1186. vi.useRealTimers();
  1187. }
  1188. });
  1189. it('shows one if-started-now ETA for a staged item', async () => {
  1190. server.use(
  1191. http.get('/api/v1/queue/', () => {
  1192. return HttpResponse.json([
  1193. {
  1194. ...mockQueueItems[0],
  1195. archive_name: 'Staged Print',
  1196. manual_start: true,
  1197. },
  1198. ]);
  1199. }),
  1200. );
  1201. render(<QueuePage />);
  1202. const name = await screen.findByText('Staged Print');
  1203. const row = name.closest('.group');
  1204. expect(row).not.toBeNull();
  1205. expect(
  1206. within(row as HTMLElement).getAllByTestId('queue-item-eta'),
  1207. ).toHaveLength(1);
  1208. });
  1209. it('shows exactly one live ETA for a printing item', async () => {
  1210. server.use(
  1211. http.get('/api/v1/printers/:id/status', ({ params }) => {
  1212. return HttpResponse.json({
  1213. id: Number(params.id),
  1214. name: 'Test Printer',
  1215. connected: true,
  1216. state: 'RUNNING',
  1217. progress: 50,
  1218. remaining_time: 60,
  1219. layer_num: 50,
  1220. total_layers: 100,
  1221. filename: 'active.3mf',
  1222. });
  1223. }),
  1224. );
  1225. render(<QueuePage />);
  1226. const name = await screen.findByText('Active Print');
  1227. const row = name.closest('.group');
  1228. expect(row).not.toBeNull();
  1229. await waitFor(() => {
  1230. expect(
  1231. within(row as HTMLElement).getAllByText(/^ETA\s/),
  1232. ).toHaveLength(1);
  1233. });
  1234. expect(
  1235. within(row as HTMLElement).queryByTestId('queue-item-eta'),
  1236. ).not.toBeInTheDocument();
  1237. });
  1238. it('does not show an ETA for a waiting item', async () => {
  1239. server.use(
  1240. http.get('/api/v1/queue/', () => {
  1241. return HttpResponse.json([
  1242. {
  1243. ...mockQueueItems[0],
  1244. archive_name: 'Waiting Print',
  1245. waiting_reason: 'Waiting for matching printer',
  1246. },
  1247. ]);
  1248. }),
  1249. );
  1250. render(<QueuePage />);
  1251. const name = await screen.findByText('Waiting Print');
  1252. const row = name.closest('.group');
  1253. expect(row).not.toBeNull();
  1254. expect(
  1255. within(row as HTMLElement).queryByTestId('queue-item-eta'),
  1256. ).not.toBeInTheDocument();
  1257. });
  1258. it('does not show an if-started-now ETA for a scheduled item', async () => {
  1259. server.use(
  1260. http.get('/api/v1/queue/', () => {
  1261. return HttpResponse.json([
  1262. {
  1263. ...mockQueueItems[0],
  1264. archive_name: 'Scheduled Print',
  1265. scheduled_time: new Date(
  1266. Date.now() + 5 * 60 * 60 * 1000,
  1267. ).toISOString(),
  1268. },
  1269. ]);
  1270. }),
  1271. );
  1272. render(<QueuePage />);
  1273. const name = await screen.findByText('Scheduled Print');
  1274. const row = name.closest('.group');
  1275. expect(row).not.toBeNull();
  1276. expect(
  1277. within(row as HTMLElement).queryByTestId('queue-item-eta'),
  1278. ).not.toBeInTheDocument();
  1279. });
  1280. it('tells an unscheduled item when it runs, without naming a dispatch mode', async () => {
  1281. // ASAP and Queue differ only in where the item is inserted; neither is
  1282. // stored on it, so this column cannot tell them apart. Labelling every
  1283. // unscheduled item "ASAP" made a Queue choice look overridden, which is
  1284. // what both #2557 and #3018 opened on.
  1285. server.use(
  1286. http.get('/api/v1/queue/', () => {
  1287. return HttpResponse.json([
  1288. { ...mockQueueItems[0], archive_name: 'Queued Print', scheduled_time: null },
  1289. ]);
  1290. }),
  1291. );
  1292. render(<QueuePage />);
  1293. const name = await screen.findByText('Queued Print');
  1294. const row = name.closest('.group') as HTMLElement;
  1295. expect(row).not.toBeNull();
  1296. expect(within(row).getByText('When a printer is free')).toBeInTheDocument();
  1297. expect(within(row).queryByText('ASAP')).not.toBeInTheDocument();
  1298. });
  1299. it('does not render a dangling ETA for an invalid duration', async () => {
  1300. server.use(
  1301. http.get('/api/v1/queue/', () => {
  1302. return HttpResponse.json([
  1303. {
  1304. ...mockQueueItems[0],
  1305. archive_name: 'Invalid Duration Print',
  1306. print_time_seconds: -60,
  1307. },
  1308. ]);
  1309. }),
  1310. );
  1311. render(<QueuePage />);
  1312. const name = await screen.findByText('Invalid Duration Print');
  1313. const row = name.closest('.group');
  1314. expect(row).not.toBeNull();
  1315. expect(
  1316. within(row as HTMLElement).queryByTestId('queue-item-eta'),
  1317. ).not.toBeInTheDocument();
  1318. expect(
  1319. within(row as HTMLElement).queryByText(/^ETA(?:\s|$)/),
  1320. ).not.toBeInTheDocument();
  1321. });
  1322. it('shows completed items in history', async () => {
  1323. const user = userEvent.setup();
  1324. render(<QueuePage />);
  1325. // The History tab now owns the completed/cancelled/failed list.
  1326. await user.click(await screen.findByRole('button', { name: /^History/ }));
  1327. await waitFor(() => {
  1328. expect(screen.getByText('Completed Print')).toBeInTheDocument();
  1329. });
  1330. });
  1331. it('shows status badges', async () => {
  1332. render(<QueuePage />);
  1333. await waitFor(() => {
  1334. // Queue items should be visible with status indicators
  1335. expect(screen.getByText('Test Print 1')).toBeInTheDocument();
  1336. });
  1337. });
  1338. it('shows printer names', async () => {
  1339. render(<QueuePage />);
  1340. await waitFor(() => {
  1341. const printerElements = screen.getAllByText('Test Printer');
  1342. expect(printerElements.length).toBeGreaterThan(0);
  1343. });
  1344. });
  1345. it('renders queue items with plate_id correctly', async () => {
  1346. // Override with queue items that have plate_id set
  1347. server.use(
  1348. http.get('/api/v1/queue/', () => {
  1349. return HttpResponse.json([
  1350. {
  1351. ...mockQueueItems[0],
  1352. plate_id: 2,
  1353. archive_name: 'Multi-plate Print',
  1354. },
  1355. ]);
  1356. })
  1357. );
  1358. render(<QueuePage />);
  1359. await waitFor(() => {
  1360. expect(screen.getByText('Multi-plate Print')).toBeInTheDocument();
  1361. });
  1362. });
  1363. });
  1364. describe('history pagination', () => {
  1365. // #2682: History rendered the full count in the header but only ever drew
  1366. // the first 50 rows, with no way to reach the rest. It now paginates with
  1367. // a "Show more" control.
  1368. const manyHistory = Array.from({ length: 60 }, (_, i) => ({
  1369. ...mockQueueItems[2],
  1370. id: 100 + i,
  1371. batch_id: null,
  1372. archive_name: `History Item ${String(i).padStart(2, '0')}`,
  1373. // Descending completed_at so index 0 is newest and sorts first; the
  1374. // default History sort is by date, newest first.
  1375. completed_at: new Date(Date.UTC(2024, 0, 1, 0, 0, 0) - i * 60000).toISOString(),
  1376. }));
  1377. beforeEach(() => {
  1378. server.use(...serveQueue(manyHistory));
  1379. });
  1380. it('caps the History list at one page and reveals the rest on Show more', async () => {
  1381. const user = userEvent.setup();
  1382. render(<QueuePage />);
  1383. await user.click(await screen.findByRole('button', { name: /^History/ }));
  1384. // First page is drawn; an item past the 50-row cap is not.
  1385. await waitFor(() => {
  1386. expect(screen.getByText('History Item 00')).toBeInTheDocument();
  1387. });
  1388. expect(screen.queryByText('History Item 59')).not.toBeInTheDocument();
  1389. expect(screen.getByText('Showing 50 of 60')).toBeInTheDocument();
  1390. // Show more reveals the remainder and then disappears (nothing left).
  1391. await user.click(screen.getByRole('button', { name: /show more/i }));
  1392. await waitFor(() => {
  1393. expect(screen.getByText('History Item 59')).toBeInTheDocument();
  1394. });
  1395. expect(screen.queryByRole('button', { name: /show more/i })).not.toBeInTheDocument();
  1396. });
  1397. });
  1398. describe('empty state', () => {
  1399. it('shows empty state when no queue items', async () => {
  1400. server.use(...serveQueue([]));
  1401. render(<QueuePage />);
  1402. await waitFor(() => {
  1403. expect(screen.getByText('No prints scheduled')).toBeInTheDocument();
  1404. });
  1405. });
  1406. });
  1407. describe('filtering', () => {
  1408. it('has printer filter options', async () => {
  1409. const user = userEvent.setup();
  1410. render(<QueuePage />);
  1411. await waitFor(() => {
  1412. expect(screen.getByText('All Printers')).toBeInTheDocument();
  1413. });
  1414. const printerSelect = screen.getByDisplayValue('All Printers');
  1415. await user.click(printerSelect);
  1416. expect(screen.getByText('Unassigned')).toBeInTheDocument();
  1417. });
  1418. it('has status filter options', async () => {
  1419. const user = userEvent.setup();
  1420. render(<QueuePage />);
  1421. await waitFor(() => {
  1422. expect(screen.getByText('All Status')).toBeInTheDocument();
  1423. });
  1424. const statusSelect = screen.getByDisplayValue('All Status');
  1425. await user.click(statusSelect);
  1426. expect(screen.getByRole('option', { name: 'Pending' })).toBeInTheDocument();
  1427. expect(screen.getByRole('option', { name: 'Printing' })).toBeInTheDocument();
  1428. expect(screen.getByRole('option', { name: 'Completed' })).toBeInTheDocument();
  1429. });
  1430. });
  1431. describe('queue actions', () => {
  1432. it('shows edit button for pending items', async () => {
  1433. render(<QueuePage />);
  1434. await waitFor(() => {
  1435. expect(screen.getByText('Test Print 1')).toBeInTheDocument();
  1436. });
  1437. // Find the edit button (Pencil icon)
  1438. const editButtons = screen.getAllByTitle('Edit');
  1439. expect(editButtons.length).toBeGreaterThan(0);
  1440. });
  1441. it('shows cancel button for pending items', async () => {
  1442. render(<QueuePage />);
  1443. await waitFor(() => {
  1444. expect(screen.getByText('Test Print 1')).toBeInTheDocument();
  1445. });
  1446. const cancelButtons = screen.getAllByTitle('Cancel');
  1447. expect(cancelButtons.length).toBeGreaterThan(0);
  1448. });
  1449. it('shows stop button for printing items', async () => {
  1450. render(<QueuePage />);
  1451. await waitFor(() => {
  1452. expect(screen.getByText('Active Print')).toBeInTheDocument();
  1453. });
  1454. const stopButtons = screen.getAllByTitle('Stop Print');
  1455. expect(stopButtons.length).toBeGreaterThan(0);
  1456. });
  1457. it('shows re-queue button for history items', async () => {
  1458. const user = userEvent.setup();
  1459. render(<QueuePage />);
  1460. await user.click(await screen.findByRole('button', { name: /^History/ }));
  1461. await waitFor(() => {
  1462. expect(screen.getByText('Completed Print')).toBeInTheDocument();
  1463. });
  1464. const requeueButtons = screen.getAllByTitle('Re-queue');
  1465. expect(requeueButtons.length).toBeGreaterThan(0);
  1466. });
  1467. it('re-queues the plate the job printed (#3395)', async () => {
  1468. const plate = (index: number) => ({
  1469. index, name: '', has_thumbnail: false, thumbnail_url: null, objects: [`Part ${index}`],
  1470. filaments: [], print_time_seconds: 600, filament_used_grams: 5,
  1471. });
  1472. server.use(
  1473. ...serveQueue(mockQueueItems.map((i) => (i.id === 3 ? { ...i, plate_id: 2 } : i))),
  1474. http.get('/api/v1/archives/:id/plates', () =>
  1475. HttpResponse.json({ is_multi_plate: true, plates: [plate(1), plate(2), plate(3)] }),
  1476. ),
  1477. );
  1478. const user = userEvent.setup();
  1479. render(<QueuePage />);
  1480. await user.click(await screen.findByRole('button', { name: /^History/ }));
  1481. await screen.findByText('Completed Print');
  1482. await user.click(screen.getAllByTitle('Re-queue')[0]);
  1483. await waitFor(() => {
  1484. expect(screen.getByTestId('selected-plates-summary')).toHaveTextContent(/^Plate 2$/);
  1485. });
  1486. });
  1487. });
  1488. describe('clear history', () => {
  1489. it('shows clear history button when history exists', async () => {
  1490. const user = userEvent.setup();
  1491. render(<QueuePage />);
  1492. // Clear History only renders inside the History tab now.
  1493. await user.click(await screen.findByRole('button', { name: /^History/ }));
  1494. await waitFor(() => {
  1495. expect(screen.getByText('Clear History')).toBeInTheDocument();
  1496. });
  1497. });
  1498. it('opens confirm modal when clicking clear history', async () => {
  1499. const user = userEvent.setup();
  1500. render(<QueuePage />);
  1501. await user.click(await screen.findByRole('button', { name: /^History/ }));
  1502. await waitFor(() => {
  1503. expect(screen.getByText('Clear History')).toBeInTheDocument();
  1504. });
  1505. const clearButton = screen.getByRole('button', { name: /clear history/i });
  1506. await user.click(clearButton);
  1507. await waitFor(() => {
  1508. expect(screen.getByText(/Are you sure you want to remove all/i)).toBeInTheDocument();
  1509. });
  1510. });
  1511. });
  1512. describe('staged items', () => {
  1513. it('shows staged badge for manual_start items', async () => {
  1514. server.use(
  1515. http.get('/api/v1/queue/', () => {
  1516. return HttpResponse.json([
  1517. {
  1518. ...mockQueueItems[0],
  1519. manual_start: true,
  1520. },
  1521. ]);
  1522. })
  1523. );
  1524. render(<QueuePage />);
  1525. await waitFor(() => {
  1526. expect(screen.getByText('Staged')).toBeInTheDocument();
  1527. });
  1528. });
  1529. it('shows start button for staged items', async () => {
  1530. server.use(
  1531. http.get('/api/v1/queue/', () => {
  1532. return HttpResponse.json([
  1533. {
  1534. ...mockQueueItems[0],
  1535. manual_start: true,
  1536. },
  1537. ]);
  1538. })
  1539. );
  1540. render(<QueuePage />);
  1541. await waitFor(() => {
  1542. expect(screen.getByTitle('Start Print')).toBeInTheDocument();
  1543. });
  1544. });
  1545. // Without queue:start_unreviewed their jobs wait for staff to start them (#1620)
  1546. describe('waiting for review', () => {
  1547. const signInWith = (permissions: string[]) => {
  1548. setAuthToken('test-token', 'session');
  1549. server.use(
  1550. http.get('*/api/v1/auth/status', () => HttpResponse.json({ auth_enabled: true, requires_setup: false })),
  1551. http.get('*/api/v1/auth/me', () =>
  1552. HttpResponse.json({ id: 7, username: 'student', is_admin: false, permissions }),
  1553. ),
  1554. http.get('/api/v1/queue/', () =>
  1555. HttpResponse.json([{ ...mockQueueItems[0], manual_start: true, created_by_id: 7 }]),
  1556. ),
  1557. );
  1558. };
  1559. afterEach(() => {
  1560. setAuthToken(null);
  1561. });
  1562. it('tells a student their job waits for review and offers no start', async () => {
  1563. signInWith(['queue:read_own', 'queue:update_own', 'queue:delete_own']);
  1564. render(<QueuePage />);
  1565. expect(await screen.findByText('Waiting for review')).toBeInTheDocument();
  1566. const start = screen.getByTitle('Waiting for review: someone who manages the queue starts this job');
  1567. expect(start).toBeDisabled();
  1568. });
  1569. it('keeps the start button for users who may print without review', async () => {
  1570. signInWith(['queue:read_own', 'queue:update_own', 'queue:start_unreviewed']);
  1571. render(<QueuePage />);
  1572. expect(await screen.findByText('Staged')).toBeInTheDocument();
  1573. expect(screen.getByTitle('Start Print')).not.toBeDisabled();
  1574. });
  1575. });
  1576. });
  1577. describe('auto power off badge', () => {
  1578. it('shows power off badge when auto_off_after is true', async () => {
  1579. render(<QueuePage />);
  1580. await waitFor(() => {
  1581. expect(screen.getByText('Auto power off')).toBeInTheDocument();
  1582. });
  1583. });
  1584. });
  1585. describe('gcode injection badge', () => {
  1586. it('shows G-code badge when gcode_injection is true', async () => {
  1587. const itemsWithGcode = mockQueueItems.map((item, i) =>
  1588. i === 0 ? { ...item, gcode_injection: true } : item
  1589. );
  1590. server.use(
  1591. http.get('/api/v1/queue/', () => HttpResponse.json(itemsWithGcode)),
  1592. );
  1593. render(<QueuePage />);
  1594. await waitFor(() => {
  1595. expect(screen.getByText('G-code')).toBeInTheDocument();
  1596. });
  1597. });
  1598. it('does not show G-code badge when gcode_injection is false', async () => {
  1599. render(<QueuePage />);
  1600. await waitFor(() => {
  1601. expect(screen.getByText('Test Print 1')).toBeInTheDocument();
  1602. });
  1603. expect(screen.queryByText('G-code')).not.toBeInTheDocument();
  1604. });
  1605. });
  1606. describe('outcome prompt badge (#1898)', () => {
  1607. it('shows the badge only on items with confirm_outcome set', async () => {
  1608. const items = mockQueueItems.map((item, i) =>
  1609. i === 0 ? { ...item, confirm_outcome: true } : { ...item, confirm_outcome: false }
  1610. );
  1611. server.use(http.get('/api/v1/queue/', () => HttpResponse.json(items)));
  1612. render(<QueuePage />);
  1613. await waitFor(() => expect(screen.getByText('Test Print 1')).toBeInTheDocument());
  1614. const badges = screen.getAllByText('Outcome prompt');
  1615. expect(badges).toHaveLength(1);
  1616. expect(badges[0].closest('span')).toHaveAttribute('title', 'Asks how the print came out after it completes');
  1617. });
  1618. it('renders nothing when no item asks for an outcome', async () => {
  1619. render(<QueuePage />);
  1620. await waitFor(() => expect(screen.getByText('Test Print 1')).toBeInTheDocument());
  1621. expect(screen.queryByText('Outcome prompt')).not.toBeInTheDocument();
  1622. });
  1623. });
  1624. describe('filament-short ▶ flow (#1496)', () => {
  1625. /**
  1626. * The dispatch pre-flight flags a queue item as filament_short. The user
  1627. * clicks ▶, the backend re-checks live and either dispatches (no deficit
  1628. * anymore — clear flag) or returns 409 with the per-slot deficit so the
  1629. * frontend can render the "Print Anyway" confirm modal.
  1630. */
  1631. const shortItem = {
  1632. ...mockQueueItems[0],
  1633. manual_start: true,
  1634. filament_short: true,
  1635. };
  1636. it('renders the filament-short badge on a flagged pending row', async () => {
  1637. server.use(
  1638. http.get('/api/v1/queue/', () => HttpResponse.json([shortItem])),
  1639. );
  1640. render(<QueuePage />);
  1641. await waitFor(() => {
  1642. expect(screen.getByText(/Insufficient filament for the assigned spool/i)).toBeInTheDocument();
  1643. });
  1644. });
  1645. it('opens the Print Anyway modal when ▶ returns 409 and retries with skip_filament_check', async () => {
  1646. let secondCallSkippedCheck: boolean | null = null;
  1647. let attempts = 0;
  1648. server.use(
  1649. http.get('/api/v1/queue/', () => HttpResponse.json([shortItem])),
  1650. http.post('/api/v1/queue/:id/start', ({ request }) => {
  1651. attempts += 1;
  1652. const url = new URL(request.url);
  1653. const skip = url.searchParams.get('skip_filament_check') === 'true';
  1654. if (attempts === 1) {
  1655. return HttpResponse.json(
  1656. {
  1657. detail: {
  1658. code: 'insufficient_filament',
  1659. deficit: [
  1660. {
  1661. slot_id: 1,
  1662. ams_id: 0,
  1663. tray_id: 0,
  1664. filament_type: 'PLA',
  1665. required_grams: 270,
  1666. remaining_grams: 200,
  1667. },
  1668. ],
  1669. },
  1670. },
  1671. { status: 409 },
  1672. );
  1673. }
  1674. secondCallSkippedCheck = skip;
  1675. return HttpResponse.json({ ...shortItem, manual_start: false, filament_short: false });
  1676. }),
  1677. );
  1678. render(<QueuePage />);
  1679. const playButton = await screen.findByTitle(/Start Print|do not have permission to start prints/i);
  1680. await userEvent.click(playButton);
  1681. // Wait for the start endpoint to be hit (the 409 path returns to onError).
  1682. await waitFor(() => expect(attempts).toBe(1));
  1683. // Modal shows the deficit detail
  1684. await screen.findByRole('button', { name: /Print Anyway/i });
  1685. expect(
  1686. screen.getByText(/Slot 1: needs 270 g, 200 g remaining/i),
  1687. ).toBeInTheDocument();
  1688. await userEvent.click(screen.getByRole('button', { name: /Print Anyway/i }));
  1689. await waitFor(() => expect(secondCallSkippedCheck).toBe(true));
  1690. expect(attempts).toBe(2);
  1691. });
  1692. });
  1693. describe('filament-not-loaded ▶ flow (#2799)', () => {
  1694. /**
  1695. * The scheduler held the item because a filament it prints has no tray on
  1696. * the printer. ▶ asks the backend first: still missing is a 409 with the
  1697. * missing filaments, and "Print Anyway" retries with skip_filament_check.
  1698. */
  1699. const heldItem = {
  1700. ...mockQueueItems[0],
  1701. manual_start: true,
  1702. waiting_reason: 'Needs PETG #2850E0',
  1703. };
  1704. it('shows the missing filament and retries with skip_filament_check', async () => {
  1705. let secondCallSkippedCheck: boolean | null = null;
  1706. let attempts = 0;
  1707. server.use(
  1708. http.get('/api/v1/queue/', () => HttpResponse.json([heldItem])),
  1709. http.post('/api/v1/queue/:id/start', ({ request }) => {
  1710. attempts += 1;
  1711. if (attempts === 1) {
  1712. return HttpResponse.json(
  1713. { detail: { code: 'unmatched_filament', missing: ['PETG #2850E0'] } },
  1714. { status: 409 },
  1715. );
  1716. }
  1717. secondCallSkippedCheck = new URL(request.url).searchParams.get('skip_filament_check') === 'true';
  1718. return HttpResponse.json({ ...heldItem, manual_start: false });
  1719. }),
  1720. );
  1721. render(<QueuePage />);
  1722. const playButton = await screen.findByTitle(/Start Print|do not have permission to start prints/i);
  1723. await userEvent.click(playButton);
  1724. await waitFor(() => expect(attempts).toBe(1));
  1725. await screen.findByText('Filament not loaded');
  1726. // The dialog's message names what to load; the row says it too.
  1727. expect(screen.getByText(/no tray with this filament[\s\S]*PETG #2850E0/)).toBeInTheDocument();
  1728. await userEvent.click(screen.getByRole('button', { name: /Print Anyway/i }));
  1729. await waitFor(() => expect(secondCallSkippedCheck).toBe(true));
  1730. expect(attempts).toBe(2);
  1731. });
  1732. });
  1733. // #2667: mobile can't drag-reorder the queue, so pending rows get up/down
  1734. // arrows. They persist via the same POST /queue/reorder as drag. The
  1735. // buttons live in the DOM at every width (Tailwind `sm:hidden` is CSS-only),
  1736. // so they're clickable in jsdom.
  1737. describe('mobile reorder arrows (#2667)', () => {
  1738. const threePending = [1, 2, 3].map((n) => ({
  1739. ...mockQueueItems[0],
  1740. id: n,
  1741. archive_id: n,
  1742. position: n,
  1743. status: 'pending',
  1744. archive_name: `Pending ${n}`,
  1745. }));
  1746. it('renders Move Up / Move Down controls for pending items', async () => {
  1747. server.use(http.get('/api/v1/queue/', () => HttpResponse.json(threePending)));
  1748. render(<QueuePage />);
  1749. await waitFor(() => expect(screen.getByText('Pending 1')).toBeInTheDocument());
  1750. // One pair per pending row.
  1751. expect(screen.getAllByTitle('Move Up')).toHaveLength(3);
  1752. expect(screen.getAllByTitle('Move Down')).toHaveLength(3);
  1753. });
  1754. it('moving the first item down persists the swapped order', async () => {
  1755. let reorderBody: { items: { id: number; position: number }[] } | null = null;
  1756. server.use(
  1757. http.get('/api/v1/queue/', () => HttpResponse.json(threePending)),
  1758. http.post('/api/v1/queue/reorder', async ({ request }) => {
  1759. reorderBody = (await request.json()) as typeof reorderBody;
  1760. return HttpResponse.json({ message: 'ok' });
  1761. }),
  1762. );
  1763. render(<QueuePage />);
  1764. await waitFor(() => expect(screen.getByText('Pending 1')).toBeInTheDocument());
  1765. // First row's "Move Down": item 1 drops below item 2 → [2, 1, 3].
  1766. await userEvent.click(screen.getAllByTitle('Move Down')[0]);
  1767. await waitFor(() => expect(reorderBody).not.toBeNull());
  1768. expect(reorderBody!.items).toEqual([
  1769. { id: 2, position: 1 },
  1770. { id: 1, position: 2 },
  1771. { id: 3, position: 3 },
  1772. ]);
  1773. });
  1774. it('disables Move Up on the first row and Move Down on the last', async () => {
  1775. server.use(http.get('/api/v1/queue/', () => HttpResponse.json(threePending)));
  1776. render(<QueuePage />);
  1777. await waitFor(() => expect(screen.getByText('Pending 1')).toBeInTheDocument());
  1778. // Rows render top-to-bottom in position order.
  1779. expect(screen.getAllByTitle('Move Up')[0]).toBeDisabled();
  1780. expect(screen.getAllByTitle('Move Down')[2]).toBeDisabled();
  1781. });
  1782. });
  1783. describe('bulk edit G-code injection (#3058)', () => {
  1784. /**
  1785. * gcode_injection is a per-item column the single-item edit modal has
  1786. * always exposed, and PATCH /queue/bulk has always accepted — only the
  1787. * bulk dialog left it out, so turning injection on for a whole queue
  1788. * meant opening every item.
  1789. */
  1790. const settingsWithSnippets = {
  1791. auto_archive: true,
  1792. gcode_snippets: '{"X1C":{"start_gcode":"","end_gcode":"M400"}}',
  1793. };
  1794. /** Select the one pending row and open the bulk edit dialog. */
  1795. const openBulkEdit = async () => {
  1796. render(<QueuePage />);
  1797. await waitFor(() => expect(screen.getByText('Test Print 1')).toBeInTheDocument());
  1798. await userEvent.click(screen.getByText('Select All'));
  1799. await userEvent.click(await screen.findByTitle('Edit Selected'));
  1800. return screen.getByText('Edit 1 Item').closest('div')!.parentElement!;
  1801. };
  1802. it('offers the toggle when a G-code snippet is configured', async () => {
  1803. server.use(http.get('/api/v1/settings/', () => HttpResponse.json(settingsWithSnippets)));
  1804. await openBulkEdit();
  1805. expect(await screen.findByText('Inject G-code')).toBeInTheDocument();
  1806. });
  1807. it('hides the toggle when no snippet is configured', async () => {
  1808. await openBulkEdit();
  1809. // The dialog is open — other queue options are there, injection is not.
  1810. expect(screen.getByText('Staged (manual start)')).toBeInTheDocument();
  1811. expect(screen.queryByText('Inject G-code')).not.toBeInTheDocument();
  1812. });
  1813. it('sends gcode_injection with the bulk PATCH once toggled on', async () => {
  1814. let patchBody: Record<string, unknown> | null = null;
  1815. server.use(
  1816. http.get('/api/v1/settings/', () => HttpResponse.json(settingsWithSnippets)),
  1817. http.patch('/api/v1/queue/bulk', async ({ request }) => {
  1818. patchBody = (await request.json()) as Record<string, unknown>;
  1819. return HttpResponse.json({ updated_count: 1, skipped_count: 0, message: 'Updated 1 items' });
  1820. }),
  1821. );
  1822. const dialog = await openBulkEdit();
  1823. const row = (await screen.findByText('Inject G-code')).closest('div')!;
  1824. await userEvent.click(within(row).getByText('On'));
  1825. await userEvent.click(within(dialog).getByText('Apply Changes'));
  1826. await waitFor(() => expect(patchBody).not.toBeNull());
  1827. expect(patchBody!.item_ids).toEqual([1]);
  1828. expect(patchBody!.gcode_injection).toBe(true);
  1829. });
  1830. it('leaves gcode_injection out of the PATCH while it stays on "no change"', async () => {
  1831. let patchBody: Record<string, unknown> | null = null;
  1832. server.use(
  1833. http.get('/api/v1/settings/', () => HttpResponse.json(settingsWithSnippets)),
  1834. http.patch('/api/v1/queue/bulk', async ({ request }) => {
  1835. patchBody = (await request.json()) as Record<string, unknown>;
  1836. return HttpResponse.json({ updated_count: 1, skipped_count: 0, message: 'Updated 1 items' });
  1837. }),
  1838. );
  1839. const dialog = await openBulkEdit();
  1840. // Change something else entirely; injection must not ride along as false.
  1841. const stagedRow = screen.getByText('Staged (manual start)').closest('div')!;
  1842. await userEvent.click(within(stagedRow).getByText('On'));
  1843. await userEvent.click(within(dialog).getByText('Apply Changes'));
  1844. await waitFor(() => expect(patchBody).not.toBeNull());
  1845. expect(patchBody!.manual_start).toBe(true);
  1846. expect('gcode_injection' in patchBody!).toBe(false);
  1847. });
  1848. });
  1849. describe('bulk edit ask-for-outcome (#1898)', () => {
  1850. const openBulkEdit = async () => {
  1851. render(<QueuePage />);
  1852. await waitFor(() => expect(screen.getByText('Test Print 1')).toBeInTheDocument());
  1853. await userEvent.click(screen.getByText('Select All'));
  1854. await userEvent.click(await screen.findByTitle('Edit Selected'));
  1855. return screen.getByText('Edit 1 Item').closest('div')!.parentElement!;
  1856. };
  1857. const captureBulkPatch = () => {
  1858. const captured: { body: Record<string, unknown> | null } = { body: null };
  1859. server.use(
  1860. http.patch('/api/v1/queue/bulk', async ({ request }) => {
  1861. captured.body = (await request.json()) as Record<string, unknown>;
  1862. return HttpResponse.json({ updated_count: 1, skipped_count: 0, message: 'Updated 1 items' });
  1863. }),
  1864. );
  1865. return captured;
  1866. };
  1867. it('sends confirm_outcome with the bulk PATCH once toggled', async () => {
  1868. const captured = captureBulkPatch();
  1869. const dialog = await openBulkEdit();
  1870. const row = within(dialog).getByText('Ask for outcome').closest('div')!;
  1871. await userEvent.click(within(row).getByText('On'));
  1872. await userEvent.click(within(dialog).getByText('Apply Changes'));
  1873. await waitFor(() => expect(captured.body).not.toBeNull());
  1874. expect(captured.body!.item_ids).toEqual([1]);
  1875. expect(captured.body!.confirm_outcome).toBe(true);
  1876. });
  1877. it('leaves confirm_outcome out of the PATCH while it stays on "no change"', async () => {
  1878. const captured = captureBulkPatch();
  1879. const dialog = await openBulkEdit();
  1880. const timelapseRow = within(dialog).getByText('Timelapse').closest('div')!;
  1881. await userEvent.click(within(timelapseRow).getByText('On'));
  1882. await userEvent.click(within(dialog).getByText('Apply Changes'));
  1883. await waitFor(() => expect(captured.body).not.toBeNull());
  1884. expect(captured.body!.timelapse).toBe(true);
  1885. expect('confirm_outcome' in captured.body!).toBe(false);
  1886. });
  1887. });
  1888. // The page used to load the whole queue, history included, every five
  1889. // seconds; on a farm that stalled the server for over a minute.
  1890. describe('history from the server', () => {
  1891. it('asks /queue/ for active work only', async () => {
  1892. const statuses: (string | null)[] = [];
  1893. server.use(
  1894. http.get('/api/v1/queue/', ({ request }) => {
  1895. statuses.push(new URL(request.url).searchParams.get('status'));
  1896. return HttpResponse.json([mockQueueItems[0]]);
  1897. }),
  1898. );
  1899. render(<QueuePage />);
  1900. await screen.findByText('Test Print 1');
  1901. expect(statuses.length).toBeGreaterThan(0);
  1902. expect(statuses.every((s) => s === 'pending,printing,skipped')).toBe(true);
  1903. });
  1904. it('does not ask /queue/ at all while a finished status is selected', async () => {
  1905. const user = userEvent.setup();
  1906. const activeCalls: string[] = [];
  1907. server.use(
  1908. http.get('/api/v1/queue/', ({ request }) => {
  1909. activeCalls.push(new URL(request.url).searchParams.get('status') ?? '');
  1910. return HttpResponse.json([]);
  1911. }),
  1912. );
  1913. render(<QueuePage />);
  1914. await waitFor(() => expect(activeCalls.length).toBeGreaterThan(0));
  1915. await user.selectOptions(screen.getByDisplayValue('All Status'), 'completed');
  1916. activeCalls.length = 0;
  1917. await user.click(await screen.findByRole('button', { name: /^History/ }));
  1918. expect(await screen.findByText('Completed Print')).toBeInTheDocument();
  1919. expect(activeCalls).toEqual([]);
  1920. });
  1921. it('sends the sort to the server', async () => {
  1922. const user = userEvent.setup();
  1923. const requests: URLSearchParams[] = [];
  1924. server.use(
  1925. http.get('/api/v1/queue/history', ({ request }) => {
  1926. requests.push(new URL(request.url).searchParams);
  1927. return HttpResponse.json({ items: [mockQueueItems[2]], total: 1, locations: [] });
  1928. }),
  1929. );
  1930. render(<QueuePage />);
  1931. await user.click(await screen.findByRole('button', { name: /^History/ }));
  1932. await screen.findByText('Completed Print');
  1933. await user.selectOptions(screen.getByDisplayValue('Sort by Date'), 'name');
  1934. await waitFor(() => expect(requests.at(-1)?.get('sort_by')).toBe('name'));
  1935. expect(requests.at(-1)?.get('reverse')).toBeNull();
  1936. await user.click(screen.getByTitle('Descending (newest first)'));
  1937. await waitFor(() => expect(requests.at(-1)?.get('reverse')).toBe('true'));
  1938. });
  1939. it('offers the target locations found only in history', async () => {
  1940. server.use(
  1941. http.get('/api/v1/queue/history', () =>
  1942. HttpResponse.json({ items: [mockQueueItems[2]], total: 1, locations: ['Annex'] }),
  1943. ),
  1944. );
  1945. render(<QueuePage />);
  1946. expect(await screen.findByRole('option', { name: 'Annex' })).toBeInTheDocument();
  1947. });
  1948. it('counts every run of a batch, including those past the page', async () => {
  1949. const user = userEvent.setup();
  1950. const run = (id: number, status: string) => ({
  1951. ...mockQueueItems[2],
  1952. id,
  1953. status,
  1954. batch_id: 7,
  1955. batch_name: 'Order 7',
  1956. });
  1957. server.use(
  1958. http.get('/api/v1/queue/history', () =>
  1959. // One row on the page; the second run of its batch rides along after it
  1960. HttpResponse.json({ items: [run(70, 'completed'), run(71, 'failed')], total: 1, locations: [] }),
  1961. ),
  1962. );
  1963. render(<QueuePage />);
  1964. await user.click(await screen.findByRole('button', { name: /^History/ }));
  1965. // The failed run is past the page, yet the batch row counts it
  1966. const batchRow = (await screen.findByText('Order 7')).closest('button') as HTMLElement;
  1967. const failedCount = batchRow.querySelector('span.text-red-700');
  1968. expect(failedCount?.textContent).toBe('1');
  1969. });
  1970. it('clears history with one request carrying the filters', async () => {
  1971. const user = userEvent.setup();
  1972. let clearUrl: URL | null = null;
  1973. let deletes = 0;
  1974. server.use(
  1975. http.post('/api/v1/queue/history/clear', ({ request }) => {
  1976. clearUrl = new URL(request.url);
  1977. return HttpResponse.json({ cleared: 4, kept: 1 });
  1978. }),
  1979. http.delete('/api/v1/queue/:id', () => {
  1980. deletes += 1;
  1981. return HttpResponse.json({ deleted: true });
  1982. }),
  1983. );
  1984. render(<QueuePage />);
  1985. await user.click(await screen.findByRole('button', { name: /^History/ }));
  1986. await user.selectOptions(await screen.findByDisplayValue('All Status'), 'completed');
  1987. await user.click(await screen.findByRole('button', { name: /clear history/i }));
  1988. await screen.findByText(/Are you sure you want to remove all 1 item/i);
  1989. // The modal's confirm button is the second "Clear History"
  1990. await user.click(screen.getAllByRole('button', { name: /clear history/i }).at(-1)!);
  1991. await waitFor(() => expect(clearUrl).not.toBeNull());
  1992. expect(clearUrl!.searchParams.get('status')).toBe('completed');
  1993. expect(deletes).toBe(0);
  1994. expect(
  1995. await screen.findByText('Cleared 4 history item(s) Kept 1 that batch orders still need.'),
  1996. ).toBeInTheDocument();
  1997. });
  1998. });
  1999. });
  2000. describe('QueuePage: jobs held by failed prints on every printer of their model', () => {
  2001. it('offers Resume for the model', async () => {
  2002. let resumed: string | null = null;
  2003. server.use(
  2004. http.get('/api/v1/queue/', () =>
  2005. HttpResponse.json([
  2006. {
  2007. ...mockQueueItems[0],
  2008. printer_id: null,
  2009. printer_name: null,
  2010. target_model: 'X1C',
  2011. require_previous_success: true,
  2012. waiting_reason: 'The last print failed on every free matching printer',
  2013. },
  2014. ]),
  2015. ),
  2016. http.post('/api/v1/queue/model/:model/resume', ({ params }) => {
  2017. resumed = params.model as string;
  2018. return HttpResponse.json({ acknowledged: 2, printers: 2 });
  2019. }),
  2020. );
  2021. const user = userEvent.setup();
  2022. render(<QueuePage />);
  2023. await user.click(await screen.findByRole('button', { name: /resume after failure/i }));
  2024. // The confirm dialog's own button carries the same label.
  2025. await waitFor(() => expect(screen.getAllByRole('button', { name: /resume after failure/i })).toHaveLength(2));
  2026. await user.click(screen.getAllByRole('button', { name: /resume after failure/i })[1]);
  2027. await waitFor(() => expect(resumed).toBe('X1C'));
  2028. });
  2029. });