StreamOverlayPage.test.tsx 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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.each([
  305. [90, { width: '720px', height: '1280px' }],
  306. [0, null],
  307. ])('fits a classic overlay camera turned %i degrees into the window (#3362)', async (rotation, expected) => {
  308. const width = vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(function (this: HTMLElement) {
  309. return this.classList.contains('classic-overlay') ? 1280 : 0;
  310. });
  311. const height = vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(function (this: HTMLElement) {
  312. return this.classList.contains('classic-overlay') ? 720 : 0;
  313. });
  314. try {
  315. server.use(http.get('/api/v1/printers/:id', () => HttpResponse.json({ ...mockPrinter, camera_rotation: rotation })));
  316. renderOverlayPage(1, '');
  317. const camera = await screen.findByAltText('Camera stream');
  318. if (expected) {
  319. await waitFor(() => expect(camera).toHaveStyle(expected));
  320. expect(camera.style.transform).toBe(`translate(-50%, -50%) rotate(${rotation}deg)`);
  321. } else {
  322. await waitFor(() => expect(camera.style.transform).toBe(''));
  323. expect(camera.style.width).toBe('');
  324. }
  325. } finally {
  326. width.mockRestore();
  327. height.mockRestore();
  328. }
  329. });
  330. it('renders selected fields and accessible progress', async () => {
  331. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json(mockStatusPrinting)));
  332. renderOverlayPage(1, '?artwork=2&show=printer,model,filename,status,progress,layers,eta');
  333. expect(await screen.findByRole('progressbar')).toHaveAttribute('aria-valuenow', '45');
  334. expect(screen.getByText('X1 Carbon')).toBeInTheDocument();
  335. expect(screen.getByText('X1C')).toBeInTheDocument();
  336. expect(screen.getByText('Benchy')).toBeInTheDocument();
  337. expect(screen.getByText('150 / 300')).toBeInTheDocument();
  338. });
  339. it('hides all unselected information, including idle status', async () => {
  340. const { container } = renderOverlayPage(1, '?artwork=2&show=&camera=false');
  341. await screen.findByAltText('Bambuddy');
  342. expect(screen.queryByText('Printer is idle')).not.toBeInTheDocument();
  343. expect(screen.queryByAltText('Camera stream')).not.toBeInTheDocument();
  344. expect(container.querySelector('.updated-overlay__panel')).not.toBeInTheDocument();
  345. });
  346. it.each(['FINISH', 'FAILED'])('shows %s without contradictory idle text', async (state) => {
  347. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json({ ...mockStatusPrinting, state })));
  348. renderOverlayPage(1, '?artwork=2&show=status,progress');
  349. expect(await screen.findByText(state === 'FINISH' ? 'Finished' : 'Failed')).toBeInTheDocument();
  350. expect(screen.queryByText('Printer is idle')).not.toBeInTheDocument();
  351. expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
  352. });
  353. it('hides stale progress when disconnected', async () => {
  354. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json({ ...mockStatusPrinting, connected: false, temperatures: { nozzle: 210 } })));
  355. renderOverlayPage(1, '?artwork=2&show=status,progress,layers,eta');
  356. expect(await screen.findByText('Printer offline')).toBeInTheDocument();
  357. expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
  358. });
  359. });
  360. describe('rendering', () => {
  361. it('renders overlay page for printer', async () => {
  362. renderOverlayPage(1);
  363. await waitFor(() => {
  364. expect(screen.getByText('Idle')).toBeInTheDocument();
  365. });
  366. });
  367. it('shows Bambuddy logo', async () => {
  368. renderOverlayPage(1);
  369. await waitFor(() => {
  370. expect(screen.getByAltText('Bambuddy')).toBeInTheDocument();
  371. });
  372. });
  373. it('logo links to GitHub', async () => {
  374. renderOverlayPage(1);
  375. await waitFor(() => {
  376. const logo = screen.getByAltText('Bambuddy');
  377. const link = logo.closest('a');
  378. expect(link).toHaveAttribute('href', 'https://github.com/maziggy/bambuddy');
  379. });
  380. });
  381. });
  382. describe('printer model', () => {
  383. it.each(['', '?show=printer', '?show='])('hides the model unless selected (%s)', async (query) => {
  384. renderOverlayPage(1, query);
  385. await screen.findByAltText('Bambuddy');
  386. expect(screen.queryByText(/X1C/)).not.toBeInTheDocument();
  387. });
  388. it.each([
  389. ['?show=model', 'X1C'],
  390. ['?show=printer,model', 'X1 Carbon · X1C'],
  391. ])('shows the selected printer identity (%s)', async (query, identity) => {
  392. renderOverlayPage(1, query);
  393. expect(await screen.findByText(identity)).toBeInTheDocument();
  394. if (query === '?show=model') expect(screen.queryByText(/X1 Carbon/)).not.toBeInTheDocument();
  395. });
  396. it.each([
  397. ['BL-P001', 'X1C'],
  398. ['O1D', 'H2D'],
  399. ['H2D', 'H2D'],
  400. ['Future printer', 'Future printer'],
  401. ])('displays the saved model %s as %s', async (model, displayName) => {
  402. server.use(http.get('/api/v1/printers/:id', () => HttpResponse.json({ ...mockPrinter, model })));
  403. renderOverlayPage(1, '?show=model');
  404. expect(await screen.findByText(displayName)).toBeInTheDocument();
  405. });
  406. it.each([null, ''])('omits a missing model without adding a separator (%s)', async (model) => {
  407. server.use(http.get('/api/v1/printers/:id', () => HttpResponse.json({ ...mockPrinter, model })));
  408. renderOverlayPage(1, '?show=printer,model');
  409. expect(await screen.findByText('X1 Carbon')).toBeInTheDocument();
  410. expect(screen.queryByText(/·/)).not.toBeInTheDocument();
  411. });
  412. 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) => {
  413. let printerHit = false;
  414. server.use(
  415. http.get('/api/v1/printers/:id/overlay-status', () => HttpResponse.json({
  416. ...mockStatusIdle, name: 'Workshop', model, camera_rotation: 0,
  417. gcode_file: null, temperatures: {}, time_format: 'system',
  418. })),
  419. http.get('/api/v1/printers/:id', () => {
  420. printerHit = true;
  421. return new HttpResponse(null, { status: 401 });
  422. }),
  423. );
  424. renderOverlayPage(1, '?token=obs-tok&show=printer,model');
  425. expect(await screen.findByText(displayName ? `Workshop · ${displayName}` : 'Workshop')).toBeInTheDocument();
  426. expect(printerHit).toBe(false);
  427. if (!model) expect(screen.queryByText(/·/)).not.toBeInTheDocument();
  428. });
  429. });
  430. describe('printing state', () => {
  431. beforeEach(() => {
  432. server.use(
  433. http.get('/api/v1/printers/:id/status', () => {
  434. return HttpResponse.json(mockStatusPrinting);
  435. })
  436. );
  437. });
  438. it('shows filename when printing', async () => {
  439. renderOverlayPage(1);
  440. await waitFor(() => {
  441. expect(screen.getByText('Benchy')).toBeInTheDocument();
  442. });
  443. });
  444. it('shows progress percentage', async () => {
  445. renderOverlayPage(1);
  446. await waitFor(() => {
  447. expect(screen.getByText('45%')).toBeInTheDocument();
  448. });
  449. });
  450. it('shows layer count', async () => {
  451. renderOverlayPage(1);
  452. await waitFor(() => {
  453. expect(screen.getByText('150')).toBeInTheDocument();
  454. expect(screen.getByText('300')).toBeInTheDocument();
  455. });
  456. });
  457. it('shows status text', async () => {
  458. renderOverlayPage(1);
  459. await waitFor(() => {
  460. expect(screen.getByText('Printing')).toBeInTheDocument();
  461. });
  462. });
  463. });
  464. describe('live updates', () => {
  465. // ws-1: the backend sends a status update as `data`; the overlay read
  466. // `data.status`, which is undefined, so every websocket update was
  467. // dropped and only the 2 s poll moved it.
  468. it('applies a websocket status update, keeping fields it does not carry', async () => {
  469. const sockets: Array<{ onmessage: ((e: { data: string }) => void) | null }> = [];
  470. vi.stubGlobal(
  471. 'WebSocket',
  472. vi.fn().mockImplementation(function (this: { close: () => void; onmessage: null; onerror: null }) {
  473. this.close = vi.fn();
  474. this.onmessage = null;
  475. this.onerror = null;
  476. sockets.push(this);
  477. }),
  478. );
  479. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json(mockStatusPrinting)));
  480. renderOverlayPage(1);
  481. expect(await screen.findByText('45%')).toBeInTheDocument();
  482. await waitFor(() => expect(sockets[0]?.onmessage).toBeTypeOf('function'));
  483. act(() => {
  484. sockets[0].onmessage!({ data: JSON.stringify({ type: 'printer_status', printer_id: 1, data: { progress: 46 } }) });
  485. });
  486. expect(await screen.findByText('46%')).toBeInTheDocument();
  487. expect(screen.getByText('Benchy')).toBeInTheDocument();
  488. });
  489. });
  490. describe('invalid printer', () => {
  491. it('shows invalid printer message for ID 0', async () => {
  492. renderOverlayPage(0);
  493. await waitFor(() => {
  494. expect(screen.getByText('Invalid printer ID')).toBeInTheDocument();
  495. });
  496. });
  497. });
  498. describe('query parameters', () => {
  499. it('respects size parameter', async () => {
  500. renderOverlayPage(1, '?size=large');
  501. await waitFor(() => {
  502. // Just verify it renders without error
  503. expect(screen.getByAltText('Bambuddy')).toBeInTheDocument();
  504. });
  505. });
  506. it('respects show parameter to hide elements', async () => {
  507. server.use(
  508. http.get('/api/v1/printers/:id/status', () => {
  509. return HttpResponse.json(mockStatusPrinting);
  510. })
  511. );
  512. renderOverlayPage(1, '?show=progress');
  513. await waitFor(() => {
  514. // Progress should be visible
  515. expect(screen.getByText('45%')).toBeInTheDocument();
  516. // Status text should be hidden when not in show list
  517. expect(screen.queryByText('Printing')).not.toBeInTheDocument();
  518. });
  519. });
  520. });
  521. describe('FPS configuration', () => {
  522. it('uses default FPS of 15 when not specified', async () => {
  523. renderOverlayPage(1);
  524. await waitFor(() => {
  525. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  526. expect(img.src).toContain('fps=15');
  527. });
  528. });
  529. it('uses custom FPS when specified in query params', async () => {
  530. renderOverlayPage(1, '?fps=30');
  531. await waitFor(() => {
  532. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  533. expect(img.src).toContain('fps=30');
  534. });
  535. });
  536. it('clamps FPS to maximum of 30', async () => {
  537. renderOverlayPage(1, '?fps=60');
  538. await waitFor(() => {
  539. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  540. expect(img.src).toContain('fps=30');
  541. });
  542. });
  543. it('clamps FPS to minimum of 1', async () => {
  544. renderOverlayPage(1, '?fps=0');
  545. await waitFor(() => {
  546. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  547. expect(img.src).toContain('fps=1');
  548. });
  549. });
  550. it('handles invalid FPS value gracefully', async () => {
  551. renderOverlayPage(1, '?fps=invalid');
  552. await waitFor(() => {
  553. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  554. // Should fall back to default of 15
  555. expect(img.src).toContain('fps=15');
  556. });
  557. });
  558. });
  559. describe('camera toggle (status-only mode)', () => {
  560. it('shows camera by default', async () => {
  561. renderOverlayPage(1);
  562. await waitFor(() => {
  563. expect(screen.getByAltText('Camera stream')).toBeInTheDocument();
  564. });
  565. });
  566. it('hides camera when camera=false', async () => {
  567. renderOverlayPage(1, '?camera=false');
  568. await waitFor(() => {
  569. // Status should still be visible
  570. expect(screen.getByText('Idle')).toBeInTheDocument();
  571. });
  572. // Camera should not be rendered
  573. expect(screen.queryByAltText('Camera stream')).not.toBeInTheDocument();
  574. });
  575. it('hides camera when camera=0', async () => {
  576. renderOverlayPage(1, '?camera=0');
  577. await waitFor(() => {
  578. expect(screen.getByText('Idle')).toBeInTheDocument();
  579. });
  580. expect(screen.queryByAltText('Camera stream')).not.toBeInTheDocument();
  581. });
  582. it('shows camera when camera=true', async () => {
  583. renderOverlayPage(1, '?camera=true');
  584. await waitFor(() => {
  585. expect(screen.getByAltText('Camera stream')).toBeInTheDocument();
  586. });
  587. });
  588. it('shows camera when camera=1', async () => {
  589. renderOverlayPage(1, '?camera=1');
  590. await waitFor(() => {
  591. expect(screen.getByAltText('Camera stream')).toBeInTheDocument();
  592. });
  593. });
  594. });
  595. describe('combined parameters', () => {
  596. it('supports fps and camera together', async () => {
  597. renderOverlayPage(1, '?fps=25&camera=true');
  598. await waitFor(() => {
  599. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  600. expect(img.src).toContain('fps=25');
  601. });
  602. });
  603. it('supports status-only with custom size', async () => {
  604. renderOverlayPage(1, '?camera=false&size=large');
  605. await waitFor(() => {
  606. expect(screen.getByText('Idle')).toBeInTheDocument();
  607. });
  608. expect(screen.queryByAltText('Camera stream')).not.toBeInTheDocument();
  609. });
  610. it('supports show parameter with fps', async () => {
  611. server.use(
  612. http.get('/api/v1/printers/:id/status', () => {
  613. return HttpResponse.json(mockStatusPrinting);
  614. })
  615. );
  616. renderOverlayPage(1, '?fps=20&show=progress');
  617. await waitFor(() => {
  618. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  619. expect(img.src).toContain('fps=20');
  620. expect(screen.getByText('45%')).toBeInTheDocument();
  621. });
  622. });
  623. });
  624. describe('offline state', () => {
  625. beforeEach(() => {
  626. server.use(
  627. http.get('/api/v1/printers/:id/status', () => {
  628. return HttpResponse.json({
  629. ...mockStatusIdle,
  630. connected: false,
  631. });
  632. })
  633. );
  634. });
  635. it('shows offline message when printer disconnected', async () => {
  636. renderOverlayPage(1);
  637. await waitFor(() => {
  638. expect(screen.getByText('Printer offline')).toBeInTheDocument();
  639. });
  640. });
  641. });
  642. describe('kiosk token mode (#2613)', () => {
  643. const mockOverlayPrinting = {
  644. id: 1,
  645. name: 'X1 Carbon',
  646. camera_rotation: 0,
  647. connected: true,
  648. state: 'RUNNING',
  649. current_print: 'KioskBenchy.gcode.3mf',
  650. gcode_file: 'plate_1.gcode',
  651. progress: 67,
  652. remaining_time: 40,
  653. layer_num: 10,
  654. total_layers: 20,
  655. stg_cur_name: null,
  656. time_format: 'system',
  657. };
  658. it('reads the token-authed overlay-status feed and carries the token to the camera', async () => {
  659. let overlayHit = false;
  660. server.use(
  661. http.get('/api/v1/printers/:id/overlay-status', () => {
  662. overlayHit = true;
  663. return HttpResponse.json(mockOverlayPrinting);
  664. })
  665. );
  666. renderOverlayPage(1, '?token=obs-tok');
  667. await waitFor(() => {
  668. expect(screen.getByText('KioskBenchy')).toBeInTheDocument();
  669. });
  670. expect(overlayHit).toBe(true);
  671. expect(screen.getByText('67%')).toBeInTheDocument();
  672. // The camera <img> must carry the same kiosk token — a fresh OBS browser
  673. // has no session to mint a camera stream token from.
  674. const img = screen.getByAltText('Camera stream') as HTMLImageElement;
  675. expect(img.src).toContain('token=obs-tok');
  676. });
  677. it('does not touch the JWT-only status endpoint or a WebSocket in kiosk mode', async () => {
  678. let statusHit = false;
  679. server.use(
  680. http.get('/api/v1/printers/:id/overlay-status', () => HttpResponse.json(mockOverlayPrinting)),
  681. http.get('/api/v1/printers/:id/status', () => {
  682. statusHit = true;
  683. return HttpResponse.json(mockStatusIdle);
  684. })
  685. );
  686. renderOverlayPage(1, '?token=obs-tok');
  687. await waitFor(() => {
  688. expect(screen.getByText('KioskBenchy')).toBeInTheDocument();
  689. });
  690. // The logged-in status query is disabled when a token is present, so an
  691. // unauthenticated OBS browser never fires a doomed 401 (or opens a socket).
  692. expect(statusHit).toBe(false);
  693. expect(WebSocket).not.toHaveBeenCalled();
  694. });
  695. });
  696. describe('temperatures (#1422)', () => {
  697. const withTemps = {
  698. ...mockStatusPrinting,
  699. temperatures: {
  700. nozzle: 219.6,
  701. nozzle_target: 220,
  702. bed: 60,
  703. bed_target: 60,
  704. chamber: 38.4,
  705. },
  706. };
  707. beforeEach(() => {
  708. server.use(http.get('/api/v1/printers/:id/status', () => HttpResponse.json(withTemps)));
  709. });
  710. it('draws no temperatures unless the URL asks for them', async () => {
  711. renderOverlayPage(1);
  712. await waitFor(() => {
  713. expect(screen.getByText('45%')).toBeInTheDocument();
  714. });
  715. // Default ?show= is unchanged by #1422, so overlays already running in an
  716. // OBS scene look identical after the upgrade.
  717. expect(screen.queryByText('Nozzle')).not.toBeInTheDocument();
  718. expect(screen.queryByText('Bed')).not.toBeInTheDocument();
  719. });
  720. it('draws only the readings named in ?show=', async () => {
  721. renderOverlayPage(1, '?show=progress,nozzle');
  722. await waitFor(() => {
  723. expect(screen.getByText('Nozzle')).toBeInTheDocument();
  724. });
  725. expect(screen.queryByText('Bed')).not.toBeInTheDocument();
  726. expect(screen.queryByText('Chamber')).not.toBeInTheDocument();
  727. });
  728. it('rounds the reading and hides a target it has already reached', async () => {
  729. renderOverlayPage(1, '?show=nozzle,bed');
  730. await waitFor(() => {
  731. expect(screen.getByText('220°C')).toBeInTheDocument();
  732. });
  733. // Nozzle is 219.6 against a target of 220: both round to 220, so the
  734. // "/ 220°C" half is dropped rather than reading "220 / 220°C" all print.
  735. expect(screen.queryByText('/')).not.toBeInTheDocument();
  736. expect(screen.getByText('60°C')).toBeInTheDocument();
  737. });
  738. it('shows the target while the heater is still climbing', async () => {
  739. server.use(
  740. http.get('/api/v1/printers/:id/status', () =>
  741. HttpResponse.json({ ...withTemps, temperatures: { nozzle: 140, nozzle_target: 220 } }),
  742. ),
  743. );
  744. renderOverlayPage(1, '?show=nozzle');
  745. await waitFor(() => {
  746. expect(screen.getByText('140°C')).toBeInTheDocument();
  747. });
  748. expect(screen.getByText('220°C')).toBeInTheDocument();
  749. });
  750. it('skips a reading the printer does not report', async () => {
  751. server.use(
  752. http.get('/api/v1/printers/:id/status', () =>
  753. // A P1S: the backend drops chamber for models without a real sensor,
  754. // so asking for it in ?show= must not produce an empty row.
  755. HttpResponse.json({ ...withTemps, temperatures: { nozzle: 200, bed: 55 } }),
  756. ),
  757. );
  758. renderOverlayPage(1, '?show=nozzle,bed,chamber');
  759. await waitFor(() => {
  760. expect(screen.getByText('Nozzle')).toBeInTheDocument();
  761. });
  762. expect(screen.queryByText('Chamber')).not.toBeInTheDocument();
  763. });
  764. it('draws both nozzles on a dual-nozzle printer', async () => {
  765. server.use(
  766. http.get('/api/v1/printers/:id/status', () =>
  767. HttpResponse.json({
  768. ...withTemps,
  769. temperatures: { nozzle: 220, nozzle_2: 250, nozzle_2_target: 250 },
  770. }),
  771. ),
  772. );
  773. renderOverlayPage(1, '?show=nozzle');
  774. await waitFor(() => {
  775. expect(screen.getByText('Nozzle')).toBeInTheDocument();
  776. });
  777. expect(screen.getByText('Nozzle 2')).toBeInTheDocument();
  778. expect(screen.getByText('250°C')).toBeInTheDocument();
  779. });
  780. it('draws temperatures while the printer is idle', async () => {
  781. server.use(
  782. http.get('/api/v1/printers/:id/status', () =>
  783. HttpResponse.json({ ...mockStatusIdle, temperatures: { bed: 45, bed_target: 60 } }),
  784. ),
  785. );
  786. renderOverlayPage(1, '?show=bed');
  787. await screen.findByText('45°C');
  788. // A preheating printer is exactly when the readings are worth watching,
  789. // so they are not gated behind a running print.
  790. expect(screen.getByText('45°C')).toBeInTheDocument();
  791. expect(screen.getByText('60°C')).toBeInTheDocument();
  792. });
  793. it('reads temperatures from the token-authed feed in kiosk mode', async () => {
  794. server.use(
  795. http.get('/api/v1/printers/:id/overlay-status', () =>
  796. HttpResponse.json({
  797. id: 1,
  798. name: 'X1 Carbon',
  799. camera_rotation: 0,
  800. connected: true,
  801. state: 'RUNNING',
  802. current_print: 'KioskBenchy.gcode.3mf',
  803. gcode_file: 'plate_1.gcode',
  804. progress: 67,
  805. remaining_time: 40,
  806. layer_num: 10,
  807. total_layers: 20,
  808. stg_cur_name: null,
  809. temperatures: { chamber: 38, chamber_target: 40 },
  810. time_format: 'system',
  811. }),
  812. ),
  813. );
  814. renderOverlayPage(1, '?token=obs-tok&show=chamber');
  815. await waitFor(() => {
  816. expect(screen.getByText('Chamber')).toBeInTheDocument();
  817. });
  818. expect(screen.getByText('38°C')).toBeInTheDocument();
  819. });
  820. });
  821. });