SettingsPage.test.tsx 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  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', 'finance', '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', 'finance', '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. 'finance',
  410. 'files',
  411. 'makerworld',
  412. 'profiles',
  413. 'maintenance',
  414. 'stats',
  415. 'notifications',
  416. 'settings',
  417. ],
  418. hiddenSystemItemIds: ['stats'],
  419. });
  420. });
  421. });
  422. describe('update CTA per deployment shape', () => {
  423. // The update card branches on the deployment shape returned by
  424. // /updates/check. Each branch is mutually exclusive — verify the right
  425. // one wins so HA addon users never see the docker-compose snippet
  426. // (which they can't run from inside an HA addon container) and Docker
  427. // users never see the in-app Install button (which would no-op).
  428. const renderWithUpdateCheck = async (
  429. checkBody: Record<string, unknown>,
  430. settingsOverrides: Record<string, unknown> = {},
  431. ) => {
  432. server.use(
  433. http.get('/api/v1/settings/', () =>
  434. HttpResponse.json({ ...mockSettings, check_updates: true, ...settingsOverrides }),
  435. ),
  436. http.get('/api/v1/updates/check', () => HttpResponse.json(checkBody)),
  437. );
  438. render(<SettingsPage />);
  439. await waitFor(() => {
  440. expect(screen.getByText('Updates')).toBeInTheDocument();
  441. });
  442. };
  443. it('shows the HA Supervisor message when running as an HA addon', async () => {
  444. await renderWithUpdateCheck({
  445. update_available: true,
  446. current_version: '0.2.4',
  447. latest_version: '0.2.5',
  448. release_name: '0.2.5',
  449. release_notes: '',
  450. release_url: 'https://example.invalid/r',
  451. published_at: '2099-01-01T00:00:00Z',
  452. is_docker: true,
  453. is_ha_addon: true,
  454. update_method: 'ha_addon',
  455. });
  456. await waitFor(() => {
  457. expect(
  458. screen.getByText(/Home Assistant Supervisor/i),
  459. ).toBeInTheDocument();
  460. });
  461. // Docker hint must NOT render — HA branch wins.
  462. expect(screen.queryByText('docker compose pull && docker compose up -d')).not.toBeInTheDocument();
  463. expect(screen.queryByRole('button', { name: /install update/i })).not.toBeInTheDocument();
  464. });
  465. it('shows the docker-compose snippet for Docker (non-HA) deployments', async () => {
  466. await renderWithUpdateCheck({
  467. update_available: true,
  468. current_version: '0.2.4',
  469. latest_version: '0.2.5',
  470. release_name: '0.2.5',
  471. release_notes: '',
  472. release_url: 'https://example.invalid/r',
  473. published_at: '2099-01-01T00:00:00Z',
  474. is_docker: true,
  475. is_ha_addon: false,
  476. update_method: 'docker',
  477. });
  478. await waitFor(() => {
  479. expect(screen.getByText('docker compose pull && docker compose up -d')).toBeInTheDocument();
  480. });
  481. expect(screen.queryByText(/Home Assistant Supervisor/i)).not.toBeInTheDocument();
  482. expect(screen.queryByRole('button', { name: /install update/i })).not.toBeInTheDocument();
  483. });
  484. // #2664: the bare command only works if the user is already standing in
  485. // the directory holding their compose file, which is exactly the thing
  486. // they came to the page not knowing.
  487. const DOCKER_CHECK = {
  488. update_available: true,
  489. current_version: '0.2.4',
  490. latest_version: '0.2.5',
  491. release_name: '0.2.5',
  492. release_notes: '',
  493. release_url: 'https://example.invalid/r',
  494. published_at: '2099-01-01T00:00:00Z',
  495. is_docker: true,
  496. is_ha_addon: false,
  497. update_method: 'docker',
  498. };
  499. it('prefixes the command with cd when the backend detected a compose directory', async () => {
  500. await renderWithUpdateCheck({ ...DOCKER_CHECK, compose_dir_detected: '/opt/bambuddy' });
  501. await waitFor(() => {
  502. expect(
  503. screen.getByText('cd /opt/bambuddy && docker compose pull && docker compose up -d'),
  504. ).toBeInTheDocument();
  505. });
  506. });
  507. it('prefers the saved directory over the detected one', async () => {
  508. await renderWithUpdateCheck(
  509. { ...DOCKER_CHECK, compose_dir_detected: '/opt/guessed' },
  510. { docker_compose_dir: '/srv/stacks/bambuddy' },
  511. );
  512. await waitFor(() => {
  513. expect(
  514. screen.getByText('cd /srv/stacks/bambuddy && docker compose pull && docker compose up -d'),
  515. ).toBeInTheDocument();
  516. });
  517. expect(screen.queryByText(/\/opt\/guessed/)).not.toBeInTheDocument();
  518. });
  519. it('quotes a directory containing a space so the cd does not split', async () => {
  520. await renderWithUpdateCheck(DOCKER_CHECK, { docker_compose_dir: '/srv/bambu buddy' });
  521. await waitFor(() => {
  522. expect(
  523. screen.getByText('cd "/srv/bambu buddy" && docker compose pull && docker compose up -d'),
  524. ).toBeInTheDocument();
  525. });
  526. });
  527. it('copies the full command including the cd', async () => {
  528. const writeText = vi.fn().mockResolvedValue(undefined);
  529. Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
  530. Object.defineProperty(window, 'isSecureContext', { value: true, configurable: true });
  531. await renderWithUpdateCheck({ ...DOCKER_CHECK, compose_dir_detected: '/opt/bambuddy' });
  532. const copy = await screen.findByRole('button', { name: /copy update command/i });
  533. await userEvent.click(copy);
  534. expect(writeText).toHaveBeenCalledWith(
  535. 'cd /opt/bambuddy && docker compose pull && docker compose up -d',
  536. );
  537. });
  538. it('offers an editable compose directory field seeded with the detected path', async () => {
  539. await renderWithUpdateCheck({ ...DOCKER_CHECK, compose_dir_detected: '/opt/bambuddy' });
  540. const field = await screen.findByPlaceholderText('/opt/bambuddy');
  541. // Placeholder, not value — the detected path is a guess the user has
  542. // not accepted, so saving must not silently adopt it.
  543. expect(field).toHaveValue('');
  544. });
  545. it('shows the installer-download link for Windows installer installs', async () => {
  546. const downloadUrl =
  547. 'https://github.com/maziggy/bambuddy/releases/download/v0.2.5/bambuddy-0.2.5-windows-x64-setup.exe';
  548. await renderWithUpdateCheck({
  549. update_available: true,
  550. current_version: '0.2.4',
  551. latest_version: '0.2.5',
  552. release_name: '0.2.5',
  553. release_notes: '',
  554. release_url: 'https://github.com/maziggy/bambuddy/releases/tag/v0.2.5',
  555. published_at: '2099-01-01T00:00:00Z',
  556. is_docker: false,
  557. is_ha_addon: false,
  558. is_windows_installer: true,
  559. update_method: 'windows_installer',
  560. installer_download_url: downloadUrl,
  561. });
  562. const link = await screen.findByRole('link', { name: /download installer for v0\.2\.5/i });
  563. expect(link).toHaveAttribute('href', downloadUrl);
  564. expect(link).toHaveAttribute('target', '_blank');
  565. expect(link).toHaveAttribute('rel', expect.stringContaining('noopener'));
  566. // The in-app update button must NOT render — the git-fetch path can't
  567. // work from an installer payload.
  568. expect(screen.queryByRole('button', { name: /install update/i })).not.toBeInTheDocument();
  569. expect(screen.queryByText(/Home Assistant Supervisor/i)).not.toBeInTheDocument();
  570. expect(screen.queryByText('docker compose pull && docker compose up -d')).not.toBeInTheDocument();
  571. });
  572. });
  573. describe('tabs navigation', () => {
  574. it('can switch to Network tab', async () => {
  575. const user = userEvent.setup();
  576. render(<SettingsPage />);
  577. // Wait for settings to load first
  578. await waitFor(() => {
  579. expect(screen.getByText('Date Format')).toBeInTheDocument();
  580. });
  581. await user.click(screen.getByText('Network'));
  582. await waitFor(() => {
  583. // Network tab contains MQTT Publishing section
  584. expect(screen.getByText('MQTT Publishing')).toBeInTheDocument();
  585. });
  586. });
  587. it('can switch to Smart Plugs tab', async () => {
  588. const user = userEvent.setup();
  589. render(<SettingsPage />);
  590. await waitFor(() => {
  591. expect(screen.getByText('Smart Plugs')).toBeInTheDocument();
  592. });
  593. await user.click(screen.getByText('Smart Plugs'));
  594. await waitFor(() => {
  595. expect(screen.getByText('Add Smart Plug')).toBeInTheDocument();
  596. });
  597. });
  598. it('can switch to Notifications tab', async () => {
  599. const user = userEvent.setup();
  600. render(<SettingsPage />);
  601. await waitFor(() => {
  602. expect(screen.getAllByText('Notifications').length).toBeGreaterThan(0);
  603. });
  604. // Click the tab button (not the mobile dropdown option)
  605. const notificationButtons = screen.getAllByText('Notifications');
  606. const tabButton = notificationButtons.find(el => el.tagName === 'BUTTON') || notificationButtons[0];
  607. await user.click(tabButton);
  608. await waitFor(() => {
  609. expect(screen.getByText('Add Provider')).toBeInTheDocument();
  610. });
  611. });
  612. it('can switch to Filament tab', async () => {
  613. const user = userEvent.setup();
  614. render(<SettingsPage />);
  615. await waitFor(() => {
  616. expect(screen.getAllByText('Filament').length).toBeGreaterThan(0);
  617. });
  618. await user.click(screen.getAllByText('Filament')[0]);
  619. await waitFor(() => {
  620. expect(screen.getByText('AMS Display Thresholds')).toBeInTheDocument();
  621. });
  622. });
  623. });
  624. describe('Workflow tab', () => {
  625. it('can switch to Workflow tab', async () => {
  626. const user = userEvent.setup();
  627. render(<SettingsPage />);
  628. await waitFor(() => {
  629. expect(screen.getByText('Workflow')).toBeInTheDocument();
  630. });
  631. await user.click(screen.getByText('Workflow'));
  632. await waitFor(() => {
  633. expect(screen.getByText('Staggered Start')).toBeInTheDocument();
  634. });
  635. });
  636. it('shows stagger settings on Workflow tab', async () => {
  637. const user = userEvent.setup();
  638. render(<SettingsPage />);
  639. await waitFor(() => {
  640. expect(screen.getByText('Workflow')).toBeInTheDocument();
  641. });
  642. await user.click(screen.getByText('Workflow'));
  643. await waitFor(() => {
  644. expect(screen.getByText('Staggered Start')).toBeInTheDocument();
  645. expect(screen.getByText('Group size')).toBeInTheDocument();
  646. expect(screen.getByText('Interval (minutes)')).toBeInTheDocument();
  647. });
  648. });
  649. it('shows auto-drying settings on Workflow tab', async () => {
  650. const user = userEvent.setup();
  651. render(<SettingsPage />);
  652. await waitFor(() => {
  653. expect(screen.getByText('Workflow')).toBeInTheDocument();
  654. });
  655. await user.click(screen.getByText('Workflow'));
  656. await waitFor(() => {
  657. expect(screen.getByText('Queue Auto-Drying')).toBeInTheDocument();
  658. });
  659. });
  660. it('shows per-filament humidity threshold editor on Workflow tab (#1605)', async () => {
  661. const user = userEvent.setup();
  662. render(<SettingsPage />);
  663. await waitFor(() => {
  664. expect(screen.getByText('Workflow')).toBeInTheDocument();
  665. });
  666. await user.click(screen.getByText('Workflow'));
  667. await waitFor(() => {
  668. expect(screen.getByText('Humidity Thresholds')).toBeInTheDocument();
  669. // Default row is unique to the humidity editor (drying presets has no
  670. // default row), so we can pin it without disambiguating from the
  671. // adjacent drying-presets table that also lists PLA/ASA/etc.
  672. expect(screen.getByText('Default (unknown types)')).toBeInTheDocument();
  673. // Filament rows render in both tables — assert by count instead of
  674. // a single getByText. 8 default filaments × 2 tables = 16 PLAs etc.
  675. expect(screen.getAllByText('PLA').length).toBeGreaterThanOrEqual(2);
  676. expect(screen.getAllByText('ASA').length).toBeGreaterThanOrEqual(2);
  677. });
  678. });
  679. it('shows default print options on Workflow tab', async () => {
  680. const user = userEvent.setup();
  681. render(<SettingsPage />);
  682. await waitFor(() => {
  683. expect(screen.getByText('Workflow')).toBeInTheDocument();
  684. });
  685. await user.click(screen.getByText('Workflow'));
  686. await waitFor(() => {
  687. expect(screen.getByText('Default Print Options')).toBeInTheDocument();
  688. expect(screen.getByText('Bed Levelling')).toBeInTheDocument();
  689. expect(screen.getByText('Flow Calibration')).toBeInTheDocument();
  690. expect(screen.getByText('Vibration Calibration')).toBeInTheDocument();
  691. expect(screen.getByText('First Layer Inspection')).toBeInTheDocument();
  692. expect(screen.getByText('Timelapse')).toBeInTheDocument();
  693. });
  694. });
  695. it('shows default print options description', async () => {
  696. const user = userEvent.setup();
  697. render(<SettingsPage />);
  698. await waitFor(() => {
  699. expect(screen.getByText('Workflow')).toBeInTheDocument();
  700. });
  701. await user.click(screen.getByText('Workflow'));
  702. await waitFor(() => {
  703. expect(screen.getByText(/overridden per print in the print dialog/)).toBeInTheDocument();
  704. });
  705. });
  706. });
  707. describe('API Keys tab', () => {
  708. it('can switch to API Keys tab', async () => {
  709. const user = userEvent.setup();
  710. render(<SettingsPage />);
  711. await waitFor(() => {
  712. expect(screen.getByText('API Keys')).toBeInTheDocument();
  713. });
  714. await user.click(screen.getByText('API Keys'));
  715. await waitFor(() => {
  716. // Button text is "Create Key"
  717. expect(screen.getByText('Create Key')).toBeInTheDocument();
  718. });
  719. });
  720. });
  721. describe('SpoolBuddy tab badge', () => {
  722. const baseDevice = {
  723. id: 1,
  724. device_id: 'sb-0001',
  725. hostname: 'sb-kitchen',
  726. ip_address: '10.0.0.1',
  727. backend_url: null,
  728. firmware_version: '1.0.0',
  729. has_nfc: true,
  730. has_scale: true,
  731. tare_offset: 0,
  732. calibration_factor: 1.0,
  733. nfc_reader_type: null,
  734. nfc_connection: null,
  735. display_brightness: 100,
  736. display_blank_timeout: 0,
  737. has_backlight: false,
  738. last_calibrated_at: null,
  739. last_seen: new Date().toISOString(),
  740. pending_command: null,
  741. nfc_ok: true,
  742. scale_ok: true,
  743. uptime_s: 100,
  744. update_status: null,
  745. update_message: null,
  746. system_stats: null,
  747. online: true,
  748. created_at: '2024-01-01T00:00:00Z',
  749. updated_at: '2024-01-01T00:00:00Z',
  750. };
  751. it('shows device count and green bullet when at least one device is online', async () => {
  752. server.use(
  753. http.get('/api/v1/spoolbuddy/devices', () => {
  754. return HttpResponse.json([
  755. { ...baseDevice, id: 1, device_id: 'sb-0001', hostname: 'sb-kitchen', online: true },
  756. { ...baseDevice, id: 2, device_id: 'sb-0002', hostname: 'sb-ghost', online: false },
  757. ]);
  758. })
  759. );
  760. render(<SettingsPage />);
  761. // Find the tab button (not the header) — it's the <button> containing the SpoolBuddy text
  762. const tabButton = await waitFor(() => {
  763. const buttons = screen.getAllByRole('button').filter((b) => b.textContent?.includes('SpoolBuddy'));
  764. expect(buttons.length).toBeGreaterThan(0);
  765. return buttons[0];
  766. });
  767. // Count pill rendered
  768. await waitFor(() => {
  769. expect(tabButton.textContent).toContain('2');
  770. });
  771. // Green status bullet (at least one device online)
  772. await waitFor(() => {
  773. expect(tabButton.querySelector('.bg-green-400')).not.toBeNull();
  774. });
  775. });
  776. it('shows gray bullet when all devices are offline', async () => {
  777. server.use(
  778. http.get('/api/v1/spoolbuddy/devices', () => {
  779. return HttpResponse.json([{ ...baseDevice, online: false }]);
  780. })
  781. );
  782. render(<SettingsPage />);
  783. const tabButton = await waitFor(() => {
  784. const buttons = screen.getAllByRole('button').filter((b) => b.textContent?.includes('SpoolBuddy'));
  785. expect(buttons.length).toBeGreaterThan(0);
  786. return buttons[0];
  787. });
  788. await waitFor(() => {
  789. expect(tabButton.querySelector('.bg-gray-500')).not.toBeNull();
  790. expect(tabButton.querySelector('.bg-green-400')).toBeNull();
  791. });
  792. });
  793. it('hides the count pill when no devices are registered', async () => {
  794. server.use(
  795. http.get('/api/v1/spoolbuddy/devices', () => HttpResponse.json([]))
  796. );
  797. render(<SettingsPage />);
  798. const tabButton = await waitFor(() => {
  799. const buttons = screen.getAllByRole('button').filter((b) => b.textContent?.includes('SpoolBuddy'));
  800. expect(buttons.length).toBeGreaterThan(0);
  801. return buttons[0];
  802. });
  803. // The only numeric content should NOT be present — tab label only
  804. await waitFor(() => {
  805. expect(tabButton.textContent).toBe('SpoolBuddy');
  806. });
  807. });
  808. });
  809. describe('API Keys tab — delete flow', () => {
  810. // Without setQueryData on success the deleted row stayed visible until a
  811. // manual reload — invalidateQueries didn't reliably trigger a UI swap on
  812. // every browser. Pin the synchronous-removal contract here.
  813. it('removes a deleted key from the list without a page reload', async () => {
  814. const initialKeys = [
  815. {
  816. id: 42,
  817. name: 'CI deploy key',
  818. key_prefix: 'bk_abcd1234',
  819. can_queue: true,
  820. can_control_printer: false,
  821. can_read_status: true,
  822. printer_ids: null,
  823. enabled: true,
  824. last_used: null,
  825. created_at: '2026-01-01T00:00:00Z',
  826. expires_at: null,
  827. },
  828. ];
  829. let deleteCallCount = 0;
  830. server.use(
  831. http.get('/api/v1/api-keys/', () => HttpResponse.json(initialKeys)),
  832. http.delete('/api/v1/api-keys/:id', ({ params }) => {
  833. deleteCallCount += 1;
  834. expect(params.id).toBe('42');
  835. return HttpResponse.json({ message: 'API key deleted' });
  836. })
  837. );
  838. const user = userEvent.setup();
  839. render(<SettingsPage />);
  840. // Switch to API Keys tab. Both desktop tab + mobile dropdown render
  841. // the label, so just grab the button form.
  842. await waitFor(() => {
  843. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  844. });
  845. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  846. expect(tabButton).toBeDefined();
  847. await user.click(tabButton!);
  848. // Key is listed
  849. await waitFor(() => {
  850. expect(screen.getByText('CI deploy key')).toBeInTheDocument();
  851. });
  852. // Click the trash button on the row
  853. const cards = screen.getByText('CI deploy key').closest('.flex.items-center.justify-between');
  854. expect(cards).not.toBeNull();
  855. const trashButton = cards!.querySelectorAll('button');
  856. await user.click(trashButton[trashButton.length - 1]);
  857. // Confirm the deletion in the modal
  858. const confirmButton = await screen.findByRole('button', { name: /delete/i });
  859. await user.click(confirmButton);
  860. // The deleted key disappears from the list immediately — no manual
  861. // reload required. setQueryData drops it before any refetch could fire.
  862. await waitFor(() => {
  863. expect(screen.queryByText('CI deploy key')).not.toBeInTheDocument();
  864. });
  865. expect(deleteCallCount).toBe(1);
  866. });
  867. });
  868. describe('API Keys tab — #1182 cloud access + ownership UI', () => {
  869. // The list now exposes two new bits of information per row:
  870. // - "Cloud" badge when can_access_cloud=true
  871. // - "Legacy" badge when user_id IS NULL (created before per-user ownership)
  872. // These tell the operator at a glance which keys can read /cloud/* data
  873. // and which keys need to be recreated to gain that capability.
  874. it('renders the Cloud badge for keys with can_access_cloud=true and the Legacy badge for ownerless keys', async () => {
  875. const keys = [
  876. {
  877. id: 1,
  878. name: 'cloud-reader',
  879. key_prefix: 'bk_cloud123',
  880. user_id: 7,
  881. can_queue: false,
  882. can_control_printer: false,
  883. can_read_status: true,
  884. can_access_cloud: true,
  885. printer_ids: null,
  886. enabled: true,
  887. last_used: null,
  888. created_at: '2026-04-30T00:00:00Z',
  889. expires_at: null,
  890. },
  891. {
  892. id: 2,
  893. name: 'legacy-key',
  894. key_prefix: 'bk_legacy01',
  895. user_id: null,
  896. can_queue: true,
  897. can_control_printer: false,
  898. can_read_status: true,
  899. can_access_cloud: false,
  900. printer_ids: null,
  901. enabled: true,
  902. last_used: null,
  903. created_at: '2025-01-01T00:00:00Z',
  904. expires_at: null,
  905. },
  906. ];
  907. server.use(http.get('/api/v1/api-keys/', () => HttpResponse.json(keys)));
  908. const user = userEvent.setup();
  909. render(<SettingsPage />);
  910. await waitFor(() => {
  911. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  912. });
  913. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  914. await user.click(tabButton!);
  915. await waitFor(() => {
  916. expect(screen.getByText('cloud-reader')).toBeInTheDocument();
  917. expect(screen.getByText('legacy-key')).toBeInTheDocument();
  918. });
  919. // Cloud-enabled key gets the Cloud badge but NOT the Legacy badge.
  920. const cloudRow = screen.getByText('cloud-reader').closest('.flex.items-center.justify-between');
  921. expect(cloudRow).not.toBeNull();
  922. expect(cloudRow!.textContent).toContain('Cloud');
  923. expect(cloudRow!.textContent).not.toContain('Legacy');
  924. // Ownerless key gets Legacy but NOT Cloud (can_access_cloud=false).
  925. const legacyRow = screen.getByText('legacy-key').closest('.flex.items-center.justify-between');
  926. expect(legacyRow).not.toBeNull();
  927. expect(legacyRow!.textContent).toContain('Legacy');
  928. // Strip the Cloud-flag check by limiting to badge area — the
  929. // "Allow cloud access" text from the create form isn't visible here.
  930. expect(legacyRow!.querySelector('.bg-purple-500\\/20')).toBeNull();
  931. });
  932. it('passes can_access_cloud through to the create call when the toggle is checked', async () => {
  933. let posted: { name?: string; can_access_cloud?: boolean } | null = null;
  934. server.use(
  935. http.get('/api/v1/api-keys/', () => HttpResponse.json([])),
  936. http.post('/api/v1/api-keys/', async ({ request }) => {
  937. posted = (await request.json()) as { name?: string; can_access_cloud?: boolean };
  938. return HttpResponse.json({
  939. id: 99,
  940. key: 'bk_returnedkey',
  941. name: posted.name,
  942. key_prefix: 'bk_returne',
  943. user_id: 1,
  944. can_queue: true,
  945. can_control_printer: false,
  946. can_read_status: true,
  947. can_access_cloud: posted.can_access_cloud ?? false,
  948. printer_ids: null,
  949. enabled: true,
  950. last_used: null,
  951. created_at: '2026-05-01T00:00:00Z',
  952. expires_at: null,
  953. });
  954. })
  955. );
  956. const user = userEvent.setup();
  957. render(<SettingsPage />);
  958. await waitFor(() => {
  959. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  960. });
  961. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  962. await user.click(tabButton!);
  963. // Open the create form. With an empty key list the empty-state card
  964. // shows "Create Your First Key" — click that to open the form.
  965. const openButton = await screen.findByRole('button', { name: /Create Your First Key/i });
  966. await user.click(openButton);
  967. // Tick the new "Allow cloud access" checkbox. The label wraps the
  968. // input AND a sibling description div, so getByLabelText doesn't
  969. // resolve via implicit-label traversal — locate via text + closest
  970. // label, then grab the checkbox from the same scope.
  971. const cloudLabelText = await screen.findByText(/Allow cloud access/i);
  972. const cloudLabel = cloudLabelText.closest('label');
  973. expect(cloudLabel).not.toBeNull();
  974. const cloudCheckbox = cloudLabel!.querySelector('input[type="checkbox"]') as HTMLInputElement;
  975. expect(cloudCheckbox).not.toBeNull();
  976. await user.click(cloudCheckbox);
  977. // Submit. Two "Create Key" buttons exist once the form is open (header
  978. // CTA + form footer); the form-footer one is the actual submit and
  979. // calls the mutation — find it by walking up from the cloud checkbox
  980. // we just clicked, since both share the same form container.
  981. const submitButtons = screen.getAllByRole('button', { name: /^Create Key$/i });
  982. // Footer submit is the one inside the same form section as the
  983. // checkbox. The header CTA is in a separate flex row.
  984. const formSubmit = submitButtons.find(
  985. (b) => b.closest('div')?.contains(cloudCheckbox) || cloudLabel?.parentElement?.parentElement?.contains(b),
  986. );
  987. await user.click(formSubmit ?? submitButtons[submitButtons.length - 1]);
  988. await waitFor(() => {
  989. expect(posted).not.toBeNull();
  990. expect(posted!.can_access_cloud).toBe(true);
  991. });
  992. });
  993. });
  994. describe('API Keys tab — #1356 energy-cost write scope', () => {
  995. /**
  996. * The narrowly-scoped settings-write toggle. We pin two contracts here:
  997. *
  998. * 1. The "Energy" badge renders for keys that have can_update_energy_cost=true.
  999. * Without a visible signal, an operator can't tell which key in their
  1000. * list is the one their HA automation depends on.
  1001. * 2. The create form sends can_update_energy_cost=true to the backend
  1002. * when the toggle is checked. The whole point of #1356 is that the
  1003. * flag must actually be persisted — a UI that drops it silently
  1004. * would put us right back where the bug started.
  1005. */
  1006. it('renders the Energy badge for keys with can_update_energy_cost=true', async () => {
  1007. const keys = [
  1008. {
  1009. id: 1,
  1010. name: 'tariff-pusher',
  1011. key_prefix: 'bk_tariff01',
  1012. user_id: 7,
  1013. can_queue: false,
  1014. can_control_printer: false,
  1015. can_read_status: true,
  1016. can_access_cloud: false,
  1017. can_update_energy_cost: true,
  1018. printer_ids: null,
  1019. enabled: true,
  1020. last_used: null,
  1021. created_at: '2026-05-15T00:00:00Z',
  1022. expires_at: null,
  1023. },
  1024. ];
  1025. server.use(http.get('/api/v1/api-keys/', () => HttpResponse.json(keys)));
  1026. const user = userEvent.setup();
  1027. render(<SettingsPage />);
  1028. await waitFor(() => {
  1029. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  1030. });
  1031. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  1032. await user.click(tabButton!);
  1033. await waitFor(() => {
  1034. expect(screen.getByText('tariff-pusher')).toBeInTheDocument();
  1035. });
  1036. const row = screen.getByText('tariff-pusher').closest('.flex.items-center.justify-between');
  1037. expect(row).not.toBeNull();
  1038. expect(row!.textContent).toContain('Energy');
  1039. });
  1040. it('passes can_update_energy_cost through to the create call when the toggle is checked', async () => {
  1041. let posted: { name?: string; can_update_energy_cost?: boolean } | null = null;
  1042. server.use(
  1043. http.get('/api/v1/api-keys/', () => HttpResponse.json([])),
  1044. http.post('/api/v1/api-keys/', async ({ request }) => {
  1045. posted = (await request.json()) as { name?: string; can_update_energy_cost?: boolean };
  1046. return HttpResponse.json({
  1047. id: 99,
  1048. key: 'bk_returnedkey',
  1049. name: posted.name,
  1050. key_prefix: 'bk_returne',
  1051. user_id: 1,
  1052. can_queue: true,
  1053. can_control_printer: false,
  1054. can_read_status: true,
  1055. can_access_cloud: false,
  1056. can_update_energy_cost: posted.can_update_energy_cost ?? false,
  1057. printer_ids: null,
  1058. enabled: true,
  1059. last_used: null,
  1060. created_at: '2026-05-15T00:00:00Z',
  1061. expires_at: null,
  1062. });
  1063. })
  1064. );
  1065. const user = userEvent.setup();
  1066. render(<SettingsPage />);
  1067. await waitFor(() => {
  1068. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  1069. });
  1070. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  1071. await user.click(tabButton!);
  1072. const openButton = await screen.findByRole('button', { name: /Create Your First Key/i });
  1073. await user.click(openButton);
  1074. const energyLabelText = await screen.findByText(/Update electricity price/i);
  1075. const energyLabel = energyLabelText.closest('label');
  1076. expect(energyLabel).not.toBeNull();
  1077. const energyCheckbox = energyLabel!.querySelector('input[type="checkbox"]') as HTMLInputElement;
  1078. expect(energyCheckbox).not.toBeNull();
  1079. await user.click(energyCheckbox);
  1080. const submitButtons = screen.getAllByRole('button', { name: /^Create Key$/i });
  1081. const formSubmit = submitButtons.find(
  1082. (b) => b.closest('div')?.contains(energyCheckbox) || energyLabel?.parentElement?.parentElement?.contains(b),
  1083. );
  1084. await user.click(formSubmit ?? submitButtons[submitButtons.length - 1]);
  1085. await waitFor(() => {
  1086. expect(posted).not.toBeNull();
  1087. expect(posted!.can_update_energy_cost).toBe(true);
  1088. });
  1089. });
  1090. });
  1091. describe('external camera snapshot URL override (#1177)', () => {
  1092. /**
  1093. * The snapshot URL input only appears for stream camera types where the
  1094. * MJPEG warm-up problem can occur (mjpeg / rtsp / usb). Pure HTTP
  1095. * snapshot sources don't need an override since their stream URL is
  1096. * already a single-frame endpoint.
  1097. */
  1098. const mjpegPrinter = {
  1099. id: 7,
  1100. name: 'go2rtc Cam',
  1101. serial_number: 'TEST123',
  1102. ip_address: '192.168.1.100',
  1103. access_code: 'XXXX',
  1104. model: 'P1S',
  1105. location: null,
  1106. nozzle_count: 1,
  1107. is_active: true,
  1108. auto_archive: true,
  1109. external_camera_url: 'http://192.168.1.61:1984/api/stream.mjpeg?src=printer',
  1110. external_camera_type: 'mjpeg',
  1111. external_camera_enabled: true,
  1112. external_camera_snapshot_url: null,
  1113. camera_rotation: 0,
  1114. plate_detection_enabled: false,
  1115. created_at: '2026-01-01T00:00:00Z',
  1116. updated_at: '2026-01-01T00:00:00Z',
  1117. };
  1118. it('renders the snapshot URL input when camera_type is mjpeg', async () => {
  1119. server.use(
  1120. http.get('/api/v1/printers/', () => HttpResponse.json([mjpegPrinter])),
  1121. );
  1122. render(<SettingsPage />);
  1123. await waitFor(() => {
  1124. expect(screen.getByPlaceholderText(/api\/frame\.jpeg\?src=printer/)).toBeInTheDocument();
  1125. });
  1126. });
  1127. it('hides the snapshot URL input when camera_type is snapshot (already a single-frame source)', async () => {
  1128. server.use(
  1129. http.get('/api/v1/printers/', () =>
  1130. HttpResponse.json([{ ...mjpegPrinter, external_camera_type: 'snapshot' }]),
  1131. ),
  1132. );
  1133. render(<SettingsPage />);
  1134. // Wait for the live-stream URL placeholder to render so we know the
  1135. // camera section finished mounting before asserting absence of the
  1136. // snapshot input below.
  1137. await waitFor(() => {
  1138. expect(screen.getByPlaceholderText(/Camera URL/i)).toBeInTheDocument();
  1139. });
  1140. expect(screen.queryByPlaceholderText(/api\/frame\.jpeg\?src=printer/)).not.toBeInTheDocument();
  1141. });
  1142. it(
  1143. 'PATCHes the printer with external_camera_snapshot_url when the user types into the input',
  1144. async () => {
  1145. let receivedBody: Record<string, unknown> | null = null;
  1146. server.use(
  1147. http.get('/api/v1/printers/', () => HttpResponse.json([mjpegPrinter])),
  1148. http.patch('/api/v1/printers/7', async ({ request }) => {
  1149. receivedBody = (await request.json()) as Record<string, unknown>;
  1150. return HttpResponse.json({ ...mjpegPrinter, ...receivedBody });
  1151. }),
  1152. );
  1153. render(<SettingsPage />);
  1154. const input = await waitFor(() =>
  1155. screen.getByPlaceholderText(/api\/frame\.jpeg\?src=printer/),
  1156. );
  1157. const user = userEvent.setup();
  1158. await user.type(input, 'http://192.168.1.61:1984/api/frame.jpeg?src=printer');
  1159. // Save is debounced by 800ms; assert the PATCH eventually fires with
  1160. // the typed snapshot URL.
  1161. await waitFor(
  1162. () => {
  1163. expect(receivedBody).not.toBeNull();
  1164. expect(receivedBody!.external_camera_snapshot_url).toBe(
  1165. 'http://192.168.1.61:1984/api/frame.jpeg?src=printer',
  1166. );
  1167. },
  1168. { timeout: 5000 },
  1169. );
  1170. },
  1171. // Per-test timeout raised to 15s — `user.type()` of a 49-char URL plus
  1172. // the 800ms save debounce fits in 5s locally (~2.3s typical) but blows
  1173. // past it on slow GitHub Actions runners (5000ms timeout was the failure
  1174. // mode on PR #1263).
  1175. 15_000,
  1176. );
  1177. });
  1178. describe('theme mode buttons', () => {
  1179. it('renders Dark, Light, and System buttons', async () => {
  1180. render(<SettingsPage />);
  1181. await waitFor(() => {
  1182. expect(screen.getByRole('button', { name: 'Dark' })).toBeInTheDocument();
  1183. expect(screen.getByRole('button', { name: 'Light' })).toBeInTheDocument();
  1184. expect(screen.getByRole('button', { name: 'System' })).toBeInTheDocument();
  1185. });
  1186. });
  1187. it('highlights the active mode button with green border', async () => {
  1188. render(<SettingsPage />);
  1189. const user = userEvent.setup();
  1190. await waitFor(() => {
  1191. expect(screen.getByRole('button', { name: 'System' })).toBeInTheDocument();
  1192. });
  1193. await user.click(screen.getByRole('button', { name: 'System' }));
  1194. await waitFor(() => {
  1195. const systemBtn = screen.getByRole('button', { name: 'System' });
  1196. expect(systemBtn.className).toContain('border-bambu-green');
  1197. });
  1198. });
  1199. it('clicking a theme button switches mode', async () => {
  1200. localStorage.setItem('theme-mode', 'dark');
  1201. render(<SettingsPage />);
  1202. const user = userEvent.setup();
  1203. await waitFor(() => {
  1204. const darkBtn = screen.getByRole('button', { name: 'Dark' });
  1205. expect(darkBtn.className).toContain('border-bambu-green');
  1206. });
  1207. const lightBtn = screen.getByRole('button', { name: 'Light' });
  1208. await user.click(lightBtn);
  1209. await waitFor(() => {
  1210. expect(lightBtn.className).toContain('border-bambu-green');
  1211. });
  1212. });
  1213. it('shows a toast when theme button is clicked', async () => {
  1214. render(<SettingsPage />);
  1215. const user = userEvent.setup();
  1216. await waitFor(() => {
  1217. expect(screen.getByRole('button', { name: 'System' })).toBeInTheDocument();
  1218. });
  1219. await user.click(screen.getByRole('button', { name: 'System' }));
  1220. await waitFor(() => {
  1221. expect(screen.getByText('Settings saved')).toBeInTheDocument();
  1222. });
  1223. });
  1224. });
  1225. // --------------------------------------------------------------------
  1226. // Slicer Pipelines (#1425) — Workflow tab sub-tabs
  1227. // --------------------------------------------------------------------
  1228. describe('workflow sub-tabs (#1425)', () => {
  1229. beforeEach(() => {
  1230. // Endpoints the Pipelines panel calls (#1425).
  1231. server.use(
  1232. http.get('/api/v1/slicer-pipelines/', () => HttpResponse.json({ pipelines: [] })),
  1233. http.get('/api/v1/slicer/presets', () =>
  1234. HttpResponse.json({
  1235. orca_cloud: { printer: [], process: [], filament: [] },
  1236. cloud: { printer: [], process: [], filament: [] },
  1237. local: { printer: [], process: [], filament: [] },
  1238. standard: { printer: [], process: [], filament: [] },
  1239. cloud_status: 'ok',
  1240. orca_cloud_status: 'ok',
  1241. }),
  1242. ),
  1243. );
  1244. });
  1245. it('renders Queue & Dispatch + Pipelines sub-tabs under Workflow', async () => {
  1246. render(<SettingsPage />);
  1247. const user = userEvent.setup();
  1248. await waitFor(() => {
  1249. // Workflow tab in the sidebar — exact match to avoid colliding with
  1250. // "Print Queue" or "Queue Settings" labels elsewhere on the page.
  1251. expect(screen.getByRole('button', { name: 'Workflow' })).toBeInTheDocument();
  1252. });
  1253. await user.click(screen.getByRole('button', { name: 'Workflow' }));
  1254. await waitFor(() => {
  1255. expect(screen.getByRole('button', { name: /Queue & Dispatch/i })).toBeInTheDocument();
  1256. expect(screen.getByRole('button', { name: /^Pipelines$/i })).toBeInTheDocument();
  1257. });
  1258. });
  1259. it('clicking Pipelines sub-tab shows the empty-state hint and updates the URL', async () => {
  1260. render(<SettingsPage />);
  1261. const user = userEvent.setup();
  1262. await waitFor(() => expect(screen.getByRole('button', { name: 'Workflow' })).toBeInTheDocument());
  1263. await user.click(screen.getByRole('button', { name: 'Workflow' }));
  1264. await user.click(screen.getByRole('button', { name: /^Pipelines$/i }));
  1265. await waitFor(() => {
  1266. expect(screen.getByText(/No pipelines yet/i)).toBeInTheDocument();
  1267. // Deep-link URL carries both ?tab=queue and ?sub=pipelines
  1268. expect(window.location.search).toContain('tab=queue');
  1269. expect(window.location.search).toContain('sub=pipelines');
  1270. });
  1271. });
  1272. });
  1273. });
  1274. /**
  1275. * Sponsor banner on Settings -> General.
  1276. *
  1277. * Below the fleet threshold it makes the community/donation ask; at or above it
  1278. * the same slot makes the commercial ask and points at business.html. A print
  1279. * farm asked to chip in $5 is a wasted impression, and a hobbyist pitched a
  1280. * support contract is an annoyed user — so both directions are pinned.
  1281. */
  1282. describe('SettingsPage — sponsor banner audience', () => {
  1283. beforeEach(() => {
  1284. // BrowserRouter shares window.location across tests and the banner only
  1285. // renders on the General tab — without this reset a prior test's ?tab=queue
  1286. // leaks in and the banner never mounts.
  1287. window.history.replaceState({}, '', '/');
  1288. });
  1289. const fleet = (count: number) =>
  1290. server.use(
  1291. http.get('/api/v1/printers/', () =>
  1292. HttpResponse.json(
  1293. Array.from({ length: count }, (_, i) => ({
  1294. id: i + 1,
  1295. name: `Printer ${i + 1}`,
  1296. serial_number: `SN${i + 1}`,
  1297. ip_address: '192.168.1.10',
  1298. model: 'X1C',
  1299. is_active: true,
  1300. })),
  1301. ),
  1302. ),
  1303. );
  1304. it('shows the community ask for a small fleet', async () => {
  1305. fleet(2);
  1306. render(<SettingsPage />);
  1307. const banner = await screen.findByRole('link', { name: /Independent & community-funded/i });
  1308. expect(banner).toHaveAttribute('href', 'https://bambuddy.cool/sponsors.html?from=app-settings');
  1309. expect(screen.queryByText(/Bambuddy for business/i)).not.toBeInTheDocument();
  1310. });
  1311. it('shows the commercial ask for a business-sized fleet', async () => {
  1312. fleet(6);
  1313. render(<SettingsPage />);
  1314. const banner = await screen.findByRole('link', { name: /Bambuddy for business/i });
  1315. expect(banner).toHaveAttribute('href', 'https://bambuddy.cool/business.html?from=app-settings');
  1316. // The donation copy is replaced, not merely supplemented.
  1317. expect(screen.queryByText(/Independent & community-funded/i)).not.toBeInTheDocument();
  1318. // The ask names the fleet back to them.
  1319. expect(screen.getByText(/6 printers/i)).toBeInTheDocument();
  1320. });
  1321. });
  1322. describe('SettingsPage — settings changed outside the page (#2716)', () => {
  1323. const restoreLabel = 'Restore plate for finish photo';
  1324. // external_url is deliberately populated: when the server has none the page
  1325. // detects one from the browser and saves it unprompted, which would show up
  1326. // as a PUT in tests that assert none was made. That behaviour has its own
  1327. // test at the end of this block.
  1328. const baseSettings = { ...mockSettings, external_url: window.location.origin };
  1329. let queryClient: QueryClient;
  1330. let puts: Record<string, unknown>[];
  1331. let served: Record<string, unknown>;
  1332. function renderPage() {
  1333. queryClient = new QueryClient({
  1334. defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false } },
  1335. });
  1336. return rtlRender(
  1337. <QueryClientProvider client={queryClient}>
  1338. <BrowserRouter>
  1339. <AuthProvider>
  1340. <ThemeProvider>
  1341. <ToastProvider>
  1342. <SettingsPage />
  1343. </ToastProvider>
  1344. </ThemeProvider>
  1345. </AuthProvider>
  1346. </BrowserRouter>
  1347. </QueryClientProvider>
  1348. );
  1349. }
  1350. /** Change the settings row server-side and let the page's query observe it. */
  1351. async function changeOnServer(patch: Record<string, unknown>) {
  1352. served = { ...served, ...patch };
  1353. await act(async () => {
  1354. await queryClient.invalidateQueries({ queryKey: ['settings'] });
  1355. });
  1356. }
  1357. /** Wait out the 100ms initial-load suppression, then flip a checkbox. */
  1358. async function toggleRestorePlate() {
  1359. const label = await screen.findByText(restoreLabel);
  1360. await new Promise((resolve) => setTimeout(resolve, 200));
  1361. const row = label.closest('div')!.parentElement!;
  1362. await userEvent.click(within(row).getByRole('checkbox'));
  1363. }
  1364. beforeEach(() => {
  1365. window.history.replaceState({}, '', '/');
  1366. localStorage.clear();
  1367. setAuthToken(null);
  1368. puts = [];
  1369. served = { ...baseSettings };
  1370. server.use(
  1371. http.get('/api/v1/settings/', () => HttpResponse.json(served)),
  1372. http.put('/api/v1/settings/', async ({ request }) => {
  1373. const body = (await request.json()) as Record<string, unknown>;
  1374. puts.push(body);
  1375. served = { ...served, ...body };
  1376. return HttpResponse.json(served);
  1377. })
  1378. );
  1379. });
  1380. it('does not write its stale copy back over a server-side change', async () => {
  1381. // The defect: the page diffed the live query cache against its own copy, so
  1382. // a refetch that carried someone else's change read as a local edit and was
  1383. // reverted ~500ms later with no user interaction at all.
  1384. renderPage();
  1385. await screen.findByText(restoreLabel);
  1386. await new Promise((resolve) => setTimeout(resolve, 200));
  1387. await changeOnServer({ currency: 'EUR' });
  1388. // Well past the 500ms debounce.
  1389. await new Promise((resolve) => setTimeout(resolve, 1200));
  1390. expect(puts).toEqual([]);
  1391. });
  1392. it('adopts the server value, so a later save carries it rather than the stale one', async () => {
  1393. renderPage();
  1394. await new Promise((resolve) => setTimeout(resolve, 200));
  1395. await changeOnServer({ currency: 'EUR' });
  1396. await toggleRestorePlate();
  1397. await waitFor(() => expect(puts).toHaveLength(1), { timeout: 3000 });
  1398. // The user's edit is saved...
  1399. expect(puts[0].finish_photo_restore_plate).toBe(false);
  1400. // ...and the field they never touched goes back as the server's value, not
  1401. // the USD the page loaded with.
  1402. expect(puts[0].currency).toBe('EUR');
  1403. });
  1404. it('never reverts a pending user edit that the server changed too', async () => {
  1405. renderPage();
  1406. await toggleRestorePlate();
  1407. // Lands while the edit is still sitting in the 500ms debounce, i.e. before
  1408. // the page has committed it. Adopting the server's value here would throw
  1409. // the edit away silently.
  1410. await changeOnServer({ finish_photo_restore_plate: true });
  1411. await waitFor(() => expect(puts.length).toBeGreaterThan(0), { timeout: 3000 });
  1412. await new Promise((resolve) => setTimeout(resolve, 1200));
  1413. // Asserted over every request rather than a particular one: whichever order
  1414. // the refetch and the debounce happen to land in, no write may carry the
  1415. // server's value back over the user's.
  1416. expect(puts.map((p) => p.finish_photo_restore_plate)).toEqual(puts.map(() => false));
  1417. });
  1418. it('saves once per edit — the baseline moves with the saved row', async () => {
  1419. // Guards the failure mode the baseline introduces if it is not advanced on
  1420. // save: every render would diff against the pre-save snapshot and re-send.
  1421. renderPage();
  1422. await toggleRestorePlate();
  1423. await waitFor(() => expect(puts).toHaveLength(1), { timeout: 3000 });
  1424. await new Promise((resolve) => setTimeout(resolve, 1500));
  1425. expect(puts).toHaveLength(1);
  1426. });
  1427. it('still persists the external_url it detects from the browser', async () => {
  1428. // The page seeds external_url from window.location.origin when the server
  1429. // has none and relies on the auto-save to persist it. That only works
  1430. // because the baseline is the raw server row: seed the baseline from the
  1431. // adjusted copy instead and the detected URL matches it, so nothing ever
  1432. // marks it as needing a save.
  1433. served = { ...mockSettings };
  1434. renderPage();
  1435. await screen.findByText(restoreLabel);
  1436. await new Promise((resolve) => setTimeout(resolve, 200));
  1437. // A refetch carrying a field this page does not manage. It is enough to
  1438. // re-run the diff, and the only thing that differs is the detected URL.
  1439. await changeOnServer({ spoolman_url: 'http://spoolman.example' });
  1440. await waitFor(() => expect(puts).toHaveLength(1), { timeout: 3000 });
  1441. expect(puts[0].external_url).toBe(window.location.origin);
  1442. });
  1443. });