SettingsPage.test.tsx 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  1. /**
  2. * Tests for the SettingsPage component.
  3. */
  4. import { describe, it, expect, beforeEach, vi } from 'vitest';
  5. import { act, fireEvent, render as rtlRender, screen, waitFor, within } from '@testing-library/react';
  6. import userEvent from '@testing-library/user-event';
  7. import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
  8. import { BrowserRouter } from 'react-router-dom';
  9. import { render } from '../utils';
  10. import { ThemeProvider } from '../../contexts/ThemeContext';
  11. import { ToastProvider } from '../../contexts/ToastContext';
  12. import { AuthProvider } from '../../contexts/AuthContext';
  13. import { SettingsPage } from '../../pages/SettingsPage';
  14. import { http, HttpResponse } from 'msw';
  15. import { server } from '../mocks/server';
  16. import { SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, SIDEBAR_ORDER_KEY } from '../../utils/sidebarLayout';
  17. import { setAuthToken } from '../../api/client';
  18. const mockSettings = {
  19. auto_archive: true,
  20. save_thumbnails: true,
  21. capture_finish_photo: true,
  22. default_filament_cost: 25.0,
  23. currency: 'USD',
  24. ams_humidity_good: 40,
  25. ams_humidity_fair: 60,
  26. ams_temp_good: 30,
  27. ams_temp_fair: 35,
  28. time_format: 'system',
  29. date_format: 'system',
  30. mqtt_enabled: false,
  31. mqtt_host: '',
  32. mqtt_port: 1883,
  33. spoolman_enabled: false,
  34. spoolman_url: '',
  35. ha_enabled: false,
  36. ha_url: '',
  37. ha_token: '',
  38. check_updates: false,
  39. check_printer_firmware: false,
  40. bed_cooled_threshold: 35,
  41. };
  42. describe('SettingsPage', () => {
  43. beforeEach(() => {
  44. // BrowserRouter shares window.location across tests; reset it so a tab
  45. // switch in one test (e.g. clicking "Workflow") doesn't carry into
  46. // sibling tests that expect to land on the default General tab.
  47. window.history.replaceState({}, '', '/');
  48. vi.mocked(localStorage.getItem).mockReset();
  49. vi.mocked(localStorage.setItem).mockReset();
  50. vi.mocked(localStorage.removeItem).mockReset();
  51. vi.mocked(localStorage.clear).mockReset();
  52. localStorage.clear();
  53. setAuthToken(null);
  54. server.use(
  55. http.get('/api/v1/settings/', () => {
  56. return HttpResponse.json(mockSettings);
  57. }),
  58. http.put('/api/v1/settings/', async ({ request }) => {
  59. const body = await request.json();
  60. return HttpResponse.json({ ...mockSettings, ...body });
  61. }),
  62. http.get('/api/v1/printers/', () => {
  63. return HttpResponse.json([]);
  64. }),
  65. http.get('/api/v1/smart-plugs/', () => {
  66. return HttpResponse.json([]);
  67. }),
  68. http.get('/api/v1/notifications/', () => {
  69. return HttpResponse.json([]);
  70. }),
  71. http.get('/api/v1/api-keys/', () => {
  72. return HttpResponse.json([]);
  73. }),
  74. http.get('/api/v1/mqtt/status', () => {
  75. return HttpResponse.json({ enabled: false });
  76. }),
  77. http.get('/api/v1/virtual-printer/status', () => {
  78. return HttpResponse.json({ running: false });
  79. }),
  80. http.get('/api/v1/auth/status', () => {
  81. return HttpResponse.json({ auth_enabled: false, requires_setup: false });
  82. }),
  83. http.get('/api/v1/external-links/', () => {
  84. return HttpResponse.json([]);
  85. })
  86. );
  87. });
  88. describe('rendering', () => {
  89. it('renders the page title', async () => {
  90. render(<SettingsPage />);
  91. await waitFor(() => {
  92. // Use role-based query to avoid conflicts with dropdown options
  93. expect(screen.getByRole('heading', { name: 'Settings' })).toBeInTheDocument();
  94. });
  95. });
  96. it('shows settings tabs', async () => {
  97. render(<SettingsPage />);
  98. await waitFor(() => {
  99. // Use getAllByText since "General" appears both as tab and section heading
  100. expect(screen.getAllByText('General').length).toBeGreaterThan(0);
  101. expect(screen.getByText('Smart Plugs')).toBeInTheDocument();
  102. expect(screen.getAllByText('Notifications').length).toBeGreaterThan(0);
  103. expect(screen.getAllByText('Filament').length).toBeGreaterThan(0);
  104. expect(screen.getByText('Network')).toBeInTheDocument();
  105. expect(screen.getByText('API Keys')).toBeInTheDocument();
  106. });
  107. });
  108. });
  109. describe('finish photo plate restore (#2547)', () => {
  110. const restoreLabel = 'Restore plate for finish photo';
  111. it('offers the toggle while finish photos are enabled', async () => {
  112. render(<SettingsPage />);
  113. expect(await screen.findByText(restoreLabel)).toBeInTheDocument();
  114. });
  115. it('hides the toggle when finish photos are switched off', async () => {
  116. // It only describes how the finish photo is framed, so it is meaningless
  117. // when no finish photo is taken at all.
  118. server.use(
  119. http.get('/api/v1/settings/', () =>
  120. HttpResponse.json({ ...mockSettings, capture_finish_photo: false })
  121. )
  122. );
  123. render(<SettingsPage />);
  124. await screen.findByRole('heading', { name: 'Settings' });
  125. await waitFor(() => {
  126. expect(screen.queryByText(restoreLabel)).not.toBeInTheDocument();
  127. });
  128. });
  129. it('defaults to on when the backend has never stored the setting', async () => {
  130. // Existing installs have no row for it; the UI must not read that as off.
  131. render(<SettingsPage />);
  132. const label = await screen.findByText(restoreLabel);
  133. const row = label.closest('div')!.parentElement!;
  134. expect(within(row).getByRole('checkbox')).toBeChecked();
  135. });
  136. it('sends the new value on save', async () => {
  137. let saved: Record<string, unknown> | null = null;
  138. server.use(
  139. http.put('/api/v1/settings/', async ({ request }) => {
  140. saved = (await request.json()) as Record<string, unknown>;
  141. return HttpResponse.json({ ...mockSettings, ...saved });
  142. })
  143. );
  144. render(<SettingsPage />);
  145. const label = await screen.findByText(restoreLabel);
  146. // The page suppresses auto-save for 100ms after the settings load, so a
  147. // click landing inside that window is swallowed with no re-trigger.
  148. await new Promise((resolve) => setTimeout(resolve, 200));
  149. const row = label.closest('div')!.parentElement!;
  150. await userEvent.click(within(row).getByRole('checkbox'));
  151. // The page auto-saves on a 500ms debounce, so the default 1s waitFor
  152. // window is only just wide enough — give the request room to land.
  153. await waitFor(() => {
  154. expect(saved).not.toBeNull();
  155. }, { timeout: 3000 });
  156. expect(saved!.finish_photo_restore_plate).toBe(false);
  157. });
  158. });
  159. describe('general settings', () => {
  160. it('shows date format setting', async () => {
  161. render(<SettingsPage />);
  162. await waitFor(() => {
  163. expect(screen.getByText('Date Format')).toBeInTheDocument();
  164. });
  165. });
  166. it('shows time format setting', async () => {
  167. render(<SettingsPage />);
  168. await waitFor(() => {
  169. expect(screen.getByText('Time Format')).toBeInTheDocument();
  170. });
  171. });
  172. it('shows default printer setting', async () => {
  173. render(<SettingsPage />);
  174. await waitFor(() => {
  175. expect(screen.getByText('Default Printer')).toBeInTheDocument();
  176. });
  177. });
  178. it('shows preferred slicer setting on Workflow tab', async () => {
  179. const user = userEvent.setup();
  180. render(<SettingsPage />);
  181. await waitFor(() => {
  182. expect(screen.getByText('Workflow')).toBeInTheDocument();
  183. });
  184. await user.click(screen.getByText('Workflow'));
  185. await waitFor(() => {
  186. expect(screen.getByText('Preferred Slicer')).toBeInTheDocument();
  187. });
  188. });
  189. it('shows slicer dropdown with both options on Workflow tab', async () => {
  190. const user = userEvent.setup();
  191. render(<SettingsPage />);
  192. await waitFor(() => {
  193. expect(screen.getByText('Workflow')).toBeInTheDocument();
  194. });
  195. await user.click(screen.getByText('Workflow'));
  196. await waitFor(() => {
  197. const slicerSelect = screen.getAllByDisplayValue('Bambu Studio');
  198. expect(slicerSelect.length).toBeGreaterThan(0);
  199. });
  200. });
  201. it('shows appearance section', async () => {
  202. render(<SettingsPage />);
  203. await waitFor(() => {
  204. expect(screen.getByText('Appearance')).toBeInTheDocument();
  205. });
  206. });
  207. it('shows updates section with firmware toggle', async () => {
  208. render(<SettingsPage />);
  209. await waitFor(() => {
  210. expect(screen.getByText('Updates')).toBeInTheDocument();
  211. expect(screen.getByText('Check for updates')).toBeInTheDocument();
  212. expect(screen.getByText('Check printer firmware')).toBeInTheDocument();
  213. });
  214. });
  215. it('hides a Bambuddy sidebar page from Sidebar', async () => {
  216. const user = userEvent.setup();
  217. render(<SettingsPage />);
  218. await screen.findByRole('heading', { name: 'Sidebar' });
  219. await screen.findAllByText('Visible in sidebar');
  220. vi.mocked(localStorage.setItem).mockClear();
  221. await user.click((await screen.findAllByLabelText('Hide page'))[0]);
  222. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, JSON.stringify(['printers']));
  223. expect(screen.getByText('Hidden from sidebar')).toBeInTheDocument();
  224. });
  225. it('shows a previously hidden Bambuddy sidebar page from Sidebar', async () => {
  226. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  227. if (key === SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY) return JSON.stringify(['printers']);
  228. return null;
  229. });
  230. const user = userEvent.setup();
  231. render(<SettingsPage />);
  232. await screen.findByRole('heading', { name: 'Sidebar' });
  233. await screen.findByText('Hidden from sidebar');
  234. vi.mocked(localStorage.setItem).mockClear();
  235. await user.click(await screen.findByLabelText('Show page'));
  236. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, JSON.stringify([]));
  237. expect(screen.getAllByText('Visible in sidebar').length).toBeGreaterThan(0);
  238. });
  239. it('does not allow Settings to be hidden from Sidebar', async () => {
  240. render(<SettingsPage />);
  241. await screen.findByRole('heading', { name: 'Sidebar' });
  242. await screen.findByText('Required in sidebar');
  243. const settingsVisibilityButton = await screen.findByLabelText('Settings cannot be hidden');
  244. expect(settingsVisibilityButton).toBeDisabled();
  245. expect(screen.getByText('Required in sidebar')).toBeInTheDocument();
  246. });
  247. it('presents external links and Bambuddy pages in saved sidebar order', async () => {
  248. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  249. if (key === SIDEBAR_ORDER_KEY) return JSON.stringify(['ext-7', 'printers', 'settings']);
  250. return null;
  251. });
  252. server.use(
  253. http.get('/api/v1/external-links/', () =>
  254. HttpResponse.json([
  255. {
  256. id: 7,
  257. name: 'Docs',
  258. url: 'https://docs.example.test',
  259. icon: 'Link',
  260. open_in_new_tab: true,
  261. custom_icon: null,
  262. sort_order: 0,
  263. created_at: '2026-01-01T00:00:00Z',
  264. updated_at: '2026-01-01T00:00:00Z',
  265. },
  266. ]),
  267. ),
  268. );
  269. render(<SettingsPage />);
  270. await screen.findByRole('heading', { name: 'Sidebar' });
  271. const docs = await screen.findByText('Docs');
  272. const printers = screen.getAllByText('Printers').find(element => element.closest('[draggable="true"]'));
  273. expect(printers).toBeDefined();
  274. expect(docs.compareDocumentPosition(printers) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
  275. });
  276. it('saves mixed Sidebar order when items are dragged', async () => {
  277. server.use(
  278. http.get('/api/v1/external-links/', () =>
  279. HttpResponse.json([
  280. {
  281. id: 7,
  282. name: 'Docs',
  283. url: 'https://docs.example.test',
  284. icon: 'Link',
  285. open_in_new_tab: true,
  286. custom_icon: null,
  287. sort_order: 0,
  288. created_at: '2026-01-01T00:00:00Z',
  289. updated_at: '2026-01-01T00:00:00Z',
  290. },
  291. ]),
  292. ),
  293. );
  294. render(<SettingsPage />);
  295. await screen.findByRole('heading', { name: 'Sidebar' });
  296. const docsRow = (await screen.findByText('Docs')).closest('[draggable="true"]');
  297. const printersRow = screen.getAllByText('Printers')
  298. .find(element => element.closest('[draggable="true"]'))
  299. ?.closest('[draggable="true"]');
  300. expect(docsRow).not.toBeNull();
  301. expect(printersRow).not.toBeNull();
  302. vi.mocked(localStorage.setItem).mockClear();
  303. const dataTransfer = {
  304. effectAllowed: '',
  305. dropEffect: '',
  306. setData: vi.fn(),
  307. };
  308. fireEvent.dragStart(docsRow!, { dataTransfer });
  309. fireEvent.dragOver(printersRow!, { dataTransfer });
  310. fireEvent.drop(printersRow!, { dataTransfer });
  311. expect(localStorage.setItem).toHaveBeenCalledWith(
  312. SIDEBAR_ORDER_KEY,
  313. JSON.stringify(['ext-7', 'printers', 'inventory', 'archives', 'queue', 'projects', 'files', 'makerworld', 'profiles', 'maintenance', 'stats', 'notifications', 'settings']),
  314. );
  315. });
  316. it('resets Sidebar to all pages first and configured links at the bottom', async () => {
  317. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  318. if (key === SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY) return JSON.stringify(['printers', 'stats']);
  319. if (key === SIDEBAR_ORDER_KEY) return JSON.stringify(['ext-7', 'settings', 'printers']);
  320. return null;
  321. });
  322. server.use(
  323. http.get('/api/v1/external-links/', () =>
  324. HttpResponse.json([
  325. {
  326. id: 7,
  327. name: 'Docs',
  328. url: 'https://docs.example.test',
  329. icon: 'Link',
  330. open_in_new_tab: true,
  331. custom_icon: null,
  332. sort_order: 0,
  333. created_at: '2026-01-01T00:00:00Z',
  334. updated_at: '2026-01-01T00:00:00Z',
  335. },
  336. ]),
  337. ),
  338. );
  339. const user = userEvent.setup();
  340. render(<SettingsPage />);
  341. const heading = await screen.findByRole('heading', { name: 'Sidebar' });
  342. const card = heading.closest('#card-sidebar-links');
  343. expect(card).not.toBeNull();
  344. await screen.findByText('Docs');
  345. vi.mocked(localStorage.setItem).mockClear();
  346. await user.click(within(card as HTMLElement).getByRole('button', { name: /reset/i }));
  347. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, JSON.stringify([]));
  348. expect(localStorage.setItem).toHaveBeenCalledWith(
  349. SIDEBAR_ORDER_KEY,
  350. JSON.stringify(['printers', 'inventory', 'archives', 'queue', 'projects', 'files', 'makerworld', 'profiles', 'maintenance', 'stats', 'notifications', 'settings', 'ext-7']),
  351. );
  352. const settingsRow = screen.getAllByText('Settings')
  353. .find(element => element.closest('[draggable="true"]'))
  354. ?.closest('[draggable="true"]');
  355. const docsRow = screen.getByText('Docs').closest('[draggable="true"]');
  356. expect(settingsRow).not.toBeNull();
  357. expect(docsRow).not.toBeNull();
  358. expect(settingsRow!.compareDocumentPosition(docsRow!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
  359. expect(screen.queryByText('Hidden from sidebar')).not.toBeInTheDocument();
  360. });
  361. it('sets the current Sidebar order as the backend default for settings admins', async () => {
  362. let defaultSidebarOrderPayload: string | null = null;
  363. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  364. if (key === SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY) return JSON.stringify(['stats']);
  365. return null;
  366. });
  367. server.use(
  368. http.get('/api/v1/auth/status', () =>
  369. HttpResponse.json({ auth_enabled: true, requires_setup: false }),
  370. ),
  371. http.get('/api/v1/auth/me', () =>
  372. HttpResponse.json({
  373. id: 1,
  374. username: 'admin',
  375. role: 'admin',
  376. is_active: true,
  377. is_admin: false,
  378. groups: [{ id: 1, name: 'Administrators' }],
  379. permissions: ['settings:update'],
  380. created_at: '2026-01-01T00:00:00Z',
  381. }),
  382. ),
  383. http.get('/api/v1/settings/', () =>
  384. HttpResponse.json({ ...mockSettings, default_sidebar_order: '' }),
  385. ),
  386. http.put('/api/v1/settings/', async ({ request }) => {
  387. const body = await request.json() as { default_sidebar_order?: string };
  388. defaultSidebarOrderPayload = body.default_sidebar_order ?? null;
  389. return HttpResponse.json({ ...mockSettings, ...body });
  390. }),
  391. );
  392. setAuthToken('test-token');
  393. const user = userEvent.setup();
  394. render(<SettingsPage />);
  395. const heading = await screen.findByRole('heading', { name: 'Sidebar' });
  396. const card = heading.closest('#card-sidebar-links');
  397. expect(card).not.toBeNull();
  398. await user.click(within(card as HTMLElement).getByRole('switch', { name: 'Set Default' }));
  399. await waitFor(() => {
  400. expect(defaultSidebarOrderPayload).not.toBeNull();
  401. });
  402. expect(JSON.parse(defaultSidebarOrderPayload!)).toEqual({
  403. order: [
  404. 'printers',
  405. 'inventory',
  406. 'archives',
  407. 'queue',
  408. 'projects',
  409. 'files',
  410. 'makerworld',
  411. 'profiles',
  412. 'maintenance',
  413. 'stats',
  414. 'notifications',
  415. 'settings',
  416. ],
  417. hiddenSystemItemIds: ['stats'],
  418. });
  419. });
  420. });
  421. describe('update CTA per deployment shape', () => {
  422. // The update card branches on the deployment shape returned by
  423. // /updates/check. Each branch is mutually exclusive — verify the right
  424. // one wins so HA addon users never see the docker-compose snippet
  425. // (which they can't run from inside an HA addon container) and Docker
  426. // users never see the in-app Install button (which would no-op).
  427. const renderWithUpdateCheck = async (
  428. checkBody: Record<string, unknown>,
  429. ) => {
  430. server.use(
  431. http.get('/api/v1/settings/', () =>
  432. HttpResponse.json({ ...mockSettings, check_updates: true }),
  433. ),
  434. http.get('/api/v1/updates/check', () => HttpResponse.json(checkBody)),
  435. );
  436. render(<SettingsPage />);
  437. await waitFor(() => {
  438. expect(screen.getByText('Updates')).toBeInTheDocument();
  439. });
  440. };
  441. it('shows the HA Supervisor message when running as an HA addon', async () => {
  442. await renderWithUpdateCheck({
  443. update_available: true,
  444. current_version: '0.2.4',
  445. latest_version: '0.2.5',
  446. release_name: '0.2.5',
  447. release_notes: '',
  448. release_url: 'https://example.invalid/r',
  449. published_at: '2099-01-01T00:00:00Z',
  450. is_docker: true,
  451. is_ha_addon: true,
  452. update_method: 'ha_addon',
  453. });
  454. await waitFor(() => {
  455. expect(
  456. screen.getByText(/Home Assistant Supervisor/i),
  457. ).toBeInTheDocument();
  458. });
  459. // Docker hint must NOT render — HA branch wins.
  460. expect(screen.queryByText('docker compose pull && docker compose up -d')).not.toBeInTheDocument();
  461. expect(screen.queryByRole('button', { name: /install update/i })).not.toBeInTheDocument();
  462. });
  463. it('shows the docker-compose snippet for Docker (non-HA) deployments', async () => {
  464. await renderWithUpdateCheck({
  465. update_available: true,
  466. current_version: '0.2.4',
  467. latest_version: '0.2.5',
  468. release_name: '0.2.5',
  469. release_notes: '',
  470. release_url: 'https://example.invalid/r',
  471. published_at: '2099-01-01T00:00:00Z',
  472. is_docker: true,
  473. is_ha_addon: false,
  474. update_method: 'docker',
  475. });
  476. await waitFor(() => {
  477. expect(screen.getByText('docker compose pull && docker compose up -d')).toBeInTheDocument();
  478. });
  479. expect(screen.queryByText(/Home Assistant Supervisor/i)).not.toBeInTheDocument();
  480. expect(screen.queryByRole('button', { name: /install update/i })).not.toBeInTheDocument();
  481. });
  482. it('shows the installer-download link for Windows installer installs', async () => {
  483. const downloadUrl =
  484. 'https://github.com/maziggy/bambuddy/releases/download/v0.2.5/bambuddy-0.2.5-windows-x64-setup.exe';
  485. await renderWithUpdateCheck({
  486. update_available: true,
  487. current_version: '0.2.4',
  488. latest_version: '0.2.5',
  489. release_name: '0.2.5',
  490. release_notes: '',
  491. release_url: 'https://github.com/maziggy/bambuddy/releases/tag/v0.2.5',
  492. published_at: '2099-01-01T00:00:00Z',
  493. is_docker: false,
  494. is_ha_addon: false,
  495. is_windows_installer: true,
  496. update_method: 'windows_installer',
  497. installer_download_url: downloadUrl,
  498. });
  499. const link = await screen.findByRole('link', { name: /download installer for v0\.2\.5/i });
  500. expect(link).toHaveAttribute('href', downloadUrl);
  501. expect(link).toHaveAttribute('target', '_blank');
  502. expect(link).toHaveAttribute('rel', expect.stringContaining('noopener'));
  503. // The in-app update button must NOT render — the git-fetch path can't
  504. // work from an installer payload.
  505. expect(screen.queryByRole('button', { name: /install update/i })).not.toBeInTheDocument();
  506. expect(screen.queryByText(/Home Assistant Supervisor/i)).not.toBeInTheDocument();
  507. expect(screen.queryByText('docker compose pull && docker compose up -d')).not.toBeInTheDocument();
  508. });
  509. });
  510. describe('tabs navigation', () => {
  511. it('can switch to Network tab', async () => {
  512. const user = userEvent.setup();
  513. render(<SettingsPage />);
  514. // Wait for settings to load first
  515. await waitFor(() => {
  516. expect(screen.getByText('Date Format')).toBeInTheDocument();
  517. });
  518. await user.click(screen.getByText('Network'));
  519. await waitFor(() => {
  520. // Network tab contains MQTT Publishing section
  521. expect(screen.getByText('MQTT Publishing')).toBeInTheDocument();
  522. });
  523. });
  524. it('can switch to Smart Plugs tab', async () => {
  525. const user = userEvent.setup();
  526. render(<SettingsPage />);
  527. await waitFor(() => {
  528. expect(screen.getByText('Smart Plugs')).toBeInTheDocument();
  529. });
  530. await user.click(screen.getByText('Smart Plugs'));
  531. await waitFor(() => {
  532. expect(screen.getByText('Add Smart Plug')).toBeInTheDocument();
  533. });
  534. });
  535. it('can switch to Notifications tab', async () => {
  536. const user = userEvent.setup();
  537. render(<SettingsPage />);
  538. await waitFor(() => {
  539. expect(screen.getAllByText('Notifications').length).toBeGreaterThan(0);
  540. });
  541. // Click the tab button (not the mobile dropdown option)
  542. const notificationButtons = screen.getAllByText('Notifications');
  543. const tabButton = notificationButtons.find(el => el.tagName === 'BUTTON') || notificationButtons[0];
  544. await user.click(tabButton);
  545. await waitFor(() => {
  546. expect(screen.getByText('Add Provider')).toBeInTheDocument();
  547. });
  548. });
  549. it('can switch to Filament tab', async () => {
  550. const user = userEvent.setup();
  551. render(<SettingsPage />);
  552. await waitFor(() => {
  553. expect(screen.getAllByText('Filament').length).toBeGreaterThan(0);
  554. });
  555. await user.click(screen.getAllByText('Filament')[0]);
  556. await waitFor(() => {
  557. expect(screen.getByText('AMS Display Thresholds')).toBeInTheDocument();
  558. });
  559. });
  560. });
  561. describe('Workflow tab', () => {
  562. it('can switch to Workflow tab', async () => {
  563. const user = userEvent.setup();
  564. render(<SettingsPage />);
  565. await waitFor(() => {
  566. expect(screen.getByText('Workflow')).toBeInTheDocument();
  567. });
  568. await user.click(screen.getByText('Workflow'));
  569. await waitFor(() => {
  570. expect(screen.getByText('Staggered Start')).toBeInTheDocument();
  571. });
  572. });
  573. it('shows stagger settings on Workflow tab', async () => {
  574. const user = userEvent.setup();
  575. render(<SettingsPage />);
  576. await waitFor(() => {
  577. expect(screen.getByText('Workflow')).toBeInTheDocument();
  578. });
  579. await user.click(screen.getByText('Workflow'));
  580. await waitFor(() => {
  581. expect(screen.getByText('Staggered Start')).toBeInTheDocument();
  582. expect(screen.getByText('Group size')).toBeInTheDocument();
  583. expect(screen.getByText('Interval (minutes)')).toBeInTheDocument();
  584. });
  585. });
  586. it('shows auto-drying settings on Workflow tab', async () => {
  587. const user = userEvent.setup();
  588. render(<SettingsPage />);
  589. await waitFor(() => {
  590. expect(screen.getByText('Workflow')).toBeInTheDocument();
  591. });
  592. await user.click(screen.getByText('Workflow'));
  593. await waitFor(() => {
  594. expect(screen.getByText('Queue Auto-Drying')).toBeInTheDocument();
  595. });
  596. });
  597. it('shows per-filament humidity threshold editor on Workflow tab (#1605)', async () => {
  598. const user = userEvent.setup();
  599. render(<SettingsPage />);
  600. await waitFor(() => {
  601. expect(screen.getByText('Workflow')).toBeInTheDocument();
  602. });
  603. await user.click(screen.getByText('Workflow'));
  604. await waitFor(() => {
  605. expect(screen.getByText('Humidity Thresholds')).toBeInTheDocument();
  606. // Default row is unique to the humidity editor (drying presets has no
  607. // default row), so we can pin it without disambiguating from the
  608. // adjacent drying-presets table that also lists PLA/ASA/etc.
  609. expect(screen.getByText('Default (unknown types)')).toBeInTheDocument();
  610. // Filament rows render in both tables — assert by count instead of
  611. // a single getByText. 8 default filaments × 2 tables = 16 PLAs etc.
  612. expect(screen.getAllByText('PLA').length).toBeGreaterThanOrEqual(2);
  613. expect(screen.getAllByText('ASA').length).toBeGreaterThanOrEqual(2);
  614. });
  615. });
  616. it('shows default print options on Workflow tab', async () => {
  617. const user = userEvent.setup();
  618. render(<SettingsPage />);
  619. await waitFor(() => {
  620. expect(screen.getByText('Workflow')).toBeInTheDocument();
  621. });
  622. await user.click(screen.getByText('Workflow'));
  623. await waitFor(() => {
  624. expect(screen.getByText('Default Print Options')).toBeInTheDocument();
  625. expect(screen.getByText('Bed Levelling')).toBeInTheDocument();
  626. expect(screen.getByText('Flow Calibration')).toBeInTheDocument();
  627. expect(screen.getByText('Vibration Calibration')).toBeInTheDocument();
  628. expect(screen.getByText('First Layer Inspection')).toBeInTheDocument();
  629. expect(screen.getByText('Timelapse')).toBeInTheDocument();
  630. });
  631. });
  632. it('shows default print options description', async () => {
  633. const user = userEvent.setup();
  634. render(<SettingsPage />);
  635. await waitFor(() => {
  636. expect(screen.getByText('Workflow')).toBeInTheDocument();
  637. });
  638. await user.click(screen.getByText('Workflow'));
  639. await waitFor(() => {
  640. expect(screen.getByText(/overridden per print in the print dialog/)).toBeInTheDocument();
  641. });
  642. });
  643. });
  644. describe('API Keys tab', () => {
  645. it('can switch to API Keys tab', async () => {
  646. const user = userEvent.setup();
  647. render(<SettingsPage />);
  648. await waitFor(() => {
  649. expect(screen.getByText('API Keys')).toBeInTheDocument();
  650. });
  651. await user.click(screen.getByText('API Keys'));
  652. await waitFor(() => {
  653. // Button text is "Create Key"
  654. expect(screen.getByText('Create Key')).toBeInTheDocument();
  655. });
  656. });
  657. });
  658. describe('SpoolBuddy tab badge', () => {
  659. const baseDevice = {
  660. id: 1,
  661. device_id: 'sb-0001',
  662. hostname: 'sb-kitchen',
  663. ip_address: '10.0.0.1',
  664. backend_url: null,
  665. firmware_version: '1.0.0',
  666. has_nfc: true,
  667. has_scale: true,
  668. tare_offset: 0,
  669. calibration_factor: 1.0,
  670. nfc_reader_type: null,
  671. nfc_connection: null,
  672. display_brightness: 100,
  673. display_blank_timeout: 0,
  674. has_backlight: false,
  675. last_calibrated_at: null,
  676. last_seen: new Date().toISOString(),
  677. pending_command: null,
  678. nfc_ok: true,
  679. scale_ok: true,
  680. uptime_s: 100,
  681. update_status: null,
  682. update_message: null,
  683. system_stats: null,
  684. online: true,
  685. created_at: '2024-01-01T00:00:00Z',
  686. updated_at: '2024-01-01T00:00:00Z',
  687. };
  688. it('shows device count and green bullet when at least one device is online', async () => {
  689. server.use(
  690. http.get('/api/v1/spoolbuddy/devices', () => {
  691. return HttpResponse.json([
  692. { ...baseDevice, id: 1, device_id: 'sb-0001', hostname: 'sb-kitchen', online: true },
  693. { ...baseDevice, id: 2, device_id: 'sb-0002', hostname: 'sb-ghost', online: false },
  694. ]);
  695. })
  696. );
  697. render(<SettingsPage />);
  698. // Find the tab button (not the header) — it's the <button> containing the SpoolBuddy text
  699. const tabButton = await waitFor(() => {
  700. const buttons = screen.getAllByRole('button').filter((b) => b.textContent?.includes('SpoolBuddy'));
  701. expect(buttons.length).toBeGreaterThan(0);
  702. return buttons[0];
  703. });
  704. // Count pill rendered
  705. await waitFor(() => {
  706. expect(tabButton.textContent).toContain('2');
  707. });
  708. // Green status bullet (at least one device online)
  709. await waitFor(() => {
  710. expect(tabButton.querySelector('.bg-green-400')).not.toBeNull();
  711. });
  712. });
  713. it('shows gray bullet when all devices are offline', async () => {
  714. server.use(
  715. http.get('/api/v1/spoolbuddy/devices', () => {
  716. return HttpResponse.json([{ ...baseDevice, online: false }]);
  717. })
  718. );
  719. render(<SettingsPage />);
  720. const tabButton = await waitFor(() => {
  721. const buttons = screen.getAllByRole('button').filter((b) => b.textContent?.includes('SpoolBuddy'));
  722. expect(buttons.length).toBeGreaterThan(0);
  723. return buttons[0];
  724. });
  725. await waitFor(() => {
  726. expect(tabButton.querySelector('.bg-gray-500')).not.toBeNull();
  727. expect(tabButton.querySelector('.bg-green-400')).toBeNull();
  728. });
  729. });
  730. it('hides the count pill when no devices are registered', async () => {
  731. server.use(
  732. http.get('/api/v1/spoolbuddy/devices', () => HttpResponse.json([]))
  733. );
  734. render(<SettingsPage />);
  735. const tabButton = await waitFor(() => {
  736. const buttons = screen.getAllByRole('button').filter((b) => b.textContent?.includes('SpoolBuddy'));
  737. expect(buttons.length).toBeGreaterThan(0);
  738. return buttons[0];
  739. });
  740. // The only numeric content should NOT be present — tab label only
  741. await waitFor(() => {
  742. expect(tabButton.textContent).toBe('SpoolBuddy');
  743. });
  744. });
  745. });
  746. describe('API Keys tab — delete flow', () => {
  747. // Without setQueryData on success the deleted row stayed visible until a
  748. // manual reload — invalidateQueries didn't reliably trigger a UI swap on
  749. // every browser. Pin the synchronous-removal contract here.
  750. it('removes a deleted key from the list without a page reload', async () => {
  751. const initialKeys = [
  752. {
  753. id: 42,
  754. name: 'CI deploy key',
  755. key_prefix: 'bk_abcd1234',
  756. can_queue: true,
  757. can_control_printer: false,
  758. can_read_status: true,
  759. printer_ids: null,
  760. enabled: true,
  761. last_used: null,
  762. created_at: '2026-01-01T00:00:00Z',
  763. expires_at: null,
  764. },
  765. ];
  766. let deleteCallCount = 0;
  767. server.use(
  768. http.get('/api/v1/api-keys/', () => HttpResponse.json(initialKeys)),
  769. http.delete('/api/v1/api-keys/:id', ({ params }) => {
  770. deleteCallCount += 1;
  771. expect(params.id).toBe('42');
  772. return HttpResponse.json({ message: 'API key deleted' });
  773. })
  774. );
  775. const user = userEvent.setup();
  776. render(<SettingsPage />);
  777. // Switch to API Keys tab. Both desktop tab + mobile dropdown render
  778. // the label, so just grab the button form.
  779. await waitFor(() => {
  780. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  781. });
  782. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  783. expect(tabButton).toBeDefined();
  784. await user.click(tabButton!);
  785. // Key is listed
  786. await waitFor(() => {
  787. expect(screen.getByText('CI deploy key')).toBeInTheDocument();
  788. });
  789. // Click the trash button on the row
  790. const cards = screen.getByText('CI deploy key').closest('.flex.items-center.justify-between');
  791. expect(cards).not.toBeNull();
  792. const trashButton = cards!.querySelectorAll('button');
  793. await user.click(trashButton[trashButton.length - 1]);
  794. // Confirm the deletion in the modal
  795. const confirmButton = await screen.findByRole('button', { name: /delete/i });
  796. await user.click(confirmButton);
  797. // The deleted key disappears from the list immediately — no manual
  798. // reload required. setQueryData drops it before any refetch could fire.
  799. await waitFor(() => {
  800. expect(screen.queryByText('CI deploy key')).not.toBeInTheDocument();
  801. });
  802. expect(deleteCallCount).toBe(1);
  803. });
  804. });
  805. describe('API Keys tab — #1182 cloud access + ownership UI', () => {
  806. // The list now exposes two new bits of information per row:
  807. // - "Cloud" badge when can_access_cloud=true
  808. // - "Legacy" badge when user_id IS NULL (created before per-user ownership)
  809. // These tell the operator at a glance which keys can read /cloud/* data
  810. // and which keys need to be recreated to gain that capability.
  811. it('renders the Cloud badge for keys with can_access_cloud=true and the Legacy badge for ownerless keys', async () => {
  812. const keys = [
  813. {
  814. id: 1,
  815. name: 'cloud-reader',
  816. key_prefix: 'bk_cloud123',
  817. user_id: 7,
  818. can_queue: false,
  819. can_control_printer: false,
  820. can_read_status: true,
  821. can_access_cloud: true,
  822. printer_ids: null,
  823. enabled: true,
  824. last_used: null,
  825. created_at: '2026-04-30T00:00:00Z',
  826. expires_at: null,
  827. },
  828. {
  829. id: 2,
  830. name: 'legacy-key',
  831. key_prefix: 'bk_legacy01',
  832. user_id: null,
  833. can_queue: true,
  834. can_control_printer: false,
  835. can_read_status: true,
  836. can_access_cloud: false,
  837. printer_ids: null,
  838. enabled: true,
  839. last_used: null,
  840. created_at: '2025-01-01T00:00:00Z',
  841. expires_at: null,
  842. },
  843. ];
  844. server.use(http.get('/api/v1/api-keys/', () => HttpResponse.json(keys)));
  845. const user = userEvent.setup();
  846. render(<SettingsPage />);
  847. await waitFor(() => {
  848. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  849. });
  850. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  851. await user.click(tabButton!);
  852. await waitFor(() => {
  853. expect(screen.getByText('cloud-reader')).toBeInTheDocument();
  854. expect(screen.getByText('legacy-key')).toBeInTheDocument();
  855. });
  856. // Cloud-enabled key gets the Cloud badge but NOT the Legacy badge.
  857. const cloudRow = screen.getByText('cloud-reader').closest('.flex.items-center.justify-between');
  858. expect(cloudRow).not.toBeNull();
  859. expect(cloudRow!.textContent).toContain('Cloud');
  860. expect(cloudRow!.textContent).not.toContain('Legacy');
  861. // Ownerless key gets Legacy but NOT Cloud (can_access_cloud=false).
  862. const legacyRow = screen.getByText('legacy-key').closest('.flex.items-center.justify-between');
  863. expect(legacyRow).not.toBeNull();
  864. expect(legacyRow!.textContent).toContain('Legacy');
  865. // Strip the Cloud-flag check by limiting to badge area — the
  866. // "Allow cloud access" text from the create form isn't visible here.
  867. expect(legacyRow!.querySelector('.bg-purple-500\\/20')).toBeNull();
  868. });
  869. it('passes can_access_cloud through to the create call when the toggle is checked', async () => {
  870. let posted: { name?: string; can_access_cloud?: boolean } | null = null;
  871. server.use(
  872. http.get('/api/v1/api-keys/', () => HttpResponse.json([])),
  873. http.post('/api/v1/api-keys/', async ({ request }) => {
  874. posted = (await request.json()) as { name?: string; can_access_cloud?: boolean };
  875. return HttpResponse.json({
  876. id: 99,
  877. key: 'bk_returnedkey',
  878. name: posted.name,
  879. key_prefix: 'bk_returne',
  880. user_id: 1,
  881. can_queue: true,
  882. can_control_printer: false,
  883. can_read_status: true,
  884. can_access_cloud: posted.can_access_cloud ?? false,
  885. printer_ids: null,
  886. enabled: true,
  887. last_used: null,
  888. created_at: '2026-05-01T00:00:00Z',
  889. expires_at: null,
  890. });
  891. })
  892. );
  893. const user = userEvent.setup();
  894. render(<SettingsPage />);
  895. await waitFor(() => {
  896. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  897. });
  898. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  899. await user.click(tabButton!);
  900. // Open the create form. With an empty key list the empty-state card
  901. // shows "Create Your First Key" — click that to open the form.
  902. const openButton = await screen.findByRole('button', { name: /Create Your First Key/i });
  903. await user.click(openButton);
  904. // Tick the new "Allow cloud access" checkbox. The label wraps the
  905. // input AND a sibling description div, so getByLabelText doesn't
  906. // resolve via implicit-label traversal — locate via text + closest
  907. // label, then grab the checkbox from the same scope.
  908. const cloudLabelText = await screen.findByText(/Allow cloud access/i);
  909. const cloudLabel = cloudLabelText.closest('label');
  910. expect(cloudLabel).not.toBeNull();
  911. const cloudCheckbox = cloudLabel!.querySelector('input[type="checkbox"]') as HTMLInputElement;
  912. expect(cloudCheckbox).not.toBeNull();
  913. await user.click(cloudCheckbox);
  914. // Submit. Two "Create Key" buttons exist once the form is open (header
  915. // CTA + form footer); the form-footer one is the actual submit and
  916. // calls the mutation — find it by walking up from the cloud checkbox
  917. // we just clicked, since both share the same form container.
  918. const submitButtons = screen.getAllByRole('button', { name: /^Create Key$/i });
  919. // Footer submit is the one inside the same form section as the
  920. // checkbox. The header CTA is in a separate flex row.
  921. const formSubmit = submitButtons.find(
  922. (b) => b.closest('div')?.contains(cloudCheckbox) || cloudLabel?.parentElement?.parentElement?.contains(b),
  923. );
  924. await user.click(formSubmit ?? submitButtons[submitButtons.length - 1]);
  925. await waitFor(() => {
  926. expect(posted).not.toBeNull();
  927. expect(posted!.can_access_cloud).toBe(true);
  928. });
  929. });
  930. });
  931. describe('API Keys tab — #1356 energy-cost write scope', () => {
  932. /**
  933. * The narrowly-scoped settings-write toggle. We pin two contracts here:
  934. *
  935. * 1. The "Energy" badge renders for keys that have can_update_energy_cost=true.
  936. * Without a visible signal, an operator can't tell which key in their
  937. * list is the one their HA automation depends on.
  938. * 2. The create form sends can_update_energy_cost=true to the backend
  939. * when the toggle is checked. The whole point of #1356 is that the
  940. * flag must actually be persisted — a UI that drops it silently
  941. * would put us right back where the bug started.
  942. */
  943. it('renders the Energy badge for keys with can_update_energy_cost=true', async () => {
  944. const keys = [
  945. {
  946. id: 1,
  947. name: 'tariff-pusher',
  948. key_prefix: 'bk_tariff01',
  949. user_id: 7,
  950. can_queue: false,
  951. can_control_printer: false,
  952. can_read_status: true,
  953. can_access_cloud: false,
  954. can_update_energy_cost: true,
  955. printer_ids: null,
  956. enabled: true,
  957. last_used: null,
  958. created_at: '2026-05-15T00:00:00Z',
  959. expires_at: null,
  960. },
  961. ];
  962. server.use(http.get('/api/v1/api-keys/', () => HttpResponse.json(keys)));
  963. const user = userEvent.setup();
  964. render(<SettingsPage />);
  965. await waitFor(() => {
  966. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  967. });
  968. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  969. await user.click(tabButton!);
  970. await waitFor(() => {
  971. expect(screen.getByText('tariff-pusher')).toBeInTheDocument();
  972. });
  973. const row = screen.getByText('tariff-pusher').closest('.flex.items-center.justify-between');
  974. expect(row).not.toBeNull();
  975. expect(row!.textContent).toContain('Energy');
  976. });
  977. it('passes can_update_energy_cost through to the create call when the toggle is checked', async () => {
  978. let posted: { name?: string; can_update_energy_cost?: boolean } | null = null;
  979. server.use(
  980. http.get('/api/v1/api-keys/', () => HttpResponse.json([])),
  981. http.post('/api/v1/api-keys/', async ({ request }) => {
  982. posted = (await request.json()) as { name?: string; can_update_energy_cost?: boolean };
  983. return HttpResponse.json({
  984. id: 99,
  985. key: 'bk_returnedkey',
  986. name: posted.name,
  987. key_prefix: 'bk_returne',
  988. user_id: 1,
  989. can_queue: true,
  990. can_control_printer: false,
  991. can_read_status: true,
  992. can_access_cloud: false,
  993. can_update_energy_cost: posted.can_update_energy_cost ?? false,
  994. printer_ids: null,
  995. enabled: true,
  996. last_used: null,
  997. created_at: '2026-05-15T00:00:00Z',
  998. expires_at: null,
  999. });
  1000. })
  1001. );
  1002. const user = userEvent.setup();
  1003. render(<SettingsPage />);
  1004. await waitFor(() => {
  1005. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  1006. });
  1007. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  1008. await user.click(tabButton!);
  1009. const openButton = await screen.findByRole('button', { name: /Create Your First Key/i });
  1010. await user.click(openButton);
  1011. const energyLabelText = await screen.findByText(/Update electricity price/i);
  1012. const energyLabel = energyLabelText.closest('label');
  1013. expect(energyLabel).not.toBeNull();
  1014. const energyCheckbox = energyLabel!.querySelector('input[type="checkbox"]') as HTMLInputElement;
  1015. expect(energyCheckbox).not.toBeNull();
  1016. await user.click(energyCheckbox);
  1017. const submitButtons = screen.getAllByRole('button', { name: /^Create Key$/i });
  1018. const formSubmit = submitButtons.find(
  1019. (b) => b.closest('div')?.contains(energyCheckbox) || energyLabel?.parentElement?.parentElement?.contains(b),
  1020. );
  1021. await user.click(formSubmit ?? submitButtons[submitButtons.length - 1]);
  1022. await waitFor(() => {
  1023. expect(posted).not.toBeNull();
  1024. expect(posted!.can_update_energy_cost).toBe(true);
  1025. });
  1026. });
  1027. });
  1028. describe('external camera snapshot URL override (#1177)', () => {
  1029. /**
  1030. * The snapshot URL input only appears for stream camera types where the
  1031. * MJPEG warm-up problem can occur (mjpeg / rtsp / usb). Pure HTTP
  1032. * snapshot sources don't need an override since their stream URL is
  1033. * already a single-frame endpoint.
  1034. */
  1035. const mjpegPrinter = {
  1036. id: 7,
  1037. name: 'go2rtc Cam',
  1038. serial_number: 'TEST123',
  1039. ip_address: '192.168.1.100',
  1040. access_code: 'XXXX',
  1041. model: 'P1S',
  1042. location: null,
  1043. nozzle_count: 1,
  1044. is_active: true,
  1045. auto_archive: true,
  1046. external_camera_url: 'http://192.168.1.61:1984/api/stream.mjpeg?src=printer',
  1047. external_camera_type: 'mjpeg',
  1048. external_camera_enabled: true,
  1049. external_camera_snapshot_url: null,
  1050. camera_rotation: 0,
  1051. plate_detection_enabled: false,
  1052. created_at: '2026-01-01T00:00:00Z',
  1053. updated_at: '2026-01-01T00:00:00Z',
  1054. };
  1055. it('renders the snapshot URL input when camera_type is mjpeg', async () => {
  1056. server.use(
  1057. http.get('/api/v1/printers/', () => HttpResponse.json([mjpegPrinter])),
  1058. );
  1059. render(<SettingsPage />);
  1060. await waitFor(() => {
  1061. expect(screen.getByPlaceholderText(/api\/frame\.jpeg\?src=printer/)).toBeInTheDocument();
  1062. });
  1063. });
  1064. it('hides the snapshot URL input when camera_type is snapshot (already a single-frame source)', async () => {
  1065. server.use(
  1066. http.get('/api/v1/printers/', () =>
  1067. HttpResponse.json([{ ...mjpegPrinter, external_camera_type: 'snapshot' }]),
  1068. ),
  1069. );
  1070. render(<SettingsPage />);
  1071. // Wait for the live-stream URL placeholder to render so we know the
  1072. // camera section finished mounting before asserting absence of the
  1073. // snapshot input below.
  1074. await waitFor(() => {
  1075. expect(screen.getByPlaceholderText(/Camera URL/i)).toBeInTheDocument();
  1076. });
  1077. expect(screen.queryByPlaceholderText(/api\/frame\.jpeg\?src=printer/)).not.toBeInTheDocument();
  1078. });
  1079. it(
  1080. 'PATCHes the printer with external_camera_snapshot_url when the user types into the input',
  1081. async () => {
  1082. let receivedBody: Record<string, unknown> | null = null;
  1083. server.use(
  1084. http.get('/api/v1/printers/', () => HttpResponse.json([mjpegPrinter])),
  1085. http.patch('/api/v1/printers/7', async ({ request }) => {
  1086. receivedBody = (await request.json()) as Record<string, unknown>;
  1087. return HttpResponse.json({ ...mjpegPrinter, ...receivedBody });
  1088. }),
  1089. );
  1090. render(<SettingsPage />);
  1091. const input = await waitFor(() =>
  1092. screen.getByPlaceholderText(/api\/frame\.jpeg\?src=printer/),
  1093. );
  1094. const user = userEvent.setup();
  1095. await user.type(input, 'http://192.168.1.61:1984/api/frame.jpeg?src=printer');
  1096. // Save is debounced by 800ms; assert the PATCH eventually fires with
  1097. // the typed snapshot URL.
  1098. await waitFor(
  1099. () => {
  1100. expect(receivedBody).not.toBeNull();
  1101. expect(receivedBody!.external_camera_snapshot_url).toBe(
  1102. 'http://192.168.1.61:1984/api/frame.jpeg?src=printer',
  1103. );
  1104. },
  1105. { timeout: 5000 },
  1106. );
  1107. },
  1108. // Per-test timeout raised to 15s — `user.type()` of a 49-char URL plus
  1109. // the 800ms save debounce fits in 5s locally (~2.3s typical) but blows
  1110. // past it on slow GitHub Actions runners (5000ms timeout was the failure
  1111. // mode on PR #1263).
  1112. 15_000,
  1113. );
  1114. });
  1115. describe('theme mode buttons', () => {
  1116. it('renders Dark, Light, and System buttons', async () => {
  1117. render(<SettingsPage />);
  1118. await waitFor(() => {
  1119. expect(screen.getByRole('button', { name: 'Dark' })).toBeInTheDocument();
  1120. expect(screen.getByRole('button', { name: 'Light' })).toBeInTheDocument();
  1121. expect(screen.getByRole('button', { name: 'System' })).toBeInTheDocument();
  1122. });
  1123. });
  1124. it('highlights the active mode button with green border', async () => {
  1125. render(<SettingsPage />);
  1126. const user = userEvent.setup();
  1127. await waitFor(() => {
  1128. expect(screen.getByRole('button', { name: 'System' })).toBeInTheDocument();
  1129. });
  1130. await user.click(screen.getByRole('button', { name: 'System' }));
  1131. await waitFor(() => {
  1132. const systemBtn = screen.getByRole('button', { name: 'System' });
  1133. expect(systemBtn.className).toContain('border-bambu-green');
  1134. });
  1135. });
  1136. it('clicking a theme button switches mode', async () => {
  1137. localStorage.setItem('theme-mode', 'dark');
  1138. render(<SettingsPage />);
  1139. const user = userEvent.setup();
  1140. await waitFor(() => {
  1141. const darkBtn = screen.getByRole('button', { name: 'Dark' });
  1142. expect(darkBtn.className).toContain('border-bambu-green');
  1143. });
  1144. const lightBtn = screen.getByRole('button', { name: 'Light' });
  1145. await user.click(lightBtn);
  1146. await waitFor(() => {
  1147. expect(lightBtn.className).toContain('border-bambu-green');
  1148. });
  1149. });
  1150. it('shows a toast when theme button is clicked', async () => {
  1151. render(<SettingsPage />);
  1152. const user = userEvent.setup();
  1153. await waitFor(() => {
  1154. expect(screen.getByRole('button', { name: 'System' })).toBeInTheDocument();
  1155. });
  1156. await user.click(screen.getByRole('button', { name: 'System' }));
  1157. await waitFor(() => {
  1158. expect(screen.getByText('Settings saved')).toBeInTheDocument();
  1159. });
  1160. });
  1161. });
  1162. // --------------------------------------------------------------------
  1163. // Slicer Pipelines (#1425) — Workflow tab sub-tabs
  1164. // --------------------------------------------------------------------
  1165. describe('workflow sub-tabs (#1425)', () => {
  1166. beforeEach(() => {
  1167. // Endpoints the Pipelines panel calls (#1425).
  1168. server.use(
  1169. http.get('/api/v1/slicer-pipelines/', () => HttpResponse.json({ pipelines: [] })),
  1170. http.get('/api/v1/slicer/presets', () =>
  1171. HttpResponse.json({
  1172. orca_cloud: { printer: [], process: [], filament: [] },
  1173. cloud: { printer: [], process: [], filament: [] },
  1174. local: { printer: [], process: [], filament: [] },
  1175. standard: { printer: [], process: [], filament: [] },
  1176. cloud_status: 'ok',
  1177. orca_cloud_status: 'ok',
  1178. }),
  1179. ),
  1180. );
  1181. });
  1182. it('renders Queue & Dispatch + Pipelines sub-tabs under Workflow', async () => {
  1183. render(<SettingsPage />);
  1184. const user = userEvent.setup();
  1185. await waitFor(() => {
  1186. // Workflow tab in the sidebar — exact match to avoid colliding with
  1187. // "Print Queue" or "Queue Settings" labels elsewhere on the page.
  1188. expect(screen.getByRole('button', { name: 'Workflow' })).toBeInTheDocument();
  1189. });
  1190. await user.click(screen.getByRole('button', { name: 'Workflow' }));
  1191. await waitFor(() => {
  1192. expect(screen.getByRole('button', { name: /Queue & Dispatch/i })).toBeInTheDocument();
  1193. expect(screen.getByRole('button', { name: /^Pipelines$/i })).toBeInTheDocument();
  1194. });
  1195. });
  1196. it('clicking Pipelines sub-tab shows the empty-state hint and updates the URL', async () => {
  1197. render(<SettingsPage />);
  1198. const user = userEvent.setup();
  1199. await waitFor(() => expect(screen.getByRole('button', { name: 'Workflow' })).toBeInTheDocument());
  1200. await user.click(screen.getByRole('button', { name: 'Workflow' }));
  1201. await user.click(screen.getByRole('button', { name: /^Pipelines$/i }));
  1202. await waitFor(() => {
  1203. expect(screen.getByText(/No pipelines yet/i)).toBeInTheDocument();
  1204. // Deep-link URL carries both ?tab=queue and ?sub=pipelines
  1205. expect(window.location.search).toContain('tab=queue');
  1206. expect(window.location.search).toContain('sub=pipelines');
  1207. });
  1208. });
  1209. });
  1210. });
  1211. /**
  1212. * Sponsor banner on Settings -> General.
  1213. *
  1214. * Below the fleet threshold it makes the community/donation ask; at or above it
  1215. * the same slot makes the commercial ask and points at business.html. A print
  1216. * farm asked to chip in $5 is a wasted impression, and a hobbyist pitched a
  1217. * support contract is an annoyed user — so both directions are pinned.
  1218. */
  1219. describe('SettingsPage — sponsor banner audience', () => {
  1220. beforeEach(() => {
  1221. // BrowserRouter shares window.location across tests and the banner only
  1222. // renders on the General tab — without this reset a prior test's ?tab=queue
  1223. // leaks in and the banner never mounts.
  1224. window.history.replaceState({}, '', '/');
  1225. });
  1226. const fleet = (count: number) =>
  1227. server.use(
  1228. http.get('/api/v1/printers/', () =>
  1229. HttpResponse.json(
  1230. Array.from({ length: count }, (_, i) => ({
  1231. id: i + 1,
  1232. name: `Printer ${i + 1}`,
  1233. serial_number: `SN${i + 1}`,
  1234. ip_address: '192.168.1.10',
  1235. model: 'X1C',
  1236. is_active: true,
  1237. })),
  1238. ),
  1239. ),
  1240. );
  1241. it('shows the community ask for a small fleet', async () => {
  1242. fleet(2);
  1243. render(<SettingsPage />);
  1244. const banner = await screen.findByRole('link', { name: /Independent & community-funded/i });
  1245. expect(banner).toHaveAttribute('href', 'https://bambuddy.cool/sponsors.html?from=app-settings');
  1246. expect(screen.queryByText(/Bambuddy for business/i)).not.toBeInTheDocument();
  1247. });
  1248. it('shows the commercial ask for a business-sized fleet', async () => {
  1249. fleet(6);
  1250. render(<SettingsPage />);
  1251. const banner = await screen.findByRole('link', { name: /Bambuddy for business/i });
  1252. expect(banner).toHaveAttribute('href', 'https://bambuddy.cool/business.html?from=app-settings');
  1253. // The donation copy is replaced, not merely supplemented.
  1254. expect(screen.queryByText(/Independent & community-funded/i)).not.toBeInTheDocument();
  1255. // The ask names the fleet back to them.
  1256. expect(screen.getByText(/6 printers/i)).toBeInTheDocument();
  1257. });
  1258. });
  1259. describe('SettingsPage — settings changed outside the page (#2716)', () => {
  1260. const restoreLabel = 'Restore plate for finish photo';
  1261. // external_url is deliberately populated: when the server has none the page
  1262. // detects one from the browser and saves it unprompted, which would show up
  1263. // as a PUT in tests that assert none was made. That behaviour has its own
  1264. // test at the end of this block.
  1265. const baseSettings = { ...mockSettings, external_url: window.location.origin };
  1266. let queryClient: QueryClient;
  1267. let puts: Record<string, unknown>[];
  1268. let served: Record<string, unknown>;
  1269. function renderPage() {
  1270. queryClient = new QueryClient({
  1271. defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false } },
  1272. });
  1273. return rtlRender(
  1274. <QueryClientProvider client={queryClient}>
  1275. <BrowserRouter>
  1276. <AuthProvider>
  1277. <ThemeProvider>
  1278. <ToastProvider>
  1279. <SettingsPage />
  1280. </ToastProvider>
  1281. </ThemeProvider>
  1282. </AuthProvider>
  1283. </BrowserRouter>
  1284. </QueryClientProvider>
  1285. );
  1286. }
  1287. /** Change the settings row server-side and let the page's query observe it. */
  1288. async function changeOnServer(patch: Record<string, unknown>) {
  1289. served = { ...served, ...patch };
  1290. await act(async () => {
  1291. await queryClient.invalidateQueries({ queryKey: ['settings'] });
  1292. });
  1293. }
  1294. /** Wait out the 100ms initial-load suppression, then flip a checkbox. */
  1295. async function toggleRestorePlate() {
  1296. const label = await screen.findByText(restoreLabel);
  1297. await new Promise((resolve) => setTimeout(resolve, 200));
  1298. const row = label.closest('div')!.parentElement!;
  1299. await userEvent.click(within(row).getByRole('checkbox'));
  1300. }
  1301. beforeEach(() => {
  1302. window.history.replaceState({}, '', '/');
  1303. localStorage.clear();
  1304. setAuthToken(null);
  1305. puts = [];
  1306. served = { ...baseSettings };
  1307. server.use(
  1308. http.get('/api/v1/settings/', () => HttpResponse.json(served)),
  1309. http.put('/api/v1/settings/', async ({ request }) => {
  1310. const body = (await request.json()) as Record<string, unknown>;
  1311. puts.push(body);
  1312. served = { ...served, ...body };
  1313. return HttpResponse.json(served);
  1314. })
  1315. );
  1316. });
  1317. it('does not write its stale copy back over a server-side change', async () => {
  1318. // The defect: the page diffed the live query cache against its own copy, so
  1319. // a refetch that carried someone else's change read as a local edit and was
  1320. // reverted ~500ms later with no user interaction at all.
  1321. renderPage();
  1322. await screen.findByText(restoreLabel);
  1323. await new Promise((resolve) => setTimeout(resolve, 200));
  1324. await changeOnServer({ currency: 'EUR' });
  1325. // Well past the 500ms debounce.
  1326. await new Promise((resolve) => setTimeout(resolve, 1200));
  1327. expect(puts).toEqual([]);
  1328. });
  1329. it('adopts the server value, so a later save carries it rather than the stale one', async () => {
  1330. renderPage();
  1331. await new Promise((resolve) => setTimeout(resolve, 200));
  1332. await changeOnServer({ currency: 'EUR' });
  1333. await toggleRestorePlate();
  1334. await waitFor(() => expect(puts).toHaveLength(1), { timeout: 3000 });
  1335. // The user's edit is saved...
  1336. expect(puts[0].finish_photo_restore_plate).toBe(false);
  1337. // ...and the field they never touched goes back as the server's value, not
  1338. // the USD the page loaded with.
  1339. expect(puts[0].currency).toBe('EUR');
  1340. });
  1341. it('never reverts a pending user edit that the server changed too', async () => {
  1342. renderPage();
  1343. await toggleRestorePlate();
  1344. // Lands while the edit is still sitting in the 500ms debounce, i.e. before
  1345. // the page has committed it. Adopting the server's value here would throw
  1346. // the edit away silently.
  1347. await changeOnServer({ finish_photo_restore_plate: true });
  1348. await waitFor(() => expect(puts.length).toBeGreaterThan(0), { timeout: 3000 });
  1349. await new Promise((resolve) => setTimeout(resolve, 1200));
  1350. // Asserted over every request rather than a particular one: whichever order
  1351. // the refetch and the debounce happen to land in, no write may carry the
  1352. // server's value back over the user's.
  1353. expect(puts.map((p) => p.finish_photo_restore_plate)).toEqual(puts.map(() => false));
  1354. });
  1355. it('saves once per edit — the baseline moves with the saved row', async () => {
  1356. // Guards the failure mode the baseline introduces if it is not advanced on
  1357. // save: every render would diff against the pre-save snapshot and re-send.
  1358. renderPage();
  1359. await toggleRestorePlate();
  1360. await waitFor(() => expect(puts).toHaveLength(1), { timeout: 3000 });
  1361. await new Promise((resolve) => setTimeout(resolve, 1500));
  1362. expect(puts).toHaveLength(1);
  1363. });
  1364. it('still persists the external_url it detects from the browser', async () => {
  1365. // The page seeds external_url from window.location.origin when the server
  1366. // has none and relies on the auto-save to persist it. That only works
  1367. // because the baseline is the raw server row: seed the baseline from the
  1368. // adjusted copy instead and the detected URL matches it, so nothing ever
  1369. // marks it as needing a save.
  1370. served = { ...mockSettings };
  1371. renderPage();
  1372. await screen.findByText(restoreLabel);
  1373. await new Promise((resolve) => setTimeout(resolve, 200));
  1374. // A refetch carrying a field this page does not manage. It is enough to
  1375. // re-run the diff, and the only thing that differs is the detected URL.
  1376. await changeOnServer({ spoolman_url: 'http://spoolman.example' });
  1377. await waitFor(() => expect(puts).toHaveLength(1), { timeout: 3000 });
  1378. expect(puts[0].external_url).toBe(window.location.origin);
  1379. });
  1380. });