StreamOverlayPage.test.tsx 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. /**
  2. * Tests for the StreamOverlayPage component.
  3. */
  4. import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
  5. import { act, screen, waitFor, render as rtlRender } from '@testing-library/react';
  6. import { StreamOverlayPage } from '../../pages/StreamOverlayPage';
  7. import { http, HttpResponse } from 'msw';
  8. import { server } from '../mocks/server';
  9. import { MemoryRouter, Route, Routes } from 'react-router-dom';
  10. import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
  11. import { ThemeProvider } from '../../contexts/ThemeContext';
  12. import { ToastProvider } from '../../contexts/ToastContext';
  13. import { AuthProvider } from '../../contexts/AuthContext';
  14. import { setStreamToken } from '../../api/client';
  15. const mockPrinter = {
  16. id: 1,
  17. name: 'X1 Carbon',
  18. ip_address: '192.168.1.100',
  19. serial_number: '00M09A350100001',
  20. access_code: '12345678',
  21. model: 'X1C',
  22. enabled: true,
  23. };
  24. const mockStatusIdle = {
  25. id: 1,
  26. name: 'X1 Carbon',
  27. connected: true,
  28. state: 'IDLE',
  29. progress: 0,
  30. current_print: null,
  31. remaining_time: null,
  32. layer_num: null,
  33. total_layers: null,
  34. stg_cur_name: null,
  35. };
  36. const mockStatusPrinting = {
  37. id: 1,
  38. name: 'X1 Carbon',
  39. connected: true,
  40. state: 'RUNNING',
  41. progress: 45,
  42. current_print: 'Benchy.gcode.3mf',
  43. remaining_time: 82,
  44. layer_num: 150,
  45. total_layers: 300,
  46. stg_cur_name: null,
  47. };
  48. // Custom render for StreamOverlayPage
  49. function renderOverlayPage(printerId: number, queryParams = '') {
  50. const queryClient = new QueryClient({
  51. defaultOptions: {
  52. queries: { retry: false, gcTime: 0 },
  53. mutations: { retry: false },
  54. },
  55. });
  56. return rtlRender(overlayTree(printerId, queryParams, queryClient));
  57. }
  58. function overlayTree(printerId: number, queryParams: string, queryClient: QueryClient) {
  59. return (
  60. <QueryClientProvider client={queryClient}>
  61. <MemoryRouter initialEntries={[`/overlay/${printerId}${queryParams}`]}>
  62. <AuthProvider>
  63. <ThemeProvider>
  64. <ToastProvider>
  65. <Routes>
  66. <Route path="/overlay/:printerId" element={<StreamOverlayPage />} />
  67. </Routes>
  68. </ToastProvider>
  69. </ThemeProvider>
  70. </AuthProvider>
  71. </MemoryRouter>
  72. </QueryClientProvider>
  73. );
  74. }
  75. describe('StreamOverlayPage', () => {
  76. const originalTitle = document.title;
  77. beforeEach(() => {
  78. // Mock WebSocket. vitest 4 dropped support for arrow-function constructor
  79. // mocks (`new (() => ...)` throws "is not a constructor"); use a plain
  80. // function so `new WebSocket(...)` resolves correctly.
  81. vi.stubGlobal(
  82. 'WebSocket',
  83. vi.fn().mockImplementation(function (this: { close: () => void; onmessage: null; onerror: null }) {
  84. this.close = vi.fn();
  85. this.onmessage = null;
  86. this.onerror = null;
  87. }),
  88. );
  89. server.use(
  90. http.get('/api/v1/printers/:id', () => {
  91. return HttpResponse.json(mockPrinter);
  92. }),
  93. http.get('/api/v1/printers/:id/status', () => {
  94. return HttpResponse.json(mockStatusIdle);
  95. })
  96. );
  97. });
  98. afterEach(() => {
  99. document.title = originalTitle;
  100. vi.unstubAllGlobals();
  101. });
  102. it.each(['1', '2'])('sizes custom logos against the portrait canvas in artwork %s', async (artwork) => {
  103. server.use(http.get('/api/v1/settings/overlay-logo', () => new HttpResponse(new Blob(['png'], { type: 'image/png' }))));
  104. renderOverlayPage(1, `?layout=portrait&artwork=${artwork}&logo=1`);
  105. expect(await screen.findByAltText('Custom logo')).toHaveStyle({ maxWidth: '216px', maxHeight: '268.8px' });
  106. });
  107. describe.each(['', 'layout=landscape&', 'layout=portrait&'])('branding with %s', (layout) => {
  108. it.each(['1', '2'])('uses the requested gradient in artwork %s', async (artwork) => {
  109. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json(mockStatusPrinting)));
  110. const { container } = renderOverlayPage(1, `?${layout}artwork=${artwork}&progressFrom=%23ff0000&progressTo=%230000ff`);
  111. await screen.findByAltText('Bambuddy');
  112. const bar = container.querySelector('[style*="width: 45%"]');
  113. expect(bar).toHaveStyle({ width: '45%', background: 'linear-gradient(to right, #ff0000, #0000ff)' });
  114. for (const text of [screen.getByText('Progress'), screen.getByText('45%')]) {
  115. expect(text).toHaveStyle({
  116. 'background-image': 'linear-gradient(to right, #ff0000, #0000ff)',
  117. 'background-clip': 'text',
  118. color: 'rgba(0, 0, 0, 0)',
  119. });
  120. }
  121. });
  122. it.each(['1', '2'])('ignores malformed branding colours in artwork %s', async (artwork) => {
  123. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json(mockStatusPrinting)));
  124. const { container } = renderOverlayPage(1, `?${layout}artwork=${artwork}&progressFrom=red&progressTo=%230000ff`);
  125. await screen.findByAltText('Bambuddy');
  126. expect(container.querySelector('[style*="linear-gradient"]')).toBeNull();
  127. });
  128. it.each([
  129. ['0', '1'], ['50', '0.5'], ['100', '0'], ['-10', '1'], ['150', '0'], ['invalid', '1'], ['', '1'],
  130. ])('validates Version 2 background transparency %s', async (value, alpha) => {
  131. const { container, unmount } = renderOverlayPage(1, `?${layout}artwork=2&camera=false&backgroundTransparency=${value}`);
  132. await screen.findByAltText('Bambuddy');
  133. expect(container.querySelector('.updated-overlay')).toHaveStyle({ '--overlay-background-alpha': alpha });
  134. if (alpha !== '1') expect(document.body.style.backgroundColor).toBe('transparent');
  135. unmount();
  136. expect(document.body.style.backgroundColor).not.toBe('transparent');
  137. });
  138. it('ignores background transparency in Classic', async () => {
  139. const { container } = renderOverlayPage(1, '?backgroundTransparency=100');
  140. await screen.findByAltText('Bambuddy');
  141. expect(container.querySelector('[style*="--overlay-background-alpha"]')).toBeNull();
  142. expect(document.body.style.backgroundColor).not.toBe('transparent');
  143. });
  144. });
  145. describe.each(['', 'layout=landscape&', 'layout=portrait&'])('consistent status for %s', (layout) => {
  146. it.each(['FINISH', 'FAILED', 'IDLE'])('honors the hidden status field for Classic %s', async (state) => {
  147. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json({ ...mockStatusPrinting, state })));
  148. renderOverlayPage(1, `?${layout}show=filename`);
  149. expect(await screen.findByText('Benchy')).toBeInTheDocument();
  150. expect(screen.queryByText('Printer is idle')).not.toBeInTheDocument();
  151. expect(screen.queryByText('Finished')).not.toBeInTheDocument();
  152. expect(screen.queryByText('Failed')).not.toBeInTheDocument();
  153. });
  154. it.each(['1', '2'])('keeps disconnected and finished states truthful in artwork %s', async (artwork) => {
  155. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json({ ...mockStatusPrinting, connected: false, temperatures: { nozzle: 210 } })));
  156. const view = renderOverlayPage(1, `?${layout}artwork=${artwork}&show=filename,status,progress,layers,eta,nozzle`);
  157. await screen.findAllByText('Printer offline');
  158. expect(screen.queryByText('45%')).not.toBeInTheDocument();
  159. expect(screen.queryByText('210°C')).not.toBeInTheDocument();
  160. expect(screen.queryByText('Printing')).not.toBeInTheDocument();
  161. view.unmount();
  162. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json({ ...mockStatusPrinting, state: 'FINISH' })));
  163. renderOverlayPage(1, `?${layout}artwork=${artwork}&show=filename,status,progress,layers,eta,nozzle`);
  164. expect(await screen.findByText('Finished')).toBeInTheDocument();
  165. expect(screen.queryByText('Printer is idle')).not.toBeInTheDocument();
  166. });
  167. });
  168. it.each(['', '&artwork=2'])('reconnects the kiosk camera without changing its token or settings (%s)', async (artwork) => {
  169. server.use(http.get('/api/v1/printers/:id/overlay-status', () => HttpResponse.json({
  170. ...mockStatusIdle, camera_rotation: 90,
  171. })));
  172. const timers = vi.spyOn(globalThis, 'setTimeout');
  173. const view = renderOverlayPage(1, `?token=overlay-test&fps=7${artwork}`);
  174. try {
  175. const image = await screen.findByAltText('Camera stream');
  176. const source = image.getAttribute('src');
  177. expect(source).toContain('token=overlay-test');
  178. const renewal = timers.mock.calls.find(([, delay]) => delay === 60_000)?.[0];
  179. expect(renewal).toBeTypeOf('function');
  180. if (typeof renewal !== 'function') throw new Error('Missing camera renewal timer');
  181. act(() => renewal());
  182. const renewed = screen.getByAltText('Camera stream');
  183. // Classic remounts the img; version 2 switches the src of the same one.
  184. if (!artwork) expect(renewed).not.toBe(image);
  185. expect(renewed.getAttribute('src')).not.toBe(source);
  186. expect(renewed.getAttribute('src')).toContain('token=overlay-test');
  187. expect(renewed.getAttribute('src')).toContain('fps=7');
  188. expect(renewed.style.transform).toBe(artwork ? 'translate(-50%, -50%) rotate(90deg)' : 'rotate(90deg)');
  189. } finally {
  190. view.unmount();
  191. timers.mockRestore();
  192. }
  193. });
  194. // A detached img keeps its MJPEG connection open (measured in Chromium, which
  195. // OBS browser sources run on): the old stream is closed before it is replaced.
  196. it.each(['', '&artwork=2'])('closes the old camera stream before it is replaced (%s)', async (artwork) => {
  197. server.use(http.get('/api/v1/printers/:id/overlay-status', () => HttpResponse.json(mockStatusIdle)));
  198. const timers = vi.spyOn(globalThis, 'setTimeout');
  199. const view = renderOverlayPage(1, `?token=overlay-test${artwork}`);
  200. try {
  201. const image = await screen.findByAltText('Camera stream');
  202. const close = timers.mock.calls.find(([, delay]) => delay === 59_800)?.[0];
  203. const renewal = timers.mock.calls.find(([, delay]) => delay === 60_000)?.[0];
  204. if (typeof close !== 'function' || typeof renewal !== 'function') throw new Error('Missing renewal timers');
  205. const source = image.getAttribute('src');
  206. // Both in one batch: React never renders the closed state in between.
  207. act(() => {
  208. close();
  209. renewal();
  210. });
  211. const renewed = screen.getByAltText('Camera stream');
  212. if (artwork) {
  213. // Version 2 keeps the img: changing its src is what closes the old stream.
  214. expect(renewed).toBe(image);
  215. expect(renewed.getAttribute('src')).not.toBe(source);
  216. expect(renewed.getAttribute('src')).toContain('/camera/stream');
  217. } else {
  218. expect(image.getAttribute('src')).toBeNull();
  219. expect(renewed).not.toBe(image);
  220. }
  221. } finally {
  222. view.unmount();
  223. timers.mockRestore();
  224. }
  225. });
  226. it.each(['', '&artwork=2'])('keeps the camera closed while it waits, whatever re-renders the page (%s)', async (artwork) => {
  227. // Signed in: a new stream token (minted after a failed stream) changes the
  228. // URL; the re-render it causes must not reconnect before the renewal.
  229. setStreamToken('first');
  230. const timers = vi.spyOn(globalThis, 'setTimeout');
  231. const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
  232. const view = rtlRender(overlayTree(1, artwork ? `?${artwork.slice(1)}` : '', queryClient));
  233. try {
  234. await screen.findByAltText('Camera stream');
  235. const close = timers.mock.calls.find(([, delay]) => delay === 59_800)?.[0];
  236. if (typeof close !== 'function') throw new Error('Missing close timer');
  237. act(() => close());
  238. setStreamToken('second');
  239. view.rerender(overlayTree(1, artwork ? `?${artwork.slice(1)}` : '', queryClient));
  240. expect(screen.getByAltText('Camera stream').getAttribute('src')).toBeNull();
  241. } finally {
  242. view.unmount();
  243. timers.mockRestore();
  244. setStreamToken(null);
  245. }
  246. });
  247. describe('updated artwork', () => {
  248. it('maps legacy model codes in version 2', async () => {
  249. server.use(http.get('/api/v1/printers/:id', () => HttpResponse.json({ ...mockPrinter, model: 'BL-P001' })));
  250. renderOverlayPage(1, '?artwork=2&show=model');
  251. expect(await screen.findByText('X1C')).toBeInTheDocument();
  252. expect(screen.queryByText('BL-P001')).not.toBeInTheDocument();
  253. });
  254. it.each(['', '?artwork=other', '?artwork=updated'])('retains the original renderer for %s', async (query) => {
  255. const { container } = renderOverlayPage(1, query);
  256. await screen.findByAltText('Bambuddy');
  257. expect(container.querySelector('.updated-overlay')).not.toBeInTheDocument();
  258. expect(screen.getByAltText('Camera stream')).toHaveClass('object-contain');
  259. });
  260. it('uses token data, rotation and both nozzles without inventing missing temperatures', async () => {
  261. server.use(http.get('/api/v1/printers/:id/overlay-status', () => HttpResponse.json({
  262. ...mockStatusPrinting, name: 'Token printer', model: 'O1D', camera_rotation: 90,
  263. time_format: '24h', temperatures: { nozzle: 210, nozzle_target: 220, nozzle_2: 215, bed: 45 },
  264. })));
  265. renderOverlayPage(1, '?artwork=2&token=bblt_test&show=model,nozzle,bed,chamber&size=large');
  266. expect(await screen.findByText('H2D')).toBeInTheDocument();
  267. expect(screen.queryByText('Token printer')).not.toBeInTheDocument();
  268. expect(screen.getByText('Nozzle 2')).toBeInTheDocument();
  269. expect(screen.queryByText('Chamber')).not.toBeInTheDocument();
  270. const camera = screen.getByAltText('Camera stream');
  271. expect(camera).toHaveAttribute('src', expect.stringContaining('token=bblt_test'));
  272. expect(camera).toHaveStyle({ transform: 'translate(-50%, -50%) rotate(90deg)' });
  273. expect(camera.closest('.updated-overlay')).toHaveAttribute('data-size', 'large');
  274. expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
  275. });
  276. it.each([
  277. [90, { width: '640px', height: '360px' }],
  278. [0, null],
  279. ])('sizes a camera turned %i degrees from its slot, not the viewport', async (rotation, expected) => {
  280. // A portrait source: the camera fills a 360 x 640 middle row, so the
  281. // viewport (the old vw/vh fallback) would be the wrong box to swap.
  282. const width = vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(function (this: HTMLElement) {
  283. return this.classList.contains('updated-overlay__camera') ? 360 : 0;
  284. });
  285. const height = vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(function (this: HTMLElement) {
  286. return this.classList.contains('updated-overlay__camera') ? 640 : 0;
  287. });
  288. try {
  289. server.use(http.get('/api/v1/printers/:id', () => HttpResponse.json({ ...mockPrinter, camera_rotation: rotation })));
  290. renderOverlayPage(1, '?artwork=2');
  291. const camera = await screen.findByAltText('Camera stream');
  292. await waitFor(() => expect(camera).toHaveStyle({ transform: `translate(-50%, -50%) rotate(${rotation}deg)` }));
  293. if (expected) {
  294. await waitFor(() => expect(camera).toHaveStyle(expected));
  295. } else {
  296. expect(camera.style.width).toBe('');
  297. expect(camera.style.height).toBe('');
  298. }
  299. } finally {
  300. width.mockRestore();
  301. height.mockRestore();
  302. }
  303. });
  304. it('renders selected fields and accessible progress', async () => {
  305. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json(mockStatusPrinting)));
  306. renderOverlayPage(1, '?artwork=2&show=printer,model,filename,status,progress,layers,eta');
  307. expect(await screen.findByRole('progressbar')).toHaveAttribute('aria-valuenow', '45');
  308. expect(screen.getByText('X1 Carbon')).toBeInTheDocument();
  309. expect(screen.getByText('X1C')).toBeInTheDocument();
  310. expect(screen.getByText('Benchy')).toBeInTheDocument();
  311. expect(screen.getByText('150 / 300')).toBeInTheDocument();
  312. });
  313. it('hides all unselected information, including idle status', async () => {
  314. const { container } = renderOverlayPage(1, '?artwork=2&show=&camera=false');
  315. await screen.findByAltText('Bambuddy');
  316. expect(screen.queryByText('Printer is idle')).not.toBeInTheDocument();
  317. expect(screen.queryByAltText('Camera stream')).not.toBeInTheDocument();
  318. expect(container.querySelector('.updated-overlay__panel')).not.toBeInTheDocument();
  319. });
  320. it.each(['FINISH', 'FAILED'])('shows %s without contradictory idle text', async (state) => {
  321. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json({ ...mockStatusPrinting, state })));
  322. renderOverlayPage(1, '?artwork=2&show=status,progress');
  323. expect(await screen.findByText(state === 'FINISH' ? 'Finished' : 'Failed')).toBeInTheDocument();
  324. expect(screen.queryByText('Printer is idle')).not.toBeInTheDocument();
  325. expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
  326. });
  327. it('hides stale progress when disconnected', async () => {
  328. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json({ ...mockStatusPrinting, connected: false, temperatures: { nozzle: 210 } })));
  329. renderOverlayPage(1, '?artwork=2&show=status,progress,layers,eta');
  330. expect(await screen.findByText('Printer offline')).toBeInTheDocument();
  331. expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
  332. });
  333. });
  334. describe('rendering', () => {
  335. it('renders overlay page for printer', async () => {
  336. renderOverlayPage(1);
  337. await waitFor(() => {
  338. expect(screen.getByText('Idle')).toBeInTheDocument();
  339. });
  340. });
  341. it('shows Bambuddy logo', async () => {
  342. renderOverlayPage(1);
  343. await waitFor(() => {
  344. expect(screen.getByAltText('Bambuddy')).toBeInTheDocument();
  345. });
  346. });
  347. it('logo links to GitHub', async () => {
  348. renderOverlayPage(1);
  349. await waitFor(() => {
  350. const logo = screen.getByAltText('Bambuddy');
  351. const link = logo.closest('a');
  352. expect(link).toHaveAttribute('href', 'https://github.com/maziggy/bambuddy');
  353. });
  354. });
  355. });
  356. describe('printer model', () => {
  357. it.each(['', '?show=printer', '?show='])('hides the model unless selected (%s)', async (query) => {
  358. renderOverlayPage(1, query);
  359. await screen.findByAltText('Bambuddy');
  360. expect(screen.queryByText(/X1C/)).not.toBeInTheDocument();
  361. });
  362. it.each([
  363. ['?show=model', 'X1C'],
  364. ['?show=printer,model', 'X1 Carbon · X1C'],
  365. ])('shows the selected printer identity (%s)', async (query, identity) => {
  366. renderOverlayPage(1, query);
  367. expect(await screen.findByText(identity)).toBeInTheDocument();
  368. if (query === '?show=model') expect(screen.queryByText(/X1 Carbon/)).not.toBeInTheDocument();
  369. });
  370. it.each([
  371. ['BL-P001', 'X1C'],
  372. ['O1D', 'H2D'],
  373. ['H2D', 'H2D'],
  374. ['Future printer', 'Future printer'],
  375. ])('displays the saved model %s as %s', async (model, displayName) => {
  376. server.use(http.get('/api/v1/printers/:id', () => HttpResponse.json({ ...mockPrinter, model })));
  377. renderOverlayPage(1, '?show=model');
  378. expect(await screen.findByText(displayName)).toBeInTheDocument();
  379. });
  380. it.each([null, ''])('omits a missing model without adding a separator (%s)', async (model) => {
  381. server.use(http.get('/api/v1/printers/:id', () => HttpResponse.json({ ...mockPrinter, model })));
  382. renderOverlayPage(1, '?show=printer,model');
  383. expect(await screen.findByText('X1 Carbon')).toBeInTheDocument();
  384. expect(screen.queryByText(/·/)).not.toBeInTheDocument();
  385. });
  386. it.each([['H2D', 'H2D'], ['BL-P001', 'X1C'], ['O1D', 'H2D'], [null, ''], ['', '']] as const)('reads the model %s from the OBS token feed without requesting printer details', async (model, displayName) => {
  387. let printerHit = false;
  388. server.use(
  389. http.get('/api/v1/printers/:id/overlay-status', () => HttpResponse.json({
  390. ...mockStatusIdle, name: 'Workshop', model, camera_rotation: 0,
  391. gcode_file: null, temperatures: {}, time_format: 'system',
  392. })),
  393. http.get('/api/v1/printers/:id', () => {
  394. printerHit = true;
  395. return new HttpResponse(null, { status: 401 });
  396. }),
  397. );
  398. renderOverlayPage(1, '?token=obs-tok&show=printer,model');
  399. expect(await screen.findByText(displayName ? `Workshop · ${displayName}` : 'Workshop')).toBeInTheDocument();
  400. expect(printerHit).toBe(false);
  401. if (!model) expect(screen.queryByText(/·/)).not.toBeInTheDocument();
  402. });
  403. });
  404. describe('printing state', () => {
  405. beforeEach(() => {
  406. server.use(
  407. http.get('/api/v1/printers/:id/status', () => {
  408. return HttpResponse.json(mockStatusPrinting);
  409. })
  410. );
  411. });
  412. it('shows filename when printing', async () => {
  413. renderOverlayPage(1);
  414. await waitFor(() => {
  415. expect(screen.getByText('Benchy')).toBeInTheDocument();
  416. });
  417. });
  418. it('shows progress percentage', async () => {
  419. renderOverlayPage(1);
  420. await waitFor(() => {
  421. expect(screen.getByText('45%')).toBeInTheDocument();
  422. });
  423. });
  424. it('shows layer count', async () => {
  425. renderOverlayPage(1);
  426. await waitFor(() => {
  427. expect(screen.getByText('150')).toBeInTheDocument();
  428. expect(screen.getByText('300')).toBeInTheDocument();
  429. });
  430. });
  431. it('shows status text', async () => {
  432. renderOverlayPage(1);
  433. await waitFor(() => {
  434. expect(screen.getByText('Printing')).toBeInTheDocument();
  435. });
  436. });
  437. });
  438. describe('invalid printer', () => {
  439. it('shows invalid printer message for ID 0', async () => {
  440. renderOverlayPage(0);
  441. await waitFor(() => {
  442. expect(screen.getByText('Invalid printer ID')).toBeInTheDocument();
  443. });
  444. });
  445. });
  446. describe('query parameters', () => {
  447. it('respects size parameter', async () => {
  448. renderOverlayPage(1, '?size=large');
  449. await waitFor(() => {
  450. // Just verify it renders without error
  451. expect(screen.getByAltText('Bambuddy')).toBeInTheDocument();
  452. });
  453. });
  454. it('respects show parameter to hide elements', async () => {
  455. server.use(
  456. http.get('/api/v1/printers/:id/status', () => {
  457. return HttpResponse.json(mockStatusPrinting);
  458. })
  459. );
  460. renderOverlayPage(1, '?show=progress');
  461. await waitFor(() => {
  462. // Progress should be visible
  463. expect(screen.getByText('45%')).toBeInTheDocument();
  464. // Status text should be hidden when not in show list
  465. expect(screen.queryByText('Printing')).not.toBeInTheDocument();
  466. });
  467. });
  468. });
  469. describe('FPS configuration', () => {
  470. it('uses default FPS of 15 when not specified', async () => {
  471. renderOverlayPage(1);
  472. await waitFor(() => {
  473. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  474. expect(img.src).toContain('fps=15');
  475. });
  476. });
  477. it('uses custom FPS when specified in query params', async () => {
  478. renderOverlayPage(1, '?fps=30');
  479. await waitFor(() => {
  480. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  481. expect(img.src).toContain('fps=30');
  482. });
  483. });
  484. it('clamps FPS to maximum of 30', async () => {
  485. renderOverlayPage(1, '?fps=60');
  486. await waitFor(() => {
  487. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  488. expect(img.src).toContain('fps=30');
  489. });
  490. });
  491. it('clamps FPS to minimum of 1', async () => {
  492. renderOverlayPage(1, '?fps=0');
  493. await waitFor(() => {
  494. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  495. expect(img.src).toContain('fps=1');
  496. });
  497. });
  498. it('handles invalid FPS value gracefully', async () => {
  499. renderOverlayPage(1, '?fps=invalid');
  500. await waitFor(() => {
  501. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  502. // Should fall back to default of 15
  503. expect(img.src).toContain('fps=15');
  504. });
  505. });
  506. });
  507. describe('camera toggle (status-only mode)', () => {
  508. it('shows camera by default', async () => {
  509. renderOverlayPage(1);
  510. await waitFor(() => {
  511. expect(screen.getByAltText('Camera stream')).toBeInTheDocument();
  512. });
  513. });
  514. it('hides camera when camera=false', async () => {
  515. renderOverlayPage(1, '?camera=false');
  516. await waitFor(() => {
  517. // Status should still be visible
  518. expect(screen.getByText('Idle')).toBeInTheDocument();
  519. });
  520. // Camera should not be rendered
  521. expect(screen.queryByAltText('Camera stream')).not.toBeInTheDocument();
  522. });
  523. it('hides camera when camera=0', async () => {
  524. renderOverlayPage(1, '?camera=0');
  525. await waitFor(() => {
  526. expect(screen.getByText('Idle')).toBeInTheDocument();
  527. });
  528. expect(screen.queryByAltText('Camera stream')).not.toBeInTheDocument();
  529. });
  530. it('shows camera when camera=true', async () => {
  531. renderOverlayPage(1, '?camera=true');
  532. await waitFor(() => {
  533. expect(screen.getByAltText('Camera stream')).toBeInTheDocument();
  534. });
  535. });
  536. it('shows camera when camera=1', async () => {
  537. renderOverlayPage(1, '?camera=1');
  538. await waitFor(() => {
  539. expect(screen.getByAltText('Camera stream')).toBeInTheDocument();
  540. });
  541. });
  542. });
  543. describe('combined parameters', () => {
  544. it('supports fps and camera together', async () => {
  545. renderOverlayPage(1, '?fps=25&camera=true');
  546. await waitFor(() => {
  547. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  548. expect(img.src).toContain('fps=25');
  549. });
  550. });
  551. it('supports status-only with custom size', async () => {
  552. renderOverlayPage(1, '?camera=false&size=large');
  553. await waitFor(() => {
  554. expect(screen.getByText('Idle')).toBeInTheDocument();
  555. });
  556. expect(screen.queryByAltText('Camera stream')).not.toBeInTheDocument();
  557. });
  558. it('supports show parameter with fps', async () => {
  559. server.use(
  560. http.get('/api/v1/printers/:id/status', () => {
  561. return HttpResponse.json(mockStatusPrinting);
  562. })
  563. );
  564. renderOverlayPage(1, '?fps=20&show=progress');
  565. await waitFor(() => {
  566. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  567. expect(img.src).toContain('fps=20');
  568. expect(screen.getByText('45%')).toBeInTheDocument();
  569. });
  570. });
  571. });
  572. describe('offline state', () => {
  573. beforeEach(() => {
  574. server.use(
  575. http.get('/api/v1/printers/:id/status', () => {
  576. return HttpResponse.json({
  577. ...mockStatusIdle,
  578. connected: false,
  579. });
  580. })
  581. );
  582. });
  583. it('shows offline message when printer disconnected', async () => {
  584. renderOverlayPage(1);
  585. await waitFor(() => {
  586. expect(screen.getByText('Printer offline')).toBeInTheDocument();
  587. });
  588. });
  589. });
  590. describe('kiosk token mode (#2613)', () => {
  591. const mockOverlayPrinting = {
  592. id: 1,
  593. name: 'X1 Carbon',
  594. camera_rotation: 0,
  595. connected: true,
  596. state: 'RUNNING',
  597. current_print: 'KioskBenchy.gcode.3mf',
  598. gcode_file: 'plate_1.gcode',
  599. progress: 67,
  600. remaining_time: 40,
  601. layer_num: 10,
  602. total_layers: 20,
  603. stg_cur_name: null,
  604. time_format: 'system',
  605. };
  606. it('reads the token-authed overlay-status feed and carries the token to the camera', async () => {
  607. let overlayHit = false;
  608. server.use(
  609. http.get('/api/v1/printers/:id/overlay-status', () => {
  610. overlayHit = true;
  611. return HttpResponse.json(mockOverlayPrinting);
  612. })
  613. );
  614. renderOverlayPage(1, '?token=obs-tok');
  615. await waitFor(() => {
  616. expect(screen.getByText('KioskBenchy')).toBeInTheDocument();
  617. });
  618. expect(overlayHit).toBe(true);
  619. expect(screen.getByText('67%')).toBeInTheDocument();
  620. // The camera <img> must carry the same kiosk token — a fresh OBS browser
  621. // has no session to mint a camera stream token from.
  622. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  623. expect(img.src).toContain('token=obs-tok');
  624. });
  625. it('does not touch the JWT-only status endpoint or a WebSocket in kiosk mode', async () => {
  626. let statusHit = false;
  627. server.use(
  628. http.get('/api/v1/printers/:id/overlay-status', () => HttpResponse.json(mockOverlayPrinting)),
  629. http.get('/api/v1/printers/:id/status', () => {
  630. statusHit = true;
  631. return HttpResponse.json(mockStatusIdle);
  632. })
  633. );
  634. renderOverlayPage(1, '?token=obs-tok');
  635. await waitFor(() => {
  636. expect(screen.getByText('KioskBenchy')).toBeInTheDocument();
  637. });
  638. // The logged-in status query is disabled when a token is present, so an
  639. // unauthenticated OBS browser never fires a doomed 401 (or opens a socket).
  640. expect(statusHit).toBe(false);
  641. expect(WebSocket).not.toHaveBeenCalled();
  642. });
  643. });
  644. describe('temperatures (#1422)', () => {
  645. const withTemps = {
  646. ...mockStatusPrinting,
  647. temperatures: {
  648. nozzle: 219.6,
  649. nozzle_target: 220,
  650. bed: 60,
  651. bed_target: 60,
  652. chamber: 38.4,
  653. },
  654. };
  655. beforeEach(() => {
  656. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json(withTemps)));
  657. });
  658. it('draws no temperatures unless the URL asks for them', async () => {
  659. renderOverlayPage(1);
  660. await waitFor(() => {
  661. expect(screen.getByText('45%')).toBeInTheDocument();
  662. });
  663. // Default ?show= is unchanged by #1422, so overlays already running in an
  664. // OBS scene look identical after the upgrade.
  665. expect(screen.queryByText('Nozzle')).not.toBeInTheDocument();
  666. expect(screen.queryByText('Bed')).not.toBeInTheDocument();
  667. });
  668. it('draws only the readings named in ?show=', async () => {
  669. renderOverlayPage(1, '?show=progress,nozzle');
  670. await waitFor(() => {
  671. expect(screen.getByText('Nozzle')).toBeInTheDocument();
  672. });
  673. expect(screen.queryByText('Bed')).not.toBeInTheDocument();
  674. expect(screen.queryByText('Chamber')).not.toBeInTheDocument();
  675. });
  676. it('rounds the reading and hides a target it has already reached', async () => {
  677. renderOverlayPage(1, '?show=nozzle,bed');
  678. await waitFor(() => {
  679. expect(screen.getByText('220°C')).toBeInTheDocument();
  680. });
  681. // Nozzle is 219.6 against a target of 220: both round to 220, so the
  682. // "/ 220°C" half is dropped rather than reading "220 / 220°C" all print.
  683. expect(screen.queryByText('/')).not.toBeInTheDocument();
  684. expect(screen.getByText('60°C')).toBeInTheDocument();
  685. });
  686. it('shows the target while the heater is still climbing', async () => {
  687. server.use(
  688. http.get('/api/v1/printers/:id/status', () =>
  689. HttpResponse.json({ ...withTemps, temperatures: { nozzle: 140, nozzle_target: 220 } }),
  690. ),
  691. );
  692. renderOverlayPage(1, '?show=nozzle');
  693. await waitFor(() => {
  694. expect(screen.getByText('140°C')).toBeInTheDocument();
  695. });
  696. expect(screen.getByText('220°C')).toBeInTheDocument();
  697. });
  698. it('skips a reading the printer does not report', async () => {
  699. server.use(
  700. http.get('/api/v1/printers/:id/status', () =>
  701. // A P1S: the backend drops chamber for models without a real sensor,
  702. // so asking for it in ?show= must not produce an empty row.
  703. HttpResponse.json({ ...withTemps, temperatures: { nozzle: 200, bed: 55 } }),
  704. ),
  705. );
  706. renderOverlayPage(1, '?show=nozzle,bed,chamber');
  707. await waitFor(() => {
  708. expect(screen.getByText('Nozzle')).toBeInTheDocument();
  709. });
  710. expect(screen.queryByText('Chamber')).not.toBeInTheDocument();
  711. });
  712. it('draws both nozzles on a dual-nozzle printer', async () => {
  713. server.use(
  714. http.get('/api/v1/printers/:id/status', () =>
  715. HttpResponse.json({
  716. ...withTemps,
  717. temperatures: { nozzle: 220, nozzle_2: 250, nozzle_2_target: 250 },
  718. }),
  719. ),
  720. );
  721. renderOverlayPage(1, '?show=nozzle');
  722. await waitFor(() => {
  723. expect(screen.getByText('Nozzle')).toBeInTheDocument();
  724. });
  725. expect(screen.getByText('Nozzle 2')).toBeInTheDocument();
  726. expect(screen.getByText('250°C')).toBeInTheDocument();
  727. });
  728. it('draws temperatures while the printer is idle', async () => {
  729. server.use(
  730. http.get('/api/v1/printers/:id/status', () =>
  731. HttpResponse.json({ ...mockStatusIdle, temperatures: { bed: 45, bed_target: 60 } }),
  732. ),
  733. );
  734. renderOverlayPage(1, '?show=bed');
  735. await screen.findByText('45°C');
  736. // A preheating printer is exactly when the readings are worth watching,
  737. // so they are not gated behind a running print.
  738. expect(screen.getByText('45°C')).toBeInTheDocument();
  739. expect(screen.getByText('60°C')).toBeInTheDocument();
  740. });
  741. it('reads temperatures from the token-authed feed in kiosk mode', async () => {
  742. server.use(
  743. http.get('/api/v1/printers/:id/overlay-status', () =>
  744. HttpResponse.json({
  745. id: 1,
  746. name: 'X1 Carbon',
  747. camera_rotation: 0,
  748. connected: true,
  749. state: 'RUNNING',
  750. current_print: 'KioskBenchy.gcode.3mf',
  751. gcode_file: 'plate_1.gcode',
  752. progress: 67,
  753. remaining_time: 40,
  754. layer_num: 10,
  755. total_layers: 20,
  756. stg_cur_name: null,
  757. temperatures: { chamber: 38, chamber_target: 40 },
  758. time_format: 'system',
  759. }),
  760. ),
  761. );
  762. renderOverlayPage(1, '?token=obs-tok&show=chamber');
  763. await waitFor(() => {
  764. expect(screen.getByText('Chamber')).toBeInTheDocument();
  765. });
  766. expect(screen.getByText('38°C')).toBeInTheDocument();
  767. });
  768. });
  769. });