SettingsPage.test.tsx 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. /**
  2. * Tests for the SettingsPage component.
  3. */
  4. import { describe, it, expect, beforeEach, vi } from 'vitest';
  5. import { fireEvent, screen, waitFor, within } from '@testing-library/react';
  6. import userEvent from '@testing-library/user-event';
  7. import { render } from '../utils';
  8. import { SettingsPage } from '../../pages/SettingsPage';
  9. import { http, HttpResponse } from 'msw';
  10. import { server } from '../mocks/server';
  11. import { SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, SIDEBAR_ORDER_KEY } from '../../utils/sidebarLayout';
  12. import { setAuthToken } from '../../api/client';
  13. const mockSettings = {
  14. auto_archive: true,
  15. save_thumbnails: true,
  16. capture_finish_photo: true,
  17. default_filament_cost: 25.0,
  18. currency: 'USD',
  19. ams_humidity_good: 40,
  20. ams_humidity_fair: 60,
  21. ams_temp_good: 30,
  22. ams_temp_fair: 35,
  23. time_format: 'system',
  24. date_format: 'system',
  25. mqtt_enabled: false,
  26. mqtt_host: '',
  27. mqtt_port: 1883,
  28. spoolman_enabled: false,
  29. spoolman_url: '',
  30. ha_enabled: false,
  31. ha_url: '',
  32. ha_token: '',
  33. check_updates: false,
  34. check_printer_firmware: false,
  35. bed_cooled_threshold: 35,
  36. };
  37. describe('SettingsPage', () => {
  38. beforeEach(() => {
  39. // BrowserRouter shares window.location across tests; reset it so a tab
  40. // switch in one test (e.g. clicking "Workflow") doesn't carry into
  41. // sibling tests that expect to land on the default General tab.
  42. window.history.replaceState({}, '', '/');
  43. vi.mocked(localStorage.getItem).mockReset();
  44. vi.mocked(localStorage.setItem).mockReset();
  45. vi.mocked(localStorage.removeItem).mockReset();
  46. vi.mocked(localStorage.clear).mockReset();
  47. localStorage.clear();
  48. setAuthToken(null);
  49. server.use(
  50. http.get('/api/v1/settings/', () => {
  51. return HttpResponse.json(mockSettings);
  52. }),
  53. http.put('/api/v1/settings/', async ({ request }) => {
  54. const body = await request.json();
  55. return HttpResponse.json({ ...mockSettings, ...body });
  56. }),
  57. http.get('/api/v1/printers/', () => {
  58. return HttpResponse.json([]);
  59. }),
  60. http.get('/api/v1/smart-plugs/', () => {
  61. return HttpResponse.json([]);
  62. }),
  63. http.get('/api/v1/notifications/', () => {
  64. return HttpResponse.json([]);
  65. }),
  66. http.get('/api/v1/api-keys/', () => {
  67. return HttpResponse.json([]);
  68. }),
  69. http.get('/api/v1/mqtt/status', () => {
  70. return HttpResponse.json({ enabled: false });
  71. }),
  72. http.get('/api/v1/virtual-printer/status', () => {
  73. return HttpResponse.json({ running: false });
  74. }),
  75. http.get('/api/v1/auth/status', () => {
  76. return HttpResponse.json({ auth_enabled: false, requires_setup: false });
  77. }),
  78. http.get('/api/v1/external-links/', () => {
  79. return HttpResponse.json([]);
  80. })
  81. );
  82. });
  83. describe('rendering', () => {
  84. it('renders the page title', async () => {
  85. render(<SettingsPage />);
  86. await waitFor(() => {
  87. // Use role-based query to avoid conflicts with dropdown options
  88. expect(screen.getByRole('heading', { name: 'Settings' })).toBeInTheDocument();
  89. });
  90. });
  91. it('shows settings tabs', async () => {
  92. render(<SettingsPage />);
  93. await waitFor(() => {
  94. // Use getAllByText since "General" appears both as tab and section heading
  95. expect(screen.getAllByText('General').length).toBeGreaterThan(0);
  96. expect(screen.getByText('Smart Plugs')).toBeInTheDocument();
  97. expect(screen.getAllByText('Notifications').length).toBeGreaterThan(0);
  98. expect(screen.getAllByText('Filament').length).toBeGreaterThan(0);
  99. expect(screen.getByText('Network')).toBeInTheDocument();
  100. expect(screen.getByText('API Keys')).toBeInTheDocument();
  101. });
  102. });
  103. });
  104. describe('general settings', () => {
  105. it('shows date format setting', async () => {
  106. render(<SettingsPage />);
  107. await waitFor(() => {
  108. expect(screen.getByText('Date Format')).toBeInTheDocument();
  109. });
  110. });
  111. it('shows time format setting', async () => {
  112. render(<SettingsPage />);
  113. await waitFor(() => {
  114. expect(screen.getByText('Time Format')).toBeInTheDocument();
  115. });
  116. });
  117. it('shows default printer setting', async () => {
  118. render(<SettingsPage />);
  119. await waitFor(() => {
  120. expect(screen.getByText('Default Printer')).toBeInTheDocument();
  121. });
  122. });
  123. it('shows preferred slicer setting on Workflow tab', async () => {
  124. const user = userEvent.setup();
  125. render(<SettingsPage />);
  126. await waitFor(() => {
  127. expect(screen.getByText('Workflow')).toBeInTheDocument();
  128. });
  129. await user.click(screen.getByText('Workflow'));
  130. await waitFor(() => {
  131. expect(screen.getByText('Preferred Slicer')).toBeInTheDocument();
  132. });
  133. });
  134. it('shows slicer dropdown with both options on Workflow tab', async () => {
  135. const user = userEvent.setup();
  136. render(<SettingsPage />);
  137. await waitFor(() => {
  138. expect(screen.getByText('Workflow')).toBeInTheDocument();
  139. });
  140. await user.click(screen.getByText('Workflow'));
  141. await waitFor(() => {
  142. const slicerSelect = screen.getAllByDisplayValue('Bambu Studio');
  143. expect(slicerSelect.length).toBeGreaterThan(0);
  144. });
  145. });
  146. it('shows appearance section', async () => {
  147. render(<SettingsPage />);
  148. await waitFor(() => {
  149. expect(screen.getByText('Appearance')).toBeInTheDocument();
  150. });
  151. });
  152. it('shows updates section with firmware toggle', async () => {
  153. render(<SettingsPage />);
  154. await waitFor(() => {
  155. expect(screen.getByText('Updates')).toBeInTheDocument();
  156. expect(screen.getByText('Check for updates')).toBeInTheDocument();
  157. expect(screen.getByText('Check printer firmware')).toBeInTheDocument();
  158. });
  159. });
  160. it('hides a Bambuddy sidebar page from Sidebar', async () => {
  161. const user = userEvent.setup();
  162. render(<SettingsPage />);
  163. await screen.findByRole('heading', { name: 'Sidebar' });
  164. await screen.findAllByText('Visible in sidebar');
  165. vi.mocked(localStorage.setItem).mockClear();
  166. await user.click((await screen.findAllByLabelText('Hide page'))[0]);
  167. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, JSON.stringify(['printers']));
  168. expect(screen.getByText('Hidden from sidebar')).toBeInTheDocument();
  169. });
  170. it('shows a previously hidden Bambuddy sidebar page from Sidebar', async () => {
  171. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  172. if (key === SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY) return JSON.stringify(['printers']);
  173. return null;
  174. });
  175. const user = userEvent.setup();
  176. render(<SettingsPage />);
  177. await screen.findByRole('heading', { name: 'Sidebar' });
  178. await screen.findByText('Hidden from sidebar');
  179. vi.mocked(localStorage.setItem).mockClear();
  180. await user.click(await screen.findByLabelText('Show page'));
  181. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, JSON.stringify([]));
  182. expect(screen.getAllByText('Visible in sidebar').length).toBeGreaterThan(0);
  183. });
  184. it('does not allow Settings to be hidden from Sidebar', async () => {
  185. render(<SettingsPage />);
  186. await screen.findByRole('heading', { name: 'Sidebar' });
  187. await screen.findByText('Required in sidebar');
  188. const settingsVisibilityButton = await screen.findByLabelText('Settings cannot be hidden');
  189. expect(settingsVisibilityButton).toBeDisabled();
  190. expect(screen.getByText('Required in sidebar')).toBeInTheDocument();
  191. });
  192. it('presents external links and Bambuddy pages in saved sidebar order', async () => {
  193. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  194. if (key === SIDEBAR_ORDER_KEY) return JSON.stringify(['ext-7', 'printers', 'settings']);
  195. return null;
  196. });
  197. server.use(
  198. http.get('/api/v1/external-links/', () =>
  199. HttpResponse.json([
  200. {
  201. id: 7,
  202. name: 'Docs',
  203. url: 'https://docs.example.test',
  204. icon: 'Link',
  205. open_in_new_tab: true,
  206. custom_icon: null,
  207. sort_order: 0,
  208. created_at: '2026-01-01T00:00:00Z',
  209. updated_at: '2026-01-01T00:00:00Z',
  210. },
  211. ]),
  212. ),
  213. );
  214. render(<SettingsPage />);
  215. await screen.findByRole('heading', { name: 'Sidebar' });
  216. const docs = await screen.findByText('Docs');
  217. const printers = screen.getAllByText('Printers').find(element => element.closest('[draggable="true"]'));
  218. expect(printers).toBeDefined();
  219. expect(docs.compareDocumentPosition(printers) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
  220. });
  221. it('saves mixed Sidebar order when items are dragged', async () => {
  222. server.use(
  223. http.get('/api/v1/external-links/', () =>
  224. HttpResponse.json([
  225. {
  226. id: 7,
  227. name: 'Docs',
  228. url: 'https://docs.example.test',
  229. icon: 'Link',
  230. open_in_new_tab: true,
  231. custom_icon: null,
  232. sort_order: 0,
  233. created_at: '2026-01-01T00:00:00Z',
  234. updated_at: '2026-01-01T00:00:00Z',
  235. },
  236. ]),
  237. ),
  238. );
  239. render(<SettingsPage />);
  240. await screen.findByRole('heading', { name: 'Sidebar' });
  241. const docsRow = (await screen.findByText('Docs')).closest('[draggable="true"]');
  242. const printersRow = screen.getAllByText('Printers')
  243. .find(element => element.closest('[draggable="true"]'))
  244. ?.closest('[draggable="true"]');
  245. expect(docsRow).not.toBeNull();
  246. expect(printersRow).not.toBeNull();
  247. vi.mocked(localStorage.setItem).mockClear();
  248. const dataTransfer = {
  249. effectAllowed: '',
  250. dropEffect: '',
  251. setData: vi.fn(),
  252. };
  253. fireEvent.dragStart(docsRow!, { dataTransfer });
  254. fireEvent.dragOver(printersRow!, { dataTransfer });
  255. fireEvent.drop(printersRow!, { dataTransfer });
  256. expect(localStorage.setItem).toHaveBeenCalledWith(
  257. SIDEBAR_ORDER_KEY,
  258. JSON.stringify(['ext-7', 'printers', 'inventory', 'archives', 'queue', 'projects', 'files', 'makerworld', 'profiles', 'maintenance', 'stats', 'settings']),
  259. );
  260. });
  261. it('resets Sidebar to all pages first and configured links at the bottom', async () => {
  262. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  263. if (key === SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY) return JSON.stringify(['printers', 'stats']);
  264. if (key === SIDEBAR_ORDER_KEY) return JSON.stringify(['ext-7', 'settings', 'printers']);
  265. return null;
  266. });
  267. server.use(
  268. http.get('/api/v1/external-links/', () =>
  269. HttpResponse.json([
  270. {
  271. id: 7,
  272. name: 'Docs',
  273. url: 'https://docs.example.test',
  274. icon: 'Link',
  275. open_in_new_tab: true,
  276. custom_icon: null,
  277. sort_order: 0,
  278. created_at: '2026-01-01T00:00:00Z',
  279. updated_at: '2026-01-01T00:00:00Z',
  280. },
  281. ]),
  282. ),
  283. );
  284. const user = userEvent.setup();
  285. render(<SettingsPage />);
  286. const heading = await screen.findByRole('heading', { name: 'Sidebar' });
  287. const card = heading.closest('#card-sidebar-links');
  288. expect(card).not.toBeNull();
  289. await screen.findByText('Docs');
  290. vi.mocked(localStorage.setItem).mockClear();
  291. await user.click(within(card as HTMLElement).getByRole('button', { name: /reset/i }));
  292. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, JSON.stringify([]));
  293. expect(localStorage.setItem).toHaveBeenCalledWith(
  294. SIDEBAR_ORDER_KEY,
  295. JSON.stringify(['printers', 'inventory', 'archives', 'queue', 'projects', 'files', 'makerworld', 'profiles', 'maintenance', 'stats', 'settings', 'ext-7']),
  296. );
  297. const settingsRow = screen.getAllByText('Settings')
  298. .find(element => element.closest('[draggable="true"]'))
  299. ?.closest('[draggable="true"]');
  300. const docsRow = screen.getByText('Docs').closest('[draggable="true"]');
  301. expect(settingsRow).not.toBeNull();
  302. expect(docsRow).not.toBeNull();
  303. expect(settingsRow!.compareDocumentPosition(docsRow!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
  304. expect(screen.queryByText('Hidden from sidebar')).not.toBeInTheDocument();
  305. });
  306. it('sets the current Sidebar order as the backend default for settings admins', async () => {
  307. let defaultSidebarOrderPayload: string | null = null;
  308. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  309. if (key === SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY) return JSON.stringify(['stats']);
  310. return null;
  311. });
  312. server.use(
  313. http.get('/api/v1/auth/status', () =>
  314. HttpResponse.json({ auth_enabled: true, requires_setup: false }),
  315. ),
  316. http.get('/api/v1/auth/me', () =>
  317. HttpResponse.json({
  318. id: 1,
  319. username: 'admin',
  320. role: 'admin',
  321. is_active: true,
  322. is_admin: false,
  323. groups: [{ id: 1, name: 'Administrators' }],
  324. permissions: ['settings:update'],
  325. created_at: '2026-01-01T00:00:00Z',
  326. }),
  327. ),
  328. http.get('/api/v1/settings/', () =>
  329. HttpResponse.json({ ...mockSettings, default_sidebar_order: '' }),
  330. ),
  331. http.put('/api/v1/settings/', async ({ request }) => {
  332. const body = await request.json() as { default_sidebar_order?: string };
  333. defaultSidebarOrderPayload = body.default_sidebar_order ?? null;
  334. return HttpResponse.json({ ...mockSettings, ...body });
  335. }),
  336. );
  337. setAuthToken('test-token');
  338. const user = userEvent.setup();
  339. render(<SettingsPage />);
  340. const heading = await screen.findByRole('heading', { name: 'Sidebar' });
  341. const card = heading.closest('#card-sidebar-links');
  342. expect(card).not.toBeNull();
  343. await user.click(within(card as HTMLElement).getByRole('switch', { name: 'Set Default' }));
  344. await waitFor(() => {
  345. expect(defaultSidebarOrderPayload).not.toBeNull();
  346. });
  347. expect(JSON.parse(defaultSidebarOrderPayload!)).toEqual({
  348. order: [
  349. 'printers',
  350. 'inventory',
  351. 'archives',
  352. 'queue',
  353. 'projects',
  354. 'files',
  355. 'makerworld',
  356. 'profiles',
  357. 'maintenance',
  358. 'stats',
  359. 'settings',
  360. ],
  361. hiddenSystemItemIds: ['stats'],
  362. });
  363. });
  364. });
  365. describe('update CTA per deployment shape', () => {
  366. // The update card branches on the deployment shape returned by
  367. // /updates/check. Each branch is mutually exclusive — verify the right
  368. // one wins so HA addon users never see the docker-compose snippet
  369. // (which they can't run from inside an HA addon container) and Docker
  370. // users never see the in-app Install button (which would no-op).
  371. const renderWithUpdateCheck = async (
  372. checkBody: Record<string, unknown>,
  373. ) => {
  374. server.use(
  375. http.get('/api/v1/settings/', () =>
  376. HttpResponse.json({ ...mockSettings, check_updates: true }),
  377. ),
  378. http.get('/api/v1/updates/check', () => HttpResponse.json(checkBody)),
  379. );
  380. render(<SettingsPage />);
  381. await waitFor(() => {
  382. expect(screen.getByText('Updates')).toBeInTheDocument();
  383. });
  384. };
  385. it('shows the HA Supervisor message when running as an HA addon', async () => {
  386. await renderWithUpdateCheck({
  387. update_available: true,
  388. current_version: '0.2.4',
  389. latest_version: '0.2.5',
  390. release_name: '0.2.5',
  391. release_notes: '',
  392. release_url: 'https://example.invalid/r',
  393. published_at: '2099-01-01T00:00:00Z',
  394. is_docker: true,
  395. is_ha_addon: true,
  396. update_method: 'ha_addon',
  397. });
  398. await waitFor(() => {
  399. expect(
  400. screen.getByText(/Home Assistant Supervisor/i),
  401. ).toBeInTheDocument();
  402. });
  403. // Docker hint must NOT render — HA branch wins.
  404. expect(screen.queryByText('docker compose pull && docker compose up -d')).not.toBeInTheDocument();
  405. expect(screen.queryByRole('button', { name: /install update/i })).not.toBeInTheDocument();
  406. });
  407. it('shows the docker-compose snippet for Docker (non-HA) deployments', async () => {
  408. await renderWithUpdateCheck({
  409. update_available: true,
  410. current_version: '0.2.4',
  411. latest_version: '0.2.5',
  412. release_name: '0.2.5',
  413. release_notes: '',
  414. release_url: 'https://example.invalid/r',
  415. published_at: '2099-01-01T00:00:00Z',
  416. is_docker: true,
  417. is_ha_addon: false,
  418. update_method: 'docker',
  419. });
  420. await waitFor(() => {
  421. expect(screen.getByText('docker compose pull && docker compose up -d')).toBeInTheDocument();
  422. });
  423. expect(screen.queryByText(/Home Assistant Supervisor/i)).not.toBeInTheDocument();
  424. expect(screen.queryByRole('button', { name: /install update/i })).not.toBeInTheDocument();
  425. });
  426. it('shows the installer-download link for Windows installer installs', async () => {
  427. const downloadUrl =
  428. 'https://github.com/maziggy/bambuddy/releases/download/v0.2.5/bambuddy-0.2.5-windows-x64-setup.exe';
  429. await renderWithUpdateCheck({
  430. update_available: true,
  431. current_version: '0.2.4',
  432. latest_version: '0.2.5',
  433. release_name: '0.2.5',
  434. release_notes: '',
  435. release_url: 'https://github.com/maziggy/bambuddy/releases/tag/v0.2.5',
  436. published_at: '2099-01-01T00:00:00Z',
  437. is_docker: false,
  438. is_ha_addon: false,
  439. is_windows_installer: true,
  440. update_method: 'windows_installer',
  441. installer_download_url: downloadUrl,
  442. });
  443. const link = await screen.findByRole('link', { name: /download installer for v0\.2\.5/i });
  444. expect(link).toHaveAttribute('href', downloadUrl);
  445. expect(link).toHaveAttribute('target', '_blank');
  446. expect(link).toHaveAttribute('rel', expect.stringContaining('noopener'));
  447. // The in-app update button must NOT render — the git-fetch path can't
  448. // work from an installer payload.
  449. expect(screen.queryByRole('button', { name: /install update/i })).not.toBeInTheDocument();
  450. expect(screen.queryByText(/Home Assistant Supervisor/i)).not.toBeInTheDocument();
  451. expect(screen.queryByText('docker compose pull && docker compose up -d')).not.toBeInTheDocument();
  452. });
  453. });
  454. describe('tabs navigation', () => {
  455. it('can switch to Network tab', async () => {
  456. const user = userEvent.setup();
  457. render(<SettingsPage />);
  458. // Wait for settings to load first
  459. await waitFor(() => {
  460. expect(screen.getByText('Date Format')).toBeInTheDocument();
  461. });
  462. await user.click(screen.getByText('Network'));
  463. await waitFor(() => {
  464. // Network tab contains MQTT Publishing section
  465. expect(screen.getByText('MQTT Publishing')).toBeInTheDocument();
  466. });
  467. });
  468. it('can switch to Smart Plugs tab', async () => {
  469. const user = userEvent.setup();
  470. render(<SettingsPage />);
  471. await waitFor(() => {
  472. expect(screen.getByText('Smart Plugs')).toBeInTheDocument();
  473. });
  474. await user.click(screen.getByText('Smart Plugs'));
  475. await waitFor(() => {
  476. expect(screen.getByText('Add Smart Plug')).toBeInTheDocument();
  477. });
  478. });
  479. it('can switch to Notifications tab', async () => {
  480. const user = userEvent.setup();
  481. render(<SettingsPage />);
  482. await waitFor(() => {
  483. expect(screen.getAllByText('Notifications').length).toBeGreaterThan(0);
  484. });
  485. // Click the tab button (not the mobile dropdown option)
  486. const notificationButtons = screen.getAllByText('Notifications');
  487. const tabButton = notificationButtons.find(el => el.tagName === 'BUTTON') || notificationButtons[0];
  488. await user.click(tabButton);
  489. await waitFor(() => {
  490. expect(screen.getByText('Add Provider')).toBeInTheDocument();
  491. });
  492. });
  493. it('can switch to Filament tab', async () => {
  494. const user = userEvent.setup();
  495. render(<SettingsPage />);
  496. await waitFor(() => {
  497. expect(screen.getAllByText('Filament').length).toBeGreaterThan(0);
  498. });
  499. await user.click(screen.getAllByText('Filament')[0]);
  500. await waitFor(() => {
  501. expect(screen.getByText('AMS Display Thresholds')).toBeInTheDocument();
  502. });
  503. });
  504. });
  505. describe('Workflow tab', () => {
  506. it('can switch to Workflow tab', async () => {
  507. const user = userEvent.setup();
  508. render(<SettingsPage />);
  509. await waitFor(() => {
  510. expect(screen.getByText('Workflow')).toBeInTheDocument();
  511. });
  512. await user.click(screen.getByText('Workflow'));
  513. await waitFor(() => {
  514. expect(screen.getByText('Staggered Start')).toBeInTheDocument();
  515. });
  516. });
  517. it('shows stagger settings on Workflow tab', async () => {
  518. const user = userEvent.setup();
  519. render(<SettingsPage />);
  520. await waitFor(() => {
  521. expect(screen.getByText('Workflow')).toBeInTheDocument();
  522. });
  523. await user.click(screen.getByText('Workflow'));
  524. await waitFor(() => {
  525. expect(screen.getByText('Staggered Start')).toBeInTheDocument();
  526. expect(screen.getByText('Group size')).toBeInTheDocument();
  527. expect(screen.getByText('Interval (minutes)')).toBeInTheDocument();
  528. });
  529. });
  530. it('shows auto-drying settings on Workflow tab', async () => {
  531. const user = userEvent.setup();
  532. render(<SettingsPage />);
  533. await waitFor(() => {
  534. expect(screen.getByText('Workflow')).toBeInTheDocument();
  535. });
  536. await user.click(screen.getByText('Workflow'));
  537. await waitFor(() => {
  538. expect(screen.getByText('Queue Auto-Drying')).toBeInTheDocument();
  539. });
  540. });
  541. it('shows per-filament humidity threshold editor on Workflow tab (#1605)', async () => {
  542. const user = userEvent.setup();
  543. render(<SettingsPage />);
  544. await waitFor(() => {
  545. expect(screen.getByText('Workflow')).toBeInTheDocument();
  546. });
  547. await user.click(screen.getByText('Workflow'));
  548. await waitFor(() => {
  549. expect(screen.getByText('Humidity Thresholds')).toBeInTheDocument();
  550. // Default row is unique to the humidity editor (drying presets has no
  551. // default row), so we can pin it without disambiguating from the
  552. // adjacent drying-presets table that also lists PLA/ASA/etc.
  553. expect(screen.getByText('Default (unknown types)')).toBeInTheDocument();
  554. // Filament rows render in both tables — assert by count instead of
  555. // a single getByText. 8 default filaments × 2 tables = 16 PLAs etc.
  556. expect(screen.getAllByText('PLA').length).toBeGreaterThanOrEqual(2);
  557. expect(screen.getAllByText('ASA').length).toBeGreaterThanOrEqual(2);
  558. });
  559. });
  560. it('shows default print options on Workflow tab', async () => {
  561. const user = userEvent.setup();
  562. render(<SettingsPage />);
  563. await waitFor(() => {
  564. expect(screen.getByText('Workflow')).toBeInTheDocument();
  565. });
  566. await user.click(screen.getByText('Workflow'));
  567. await waitFor(() => {
  568. expect(screen.getByText('Default Print Options')).toBeInTheDocument();
  569. expect(screen.getByText('Bed Levelling')).toBeInTheDocument();
  570. expect(screen.getByText('Flow Calibration')).toBeInTheDocument();
  571. expect(screen.getByText('Vibration Calibration')).toBeInTheDocument();
  572. expect(screen.getByText('First Layer Inspection')).toBeInTheDocument();
  573. expect(screen.getByText('Timelapse')).toBeInTheDocument();
  574. });
  575. });
  576. it('shows default print options description', async () => {
  577. const user = userEvent.setup();
  578. render(<SettingsPage />);
  579. await waitFor(() => {
  580. expect(screen.getByText('Workflow')).toBeInTheDocument();
  581. });
  582. await user.click(screen.getByText('Workflow'));
  583. await waitFor(() => {
  584. expect(screen.getByText(/overridden per print in the print dialog/)).toBeInTheDocument();
  585. });
  586. });
  587. });
  588. describe('API Keys tab', () => {
  589. it('can switch to API Keys tab', async () => {
  590. const user = userEvent.setup();
  591. render(<SettingsPage />);
  592. await waitFor(() => {
  593. expect(screen.getByText('API Keys')).toBeInTheDocument();
  594. });
  595. await user.click(screen.getByText('API Keys'));
  596. await waitFor(() => {
  597. // Button text is "Create Key"
  598. expect(screen.getByText('Create Key')).toBeInTheDocument();
  599. });
  600. });
  601. });
  602. describe('SpoolBuddy tab badge', () => {
  603. const baseDevice = {
  604. id: 1,
  605. device_id: 'sb-0001',
  606. hostname: 'sb-kitchen',
  607. ip_address: '10.0.0.1',
  608. backend_url: null,
  609. firmware_version: '1.0.0',
  610. has_nfc: true,
  611. has_scale: true,
  612. tare_offset: 0,
  613. calibration_factor: 1.0,
  614. nfc_reader_type: null,
  615. nfc_connection: null,
  616. display_brightness: 100,
  617. display_blank_timeout: 0,
  618. has_backlight: false,
  619. last_calibrated_at: null,
  620. last_seen: new Date().toISOString(),
  621. pending_command: null,
  622. nfc_ok: true,
  623. scale_ok: true,
  624. uptime_s: 100,
  625. update_status: null,
  626. update_message: null,
  627. system_stats: null,
  628. online: true,
  629. created_at: '2024-01-01T00:00:00Z',
  630. updated_at: '2024-01-01T00:00:00Z',
  631. };
  632. it('shows device count and green bullet when at least one device is online', async () => {
  633. server.use(
  634. http.get('/api/v1/spoolbuddy/devices', () => {
  635. return HttpResponse.json([
  636. { ...baseDevice, id: 1, device_id: 'sb-0001', hostname: 'sb-kitchen', online: true },
  637. { ...baseDevice, id: 2, device_id: 'sb-0002', hostname: 'sb-ghost', online: false },
  638. ]);
  639. })
  640. );
  641. render(<SettingsPage />);
  642. // Find the tab button (not the header) — it's the <button> containing the SpoolBuddy text
  643. const tabButton = await waitFor(() => {
  644. const buttons = screen.getAllByRole('button').filter((b) => b.textContent?.includes('SpoolBuddy'));
  645. expect(buttons.length).toBeGreaterThan(0);
  646. return buttons[0];
  647. });
  648. // Count pill rendered
  649. await waitFor(() => {
  650. expect(tabButton.textContent).toContain('2');
  651. });
  652. // Green status bullet (at least one device online)
  653. await waitFor(() => {
  654. expect(tabButton.querySelector('.bg-green-400')).not.toBeNull();
  655. });
  656. });
  657. it('shows gray bullet when all devices are offline', async () => {
  658. server.use(
  659. http.get('/api/v1/spoolbuddy/devices', () => {
  660. return HttpResponse.json([{ ...baseDevice, online: false }]);
  661. })
  662. );
  663. render(<SettingsPage />);
  664. const tabButton = await waitFor(() => {
  665. const buttons = screen.getAllByRole('button').filter((b) => b.textContent?.includes('SpoolBuddy'));
  666. expect(buttons.length).toBeGreaterThan(0);
  667. return buttons[0];
  668. });
  669. await waitFor(() => {
  670. expect(tabButton.querySelector('.bg-gray-500')).not.toBeNull();
  671. expect(tabButton.querySelector('.bg-green-400')).toBeNull();
  672. });
  673. });
  674. it('hides the count pill when no devices are registered', async () => {
  675. server.use(
  676. http.get('/api/v1/spoolbuddy/devices', () => HttpResponse.json([]))
  677. );
  678. render(<SettingsPage />);
  679. const tabButton = await waitFor(() => {
  680. const buttons = screen.getAllByRole('button').filter((b) => b.textContent?.includes('SpoolBuddy'));
  681. expect(buttons.length).toBeGreaterThan(0);
  682. return buttons[0];
  683. });
  684. // The only numeric content should NOT be present — tab label only
  685. await waitFor(() => {
  686. expect(tabButton.textContent).toBe('SpoolBuddy');
  687. });
  688. });
  689. });
  690. describe('API Keys tab — delete flow', () => {
  691. // Without setQueryData on success the deleted row stayed visible until a
  692. // manual reload — invalidateQueries didn't reliably trigger a UI swap on
  693. // every browser. Pin the synchronous-removal contract here.
  694. it('removes a deleted key from the list without a page reload', async () => {
  695. const initialKeys = [
  696. {
  697. id: 42,
  698. name: 'CI deploy key',
  699. key_prefix: 'bk_abcd1234',
  700. can_queue: true,
  701. can_control_printer: false,
  702. can_read_status: true,
  703. printer_ids: null,
  704. enabled: true,
  705. last_used: null,
  706. created_at: '2026-01-01T00:00:00Z',
  707. expires_at: null,
  708. },
  709. ];
  710. let deleteCallCount = 0;
  711. server.use(
  712. http.get('/api/v1/api-keys/', () => HttpResponse.json(initialKeys)),
  713. http.delete('/api/v1/api-keys/:id', ({ params }) => {
  714. deleteCallCount += 1;
  715. expect(params.id).toBe('42');
  716. return HttpResponse.json({ message: 'API key deleted' });
  717. })
  718. );
  719. const user = userEvent.setup();
  720. render(<SettingsPage />);
  721. // Switch to API Keys tab. Both desktop tab + mobile dropdown render
  722. // the label, so just grab the button form.
  723. await waitFor(() => {
  724. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  725. });
  726. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  727. expect(tabButton).toBeDefined();
  728. await user.click(tabButton!);
  729. // Key is listed
  730. await waitFor(() => {
  731. expect(screen.getByText('CI deploy key')).toBeInTheDocument();
  732. });
  733. // Click the trash button on the row
  734. const cards = screen.getByText('CI deploy key').closest('.flex.items-center.justify-between');
  735. expect(cards).not.toBeNull();
  736. const trashButton = cards!.querySelectorAll('button');
  737. await user.click(trashButton[trashButton.length - 1]);
  738. // Confirm the deletion in the modal
  739. const confirmButton = await screen.findByRole('button', { name: /delete/i });
  740. await user.click(confirmButton);
  741. // The deleted key disappears from the list immediately — no manual
  742. // reload required. setQueryData drops it before any refetch could fire.
  743. await waitFor(() => {
  744. expect(screen.queryByText('CI deploy key')).not.toBeInTheDocument();
  745. });
  746. expect(deleteCallCount).toBe(1);
  747. });
  748. });
  749. describe('API Keys tab — #1182 cloud access + ownership UI', () => {
  750. // The list now exposes two new bits of information per row:
  751. // - "Cloud" badge when can_access_cloud=true
  752. // - "Legacy" badge when user_id IS NULL (created before per-user ownership)
  753. // These tell the operator at a glance which keys can read /cloud/* data
  754. // and which keys need to be recreated to gain that capability.
  755. it('renders the Cloud badge for keys with can_access_cloud=true and the Legacy badge for ownerless keys', async () => {
  756. const keys = [
  757. {
  758. id: 1,
  759. name: 'cloud-reader',
  760. key_prefix: 'bk_cloud123',
  761. user_id: 7,
  762. can_queue: false,
  763. can_control_printer: false,
  764. can_read_status: true,
  765. can_access_cloud: true,
  766. printer_ids: null,
  767. enabled: true,
  768. last_used: null,
  769. created_at: '2026-04-30T00:00:00Z',
  770. expires_at: null,
  771. },
  772. {
  773. id: 2,
  774. name: 'legacy-key',
  775. key_prefix: 'bk_legacy01',
  776. user_id: null,
  777. can_queue: true,
  778. can_control_printer: false,
  779. can_read_status: true,
  780. can_access_cloud: false,
  781. printer_ids: null,
  782. enabled: true,
  783. last_used: null,
  784. created_at: '2025-01-01T00:00:00Z',
  785. expires_at: null,
  786. },
  787. ];
  788. server.use(http.get('/api/v1/api-keys/', () => HttpResponse.json(keys)));
  789. const user = userEvent.setup();
  790. render(<SettingsPage />);
  791. await waitFor(() => {
  792. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  793. });
  794. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  795. await user.click(tabButton!);
  796. await waitFor(() => {
  797. expect(screen.getByText('cloud-reader')).toBeInTheDocument();
  798. expect(screen.getByText('legacy-key')).toBeInTheDocument();
  799. });
  800. // Cloud-enabled key gets the Cloud badge but NOT the Legacy badge.
  801. const cloudRow = screen.getByText('cloud-reader').closest('.flex.items-center.justify-between');
  802. expect(cloudRow).not.toBeNull();
  803. expect(cloudRow!.textContent).toContain('Cloud');
  804. expect(cloudRow!.textContent).not.toContain('Legacy');
  805. // Ownerless key gets Legacy but NOT Cloud (can_access_cloud=false).
  806. const legacyRow = screen.getByText('legacy-key').closest('.flex.items-center.justify-between');
  807. expect(legacyRow).not.toBeNull();
  808. expect(legacyRow!.textContent).toContain('Legacy');
  809. // Strip the Cloud-flag check by limiting to badge area — the
  810. // "Allow cloud access" text from the create form isn't visible here.
  811. expect(legacyRow!.querySelector('.bg-purple-500\\/20')).toBeNull();
  812. });
  813. it('passes can_access_cloud through to the create call when the toggle is checked', async () => {
  814. let posted: { name?: string; can_access_cloud?: boolean } | null = null;
  815. server.use(
  816. http.get('/api/v1/api-keys/', () => HttpResponse.json([])),
  817. http.post('/api/v1/api-keys/', async ({ request }) => {
  818. posted = (await request.json()) as { name?: string; can_access_cloud?: boolean };
  819. return HttpResponse.json({
  820. id: 99,
  821. key: 'bk_returnedkey',
  822. name: posted.name,
  823. key_prefix: 'bk_returne',
  824. user_id: 1,
  825. can_queue: true,
  826. can_control_printer: false,
  827. can_read_status: true,
  828. can_access_cloud: posted.can_access_cloud ?? false,
  829. printer_ids: null,
  830. enabled: true,
  831. last_used: null,
  832. created_at: '2026-05-01T00:00:00Z',
  833. expires_at: null,
  834. });
  835. })
  836. );
  837. const user = userEvent.setup();
  838. render(<SettingsPage />);
  839. await waitFor(() => {
  840. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  841. });
  842. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  843. await user.click(tabButton!);
  844. // Open the create form. With an empty key list the empty-state card
  845. // shows "Create Your First Key" — click that to open the form.
  846. const openButton = await screen.findByRole('button', { name: /Create Your First Key/i });
  847. await user.click(openButton);
  848. // Tick the new "Allow cloud access" checkbox. The label wraps the
  849. // input AND a sibling description div, so getByLabelText doesn't
  850. // resolve via implicit-label traversal — locate via text + closest
  851. // label, then grab the checkbox from the same scope.
  852. const cloudLabelText = await screen.findByText(/Allow cloud access/i);
  853. const cloudLabel = cloudLabelText.closest('label');
  854. expect(cloudLabel).not.toBeNull();
  855. const cloudCheckbox = cloudLabel!.querySelector('input[type="checkbox"]') as HTMLInputElement;
  856. expect(cloudCheckbox).not.toBeNull();
  857. await user.click(cloudCheckbox);
  858. // Submit. Two "Create Key" buttons exist once the form is open (header
  859. // CTA + form footer); the form-footer one is the actual submit and
  860. // calls the mutation — find it by walking up from the cloud checkbox
  861. // we just clicked, since both share the same form container.
  862. const submitButtons = screen.getAllByRole('button', { name: /^Create Key$/i });
  863. // Footer submit is the one inside the same form section as the
  864. // checkbox. The header CTA is in a separate flex row.
  865. const formSubmit = submitButtons.find(
  866. (b) => b.closest('div')?.contains(cloudCheckbox) || cloudLabel?.parentElement?.parentElement?.contains(b),
  867. );
  868. await user.click(formSubmit ?? submitButtons[submitButtons.length - 1]);
  869. await waitFor(() => {
  870. expect(posted).not.toBeNull();
  871. expect(posted!.can_access_cloud).toBe(true);
  872. });
  873. });
  874. });
  875. describe('API Keys tab — #1356 energy-cost write scope', () => {
  876. /**
  877. * The narrowly-scoped settings-write toggle. We pin two contracts here:
  878. *
  879. * 1. The "Energy" badge renders for keys that have can_update_energy_cost=true.
  880. * Without a visible signal, an operator can't tell which key in their
  881. * list is the one their HA automation depends on.
  882. * 2. The create form sends can_update_energy_cost=true to the backend
  883. * when the toggle is checked. The whole point of #1356 is that the
  884. * flag must actually be persisted — a UI that drops it silently
  885. * would put us right back where the bug started.
  886. */
  887. it('renders the Energy badge for keys with can_update_energy_cost=true', async () => {
  888. const keys = [
  889. {
  890. id: 1,
  891. name: 'tariff-pusher',
  892. key_prefix: 'bk_tariff01',
  893. user_id: 7,
  894. can_queue: false,
  895. can_control_printer: false,
  896. can_read_status: true,
  897. can_access_cloud: false,
  898. can_update_energy_cost: true,
  899. printer_ids: null,
  900. enabled: true,
  901. last_used: null,
  902. created_at: '2026-05-15T00:00:00Z',
  903. expires_at: null,
  904. },
  905. ];
  906. server.use(http.get('/api/v1/api-keys/', () => HttpResponse.json(keys)));
  907. const user = userEvent.setup();
  908. render(<SettingsPage />);
  909. await waitFor(() => {
  910. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  911. });
  912. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  913. await user.click(tabButton!);
  914. await waitFor(() => {
  915. expect(screen.getByText('tariff-pusher')).toBeInTheDocument();
  916. });
  917. const row = screen.getByText('tariff-pusher').closest('.flex.items-center.justify-between');
  918. expect(row).not.toBeNull();
  919. expect(row!.textContent).toContain('Energy');
  920. });
  921. it('passes can_update_energy_cost through to the create call when the toggle is checked', async () => {
  922. let posted: { name?: string; can_update_energy_cost?: boolean } | null = null;
  923. server.use(
  924. http.get('/api/v1/api-keys/', () => HttpResponse.json([])),
  925. http.post('/api/v1/api-keys/', async ({ request }) => {
  926. posted = (await request.json()) as { name?: string; can_update_energy_cost?: boolean };
  927. return HttpResponse.json({
  928. id: 99,
  929. key: 'bk_returnedkey',
  930. name: posted.name,
  931. key_prefix: 'bk_returne',
  932. user_id: 1,
  933. can_queue: true,
  934. can_control_printer: false,
  935. can_read_status: true,
  936. can_access_cloud: false,
  937. can_update_energy_cost: posted.can_update_energy_cost ?? false,
  938. printer_ids: null,
  939. enabled: true,
  940. last_used: null,
  941. created_at: '2026-05-15T00:00:00Z',
  942. expires_at: null,
  943. });
  944. })
  945. );
  946. const user = userEvent.setup();
  947. render(<SettingsPage />);
  948. await waitFor(() => {
  949. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  950. });
  951. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  952. await user.click(tabButton!);
  953. const openButton = await screen.findByRole('button', { name: /Create Your First Key/i });
  954. await user.click(openButton);
  955. const energyLabelText = await screen.findByText(/Update electricity price/i);
  956. const energyLabel = energyLabelText.closest('label');
  957. expect(energyLabel).not.toBeNull();
  958. const energyCheckbox = energyLabel!.querySelector('input[type="checkbox"]') as HTMLInputElement;
  959. expect(energyCheckbox).not.toBeNull();
  960. await user.click(energyCheckbox);
  961. const submitButtons = screen.getAllByRole('button', { name: /^Create Key$/i });
  962. const formSubmit = submitButtons.find(
  963. (b) => b.closest('div')?.contains(energyCheckbox) || energyLabel?.parentElement?.parentElement?.contains(b),
  964. );
  965. await user.click(formSubmit ?? submitButtons[submitButtons.length - 1]);
  966. await waitFor(() => {
  967. expect(posted).not.toBeNull();
  968. expect(posted!.can_update_energy_cost).toBe(true);
  969. });
  970. });
  971. });
  972. describe('external camera snapshot URL override (#1177)', () => {
  973. /**
  974. * The snapshot URL input only appears for stream camera types where the
  975. * MJPEG warm-up problem can occur (mjpeg / rtsp / usb). Pure HTTP
  976. * snapshot sources don't need an override since their stream URL is
  977. * already a single-frame endpoint.
  978. */
  979. const mjpegPrinter = {
  980. id: 7,
  981. name: 'go2rtc Cam',
  982. serial_number: 'TEST123',
  983. ip_address: '192.168.1.100',
  984. access_code: 'XXXX',
  985. model: 'P1S',
  986. location: null,
  987. nozzle_count: 1,
  988. is_active: true,
  989. auto_archive: true,
  990. external_camera_url: 'http://192.168.1.61:1984/api/stream.mjpeg?src=printer',
  991. external_camera_type: 'mjpeg',
  992. external_camera_enabled: true,
  993. external_camera_snapshot_url: null,
  994. camera_rotation: 0,
  995. plate_detection_enabled: false,
  996. created_at: '2026-01-01T00:00:00Z',
  997. updated_at: '2026-01-01T00:00:00Z',
  998. };
  999. it('renders the snapshot URL input when camera_type is mjpeg', async () => {
  1000. server.use(
  1001. http.get('/api/v1/printers/', () => HttpResponse.json([mjpegPrinter])),
  1002. );
  1003. render(<SettingsPage />);
  1004. await waitFor(() => {
  1005. expect(screen.getByPlaceholderText(/api\/frame\.jpeg\?src=printer/)).toBeInTheDocument();
  1006. });
  1007. });
  1008. it('hides the snapshot URL input when camera_type is snapshot (already a single-frame source)', async () => {
  1009. server.use(
  1010. http.get('/api/v1/printers/', () =>
  1011. HttpResponse.json([{ ...mjpegPrinter, external_camera_type: 'snapshot' }]),
  1012. ),
  1013. );
  1014. render(<SettingsPage />);
  1015. // Wait for the live-stream URL placeholder to render so we know the
  1016. // camera section finished mounting before asserting absence of the
  1017. // snapshot input below.
  1018. await waitFor(() => {
  1019. expect(screen.getByPlaceholderText(/Camera URL/i)).toBeInTheDocument();
  1020. });
  1021. expect(screen.queryByPlaceholderText(/api\/frame\.jpeg\?src=printer/)).not.toBeInTheDocument();
  1022. });
  1023. it(
  1024. 'PATCHes the printer with external_camera_snapshot_url when the user types into the input',
  1025. async () => {
  1026. let receivedBody: Record<string, unknown> | null = null;
  1027. server.use(
  1028. http.get('/api/v1/printers/', () => HttpResponse.json([mjpegPrinter])),
  1029. http.patch('/api/v1/printers/7', async ({ request }) => {
  1030. receivedBody = (await request.json()) as Record<string, unknown>;
  1031. return HttpResponse.json({ ...mjpegPrinter, ...receivedBody });
  1032. }),
  1033. );
  1034. render(<SettingsPage />);
  1035. const input = await waitFor(() =>
  1036. screen.getByPlaceholderText(/api\/frame\.jpeg\?src=printer/),
  1037. );
  1038. const user = userEvent.setup();
  1039. await user.type(input, 'http://192.168.1.61:1984/api/frame.jpeg?src=printer');
  1040. // Save is debounced by 800ms; assert the PATCH eventually fires with
  1041. // the typed snapshot URL.
  1042. await waitFor(
  1043. () => {
  1044. expect(receivedBody).not.toBeNull();
  1045. expect(receivedBody!.external_camera_snapshot_url).toBe(
  1046. 'http://192.168.1.61:1984/api/frame.jpeg?src=printer',
  1047. );
  1048. },
  1049. { timeout: 5000 },
  1050. );
  1051. },
  1052. // Per-test timeout raised to 15s — `user.type()` of a 49-char URL plus
  1053. // the 800ms save debounce fits in 5s locally (~2.3s typical) but blows
  1054. // past it on slow GitHub Actions runners (5000ms timeout was the failure
  1055. // mode on PR #1263).
  1056. 15_000,
  1057. );
  1058. });
  1059. describe('theme mode buttons', () => {
  1060. it('renders Dark, Light, and System buttons', async () => {
  1061. render(<SettingsPage />);
  1062. await waitFor(() => {
  1063. expect(screen.getByRole('button', { name: 'Dark' })).toBeInTheDocument();
  1064. expect(screen.getByRole('button', { name: 'Light' })).toBeInTheDocument();
  1065. expect(screen.getByRole('button', { name: 'System' })).toBeInTheDocument();
  1066. });
  1067. });
  1068. it('highlights the active mode button with green border', async () => {
  1069. render(<SettingsPage />);
  1070. const user = userEvent.setup();
  1071. await waitFor(() => {
  1072. expect(screen.getByRole('button', { name: 'System' })).toBeInTheDocument();
  1073. });
  1074. await user.click(screen.getByRole('button', { name: 'System' }));
  1075. await waitFor(() => {
  1076. const systemBtn = screen.getByRole('button', { name: 'System' });
  1077. expect(systemBtn.className).toContain('border-bambu-green');
  1078. });
  1079. });
  1080. it('clicking a theme button switches mode', async () => {
  1081. localStorage.setItem('theme-mode', 'dark');
  1082. render(<SettingsPage />);
  1083. const user = userEvent.setup();
  1084. await waitFor(() => {
  1085. const darkBtn = screen.getByRole('button', { name: 'Dark' });
  1086. expect(darkBtn.className).toContain('border-bambu-green');
  1087. });
  1088. const lightBtn = screen.getByRole('button', { name: 'Light' });
  1089. await user.click(lightBtn);
  1090. await waitFor(() => {
  1091. expect(lightBtn.className).toContain('border-bambu-green');
  1092. });
  1093. });
  1094. it('shows a toast when theme button is clicked', async () => {
  1095. render(<SettingsPage />);
  1096. const user = userEvent.setup();
  1097. await waitFor(() => {
  1098. expect(screen.getByRole('button', { name: 'System' })).toBeInTheDocument();
  1099. });
  1100. await user.click(screen.getByRole('button', { name: 'System' }));
  1101. await waitFor(() => {
  1102. expect(screen.getByText('Settings saved')).toBeInTheDocument();
  1103. });
  1104. });
  1105. });
  1106. });