PrintersPagePlateCheckWiring.test.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /**
  2. * Build-plate check wiring on the printer card.
  3. *
  4. * Opening the check turns the chamber light on when it is off (the camera
  5. * needs it), then asks the backend for a check with the debug image. Closing
  6. * the result (X, Close or Escape) must turn the light back off -- but only if
  7. * the check was what turned it on. A failed check must restore the light too.
  8. * From the result modal: calibrate, delete a reference and save the ROI all
  9. * name THIS printer.
  10. */
  11. import { describe, it, expect, vi, beforeEach } from 'vitest';
  12. import { screen, waitFor, within, fireEvent } from '@testing-library/react';
  13. import userEvent from '@testing-library/user-event';
  14. import { http, HttpResponse } from 'msw';
  15. import { server } from '../mocks/server';
  16. const permissions = { denied: new Set<string>() };
  17. const mockUseAuth = {
  18. user: { id: 1, username: 'operator', permissions: [] as string[] },
  19. authEnabled: true,
  20. loading: false,
  21. isAdmin: false,
  22. login: vi.fn(),
  23. loginWithToken: vi.fn(),
  24. logout: vi.fn(),
  25. refreshAuth: vi.fn(),
  26. hasPermission: vi.fn((permission: string) => !permissions.denied.has(permission)),
  27. hasAnyPermission: vi.fn(() => true),
  28. canModify: vi.fn(() => true),
  29. };
  30. vi.mock('../../contexts/AuthContext', async (importOriginal) => {
  31. const actual = await importOriginal<typeof import('../../contexts/AuthContext')>();
  32. return { ...actual, useAuth: () => mockUseAuth };
  33. });
  34. import { render } from '../utils';
  35. import { PrintersPage } from '../../pages/PrintersPage';
  36. const PRINTER_ID = 9;
  37. // Opening with the light off waits 2.5 s for the camera before checking.
  38. const LIGHT_WAIT = { timeout: 6000 };
  39. const mockPrinter = {
  40. id: PRINTER_ID,
  41. name: 'Plate X1C',
  42. ip_address: '192.0.2.109',
  43. serial_number: '00M09A350100009',
  44. access_code: '12345678',
  45. model: 'X1C',
  46. enabled: true,
  47. plate_detection_enabled: true,
  48. nozzle_diameter: 0.4,
  49. nozzle_type: 'hardened_steel',
  50. auto_archive: true,
  51. created_at: '2024-01-01T00:00:00Z',
  52. updated_at: '2024-01-01T00:00:00Z',
  53. };
  54. const statusWithLight = (on: boolean) => ({
  55. connected: true,
  56. state: 'IDLE',
  57. progress: 0,
  58. layer_num: 0,
  59. total_layers: 0,
  60. temperatures: { nozzle: 25, bed: 25, chamber: 25 },
  61. remaining_time: 0,
  62. filename: null,
  63. wifi_signal: -50,
  64. speed_level: 2,
  65. chamber_light: on,
  66. vt_tray: [],
  67. ams: [],
  68. });
  69. const emptyResult = {
  70. is_empty: true,
  71. confidence: 0.93,
  72. difference_percent: 1.2,
  73. message: 'Plate is empty',
  74. has_debug_image: false,
  75. needs_calibration: false,
  76. failure_reason: null,
  77. reference_count: 2,
  78. max_references: 5,
  79. roi: { x: 0.1, y: 0.2, w: 0.6, h: 0.5 },
  80. };
  81. type Sent = { method: string; path: string; params: Record<string, string>; body: unknown };
  82. interface SetupOptions {
  83. lightOn?: boolean;
  84. checkResult?: Record<string, unknown>;
  85. checkStatus?: number;
  86. }
  87. function setup({ lightOn = false, checkResult = emptyResult, checkStatus = 200 }: SetupOptions = {}) {
  88. const sent: Sent[] = [];
  89. const log = async (request: Request) => {
  90. const url = new URL(request.url);
  91. const text = request.method === 'GET' ? '' : await request.text();
  92. sent.push({
  93. method: request.method,
  94. path: url.pathname.replace(`/api/v1/printers/${PRINTER_ID}`, ''),
  95. params: Object.fromEntries(url.searchParams.entries()),
  96. body: text ? JSON.parse(text) : null,
  97. });
  98. };
  99. server.use(
  100. http.get('/api/v1/printers/', () => HttpResponse.json([mockPrinter])),
  101. http.get('/api/v1/queue/', () => HttpResponse.json([])),
  102. http.get('/api/v1/printers/:id/status', () => HttpResponse.json(statusWithLight(lightOn))),
  103. http.post('/api/v1/printers/:id/chamber-light', async ({ request }) => {
  104. await log(request);
  105. return HttpResponse.json({ success: true, message: 'ok' });
  106. }),
  107. http.get('/api/v1/printers/:id/camera/check-plate', async ({ request }) => {
  108. await log(request);
  109. if (checkStatus !== 200) {
  110. return HttpResponse.json({ detail: 'Camera unreachable' }, { status: checkStatus });
  111. }
  112. return HttpResponse.json(checkResult);
  113. }),
  114. http.get('/api/v1/printers/:id/camera/plate-detection/references', () =>
  115. HttpResponse.json({
  116. references: [
  117. { index: 0, label: 'Textured', timestamp: '2024-01-01T00:00:00Z', has_image: true, thumbnail_url: '' },
  118. { index: 3, label: 'Smooth', timestamp: '2024-01-02T00:00:00Z', has_image: true, thumbnail_url: '' },
  119. ],
  120. max_references: 5,
  121. })
  122. ),
  123. http.get('/api/v1/printers/:id/camera/plate-detection/references/:index/thumbnail', () =>
  124. new HttpResponse(null, { status: 204 })
  125. ),
  126. http.post('/api/v1/printers/:id/camera/plate-detection/calibrate', async ({ request }) => {
  127. await log(request);
  128. return HttpResponse.json({ success: true, message: 'Calibrated', index: 2 });
  129. }),
  130. http.delete('/api/v1/printers/:id/camera/plate-detection/references/:index', async ({ request }) => {
  131. await log(request);
  132. return HttpResponse.json({ success: true, message: 'Deleted' });
  133. }),
  134. http.patch('/api/v1/printers/:id', async ({ request }) => {
  135. await log(request);
  136. return HttpResponse.json(mockPrinter);
  137. }),
  138. );
  139. render(<PrintersPage />);
  140. return sent;
  141. }
  142. const light = (on: boolean) => ({ method: 'POST', path: '/chamber-light', params: { on: String(on) }, body: null });
  143. const check = { method: 'GET', path: '/camera/check-plate', params: { include_debug_image: 'true' }, body: null };
  144. async function openCheck(user: ReturnType<typeof userEvent.setup>) {
  145. await user.click(await screen.findByTitle('Manage plate detection calibration'));
  146. }
  147. function modal() {
  148. return screen.getByText('Build Plate Check').closest('div.max-w-lg') as HTMLElement;
  149. }
  150. describe('PrintersPage plate check: chamber light handling', () => {
  151. beforeEach(() => {
  152. permissions.denied = new Set();
  153. });
  154. it('light off: turns it on, then checks with the debug image; X turns it back off', async () => {
  155. const user = userEvent.setup();
  156. const sent = setup({ lightOn: false });
  157. await openCheck(user);
  158. await screen.findByText('Build Plate Check', {}, LIGHT_WAIT);
  159. expect(sent).toEqual([light(true), check]);
  160. // The header X is the first button in the modal.
  161. await user.click(within(modal()).getAllByRole('button')[0]);
  162. await waitFor(() => expect(screen.queryByText('Build Plate Check')).toBeNull());
  163. await waitFor(() => expect(sent).toEqual([light(true), check, light(false)]));
  164. });
  165. it('light off: Escape closes the result and turns the light back off', async () => {
  166. const user = userEvent.setup();
  167. const sent = setup({ lightOn: false });
  168. await openCheck(user);
  169. await screen.findByText('Build Plate Check', {}, LIGHT_WAIT);
  170. fireEvent.keyDown(window, { key: 'Escape' });
  171. await waitFor(() => expect(screen.queryByText('Build Plate Check')).toBeNull());
  172. await waitFor(() => expect(sent).toEqual([light(true), check, light(false)]));
  173. });
  174. it('Escape pressed the moment the result shows still closes it', async () => {
  175. const user = userEvent.setup();
  176. const sent = setup({ lightOn: false });
  177. // Pressed from the DOM change itself: before React's passive effects of
  178. // that render could run, as on a busy machine.
  179. const pressed = { done: false };
  180. const observer = new MutationObserver(() => {
  181. if (!pressed.done && screen.queryByText('Build Plate Check')) {
  182. pressed.done = true;
  183. fireEvent.keyDown(window, { key: 'Escape' });
  184. }
  185. });
  186. observer.observe(document.body, { childList: true, subtree: true });
  187. try {
  188. await openCheck(user);
  189. await waitFor(() => expect(pressed.done).toBe(true), LIGHT_WAIT);
  190. await waitFor(() => expect(screen.queryByText('Build Plate Check')).toBeNull());
  191. await waitFor(() => expect(sent).toEqual([light(true), check, light(false)]));
  192. } finally {
  193. observer.disconnect();
  194. }
  195. });
  196. it('light already on: no chamber-light request on open or on close', async () => {
  197. const user = userEvent.setup();
  198. const sent = setup({ lightOn: true });
  199. await openCheck(user);
  200. await screen.findByText('Build Plate Check');
  201. await user.click(within(modal()).getByRole('button', { name: 'Close' }));
  202. await waitFor(() => expect(screen.queryByText('Build Plate Check')).toBeNull());
  203. await new Promise((r) => setTimeout(r, 50));
  204. expect(sent).toEqual([check]);
  205. });
  206. it('check failure (500): error toast, no modal, and the light it turned on goes back off', async () => {
  207. const user = userEvent.setup();
  208. const sent = setup({ lightOn: false, checkStatus: 500 });
  209. await openCheck(user);
  210. expect(await screen.findByText('Camera unreachable', {}, LIGHT_WAIT)).toBeInTheDocument();
  211. await waitFor(() => expect(sent).toEqual([light(true), check, light(false)]));
  212. expect(screen.queryByText('Build Plate Check')).toBeNull();
  213. });
  214. it('check failure with the light already on sends no chamber-light request', async () => {
  215. const user = userEvent.setup();
  216. const sent = setup({ lightOn: true, checkStatus: 500 });
  217. await openCheck(user);
  218. expect(await screen.findByText('Camera unreachable')).toBeInTheDocument();
  219. await new Promise((r) => setTimeout(r, 50));
  220. expect(sent).toEqual([check]);
  221. });
  222. it('without printers:update the check button is disabled and sends nothing', async () => {
  223. permissions.denied = new Set(['printers:update']);
  224. const user = userEvent.setup();
  225. const sent = setup({ lightOn: true });
  226. const buttons = (await screen.findAllByTitle('You do not have permission to update printers')).filter(
  227. (el) => el.tagName === 'BUTTON'
  228. );
  229. expect(buttons.length).toBeGreaterThanOrEqual(2);
  230. for (const b of buttons) {
  231. expect(b).toBeDisabled();
  232. await user.click(b);
  233. }
  234. await new Promise((r) => setTimeout(r, 50));
  235. expect(sent).toEqual([]);
  236. });
  237. });
  238. describe('PrintersPage plate check: result rendering', () => {
  239. beforeEach(() => {
  240. permissions.denied = new Set();
  241. });
  242. it('empty plate shows the empty verdict', async () => {
  243. const user = userEvent.setup();
  244. setup({ lightOn: true });
  245. await openCheck(user);
  246. expect(await screen.findByText('Plate appears empty')).toBeInTheDocument();
  247. expect(screen.queryByText('Objects detected on plate')).toBeNull();
  248. });
  249. it('occupied plate shows objects detected', async () => {
  250. const user = userEvent.setup();
  251. setup({ lightOn: true, checkResult: { ...emptyResult, is_empty: false } });
  252. await openCheck(user);
  253. expect(await screen.findByText('Objects detected on plate')).toBeInTheDocument();
  254. expect(screen.queryByText('Plate appears empty')).toBeNull();
  255. });
  256. it('failure_reason shows the could-not-run text instead of a verdict', async () => {
  257. const user = userEvent.setup();
  258. setup({ lightOn: true, checkResult: { ...emptyResult, failure_reason: 'no_camera_frame' } });
  259. await openCheck(user);
  260. expect(await screen.findByText('Plate check could not run')).toBeInTheDocument();
  261. expect(screen.getByText('no camera image')).toBeInTheDocument();
  262. expect(screen.queryByText('Plate appears empty')).toBeNull();
  263. });
  264. it('needs_calibration shows the calibration prompt and no ROI editor', async () => {
  265. const user = userEvent.setup();
  266. setup({ lightOn: true, checkResult: { ...emptyResult, needs_calibration: true } });
  267. await openCheck(user);
  268. expect(await screen.findByText('Calibration Required')).toBeInTheDocument();
  269. expect(screen.queryByText('Detection Area (ROI)')).toBeNull();
  270. expect(screen.queryByText('Plate appears empty')).toBeNull();
  271. });
  272. });
  273. describe('PrintersPage plate check: calibrate, references, ROI', () => {
  274. beforeEach(() => {
  275. permissions.denied = new Set();
  276. });
  277. it('Calibrate Empty Plate -> POST calibrate for this printer, then re-checks', async () => {
  278. const user = userEvent.setup();
  279. const sent = setup({ lightOn: true, checkResult: { ...emptyResult, needs_calibration: true } });
  280. await openCheck(user);
  281. await screen.findByText('Calibration Required');
  282. await user.click(screen.getByRole('button', { name: 'Calibrate Empty Plate' }));
  283. // The card never passes a label, so the request carries none.
  284. await waitFor(() =>
  285. expect(sent).toEqual([
  286. check,
  287. { method: 'POST', path: '/camera/plate-detection/calibrate', params: {}, body: null },
  288. check,
  289. ])
  290. );
  291. });
  292. it('Add Reference on a calibrated printer also POSTs calibrate', async () => {
  293. const user = userEvent.setup();
  294. const sent = setup({ lightOn: true });
  295. await openCheck(user);
  296. await user.click(await screen.findByRole('button', { name: /^Add Reference/ }));
  297. await waitFor(() =>
  298. expect(sent.filter((s) => s.path === '/camera/plate-detection/calibrate')).toHaveLength(1)
  299. );
  300. });
  301. it('deleting a reference DELETEs that reference index for this printer, then re-checks', async () => {
  302. const user = userEvent.setup();
  303. const sent = setup({ lightOn: true });
  304. await openCheck(user);
  305. // Second saved reference has index 3 (indices are not positions).
  306. const deletes = await screen.findAllByTitle('Delete reference');
  307. expect(deletes).toHaveLength(2);
  308. await user.click(deletes[1]);
  309. await waitFor(() =>
  310. expect(sent).toEqual([
  311. check,
  312. { method: 'DELETE', path: '/camera/plate-detection/references/3', params: {}, body: null },
  313. check,
  314. ])
  315. );
  316. });
  317. it('Save ROI -> PATCH /printers/{id} {plate_detection_roi}', async () => {
  318. const user = userEvent.setup();
  319. const sent = setup({ lightOn: true });
  320. await openCheck(user);
  321. await screen.findByText('Detection Area (ROI)');
  322. await user.click(within(modal()).getByRole('button', { name: 'Edit' }));
  323. const sliders = within(modal()).getAllByRole('slider');
  324. fireEvent.change(sliders[0], { target: { value: '0.25' } });
  325. await user.click(within(modal()).getByRole('button', { name: 'Save' }));
  326. await waitFor(() =>
  327. expect(sent).toContainEqual({
  328. method: 'PATCH',
  329. path: '',
  330. params: {},
  331. body: { plate_detection_roi: { x: 0.25, y: 0.2, w: 0.6, h: 0.5 } },
  332. })
  333. );
  334. // and then re-checks with the new area
  335. await waitFor(() => expect(sent.at(-1)).toEqual(check));
  336. });
  337. it('cancelling the ROI edit sends nothing', async () => {
  338. const user = userEvent.setup();
  339. const sent = setup({ lightOn: true });
  340. await openCheck(user);
  341. await screen.findByText('Detection Area (ROI)');
  342. await user.click(within(modal()).getByRole('button', { name: 'Edit' }));
  343. await user.click(within(modal()).getByRole('button', { name: 'Cancel' }));
  344. await new Promise((r) => setTimeout(r, 50));
  345. expect(sent).toEqual([check]);
  346. });
  347. });