SettingsPage.test.tsx 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  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. ams_temp_alarm: null,
  29. time_format: 'system',
  30. date_format: 'system',
  31. mqtt_enabled: false,
  32. mqtt_host: '',
  33. mqtt_port: 1883,
  34. spoolman_enabled: false,
  35. spoolman_url: '',
  36. ha_enabled: false,
  37. ha_url: '',
  38. ha_token: '',
  39. check_updates: false,
  40. check_printer_firmware: false,
  41. bed_cooled_threshold: 35,
  42. };
  43. describe('SettingsPage', () => {
  44. beforeEach(() => {
  45. // BrowserRouter shares window.location across tests; reset it so a tab
  46. // switch in one test (e.g. clicking "Workflow") doesn't carry into
  47. // sibling tests that expect to land on the default General tab.
  48. window.history.replaceState({}, '', '/');
  49. vi.mocked(localStorage.getItem).mockReset();
  50. vi.mocked(localStorage.setItem).mockReset();
  51. vi.mocked(localStorage.removeItem).mockReset();
  52. vi.mocked(localStorage.clear).mockReset();
  53. localStorage.clear();
  54. setAuthToken(null);
  55. server.use(
  56. http.get('/api/v1/settings/', () => {
  57. return HttpResponse.json(mockSettings);
  58. }),
  59. http.put('/api/v1/settings/', async ({ request }) => {
  60. const body = await request.json();
  61. return HttpResponse.json({ ...mockSettings, ...body });
  62. }),
  63. http.get('/api/v1/printers/', () => {
  64. return HttpResponse.json([]);
  65. }),
  66. http.get('/api/v1/smart-plugs/', () => {
  67. return HttpResponse.json([]);
  68. }),
  69. http.get('/api/v1/notifications/', () => {
  70. return HttpResponse.json([]);
  71. }),
  72. http.get('/api/v1/api-keys/', () => {
  73. return HttpResponse.json([]);
  74. }),
  75. http.get('/api/v1/mqtt/status', () => {
  76. return HttpResponse.json({ enabled: false });
  77. }),
  78. http.get('/api/v1/virtual-printer/status', () => {
  79. return HttpResponse.json({ running: false });
  80. }),
  81. http.get('/api/v1/auth/status', () => {
  82. return HttpResponse.json({ auth_enabled: false, requires_setup: false });
  83. }),
  84. http.get('/api/v1/external-links/', () => {
  85. return HttpResponse.json([]);
  86. })
  87. );
  88. });
  89. describe('rendering', () => {
  90. it('renders the page title', async () => {
  91. render(<SettingsPage />);
  92. await waitFor(() => {
  93. // Use role-based query to avoid conflicts with dropdown options
  94. expect(screen.getByRole('heading', { name: 'Settings' })).toBeInTheDocument();
  95. });
  96. });
  97. it('shows settings tabs', async () => {
  98. render(<SettingsPage />);
  99. await waitFor(() => {
  100. // Use getAllByText since "General" appears both as tab and section heading
  101. expect(screen.getAllByText('General').length).toBeGreaterThan(0);
  102. expect(screen.getByText('Smart Plugs')).toBeInTheDocument();
  103. expect(screen.getAllByText('Notifications').length).toBeGreaterThan(0);
  104. expect(screen.getAllByText('Filament').length).toBeGreaterThan(0);
  105. expect(screen.getByText('Network')).toBeInTheDocument();
  106. expect(screen.getByText('API Keys')).toBeInTheDocument();
  107. });
  108. });
  109. });
  110. describe('finish photo plate restore (#2547)', () => {
  111. const restoreLabel = 'Restore plate for finish photo';
  112. it('offers the toggle while finish photos are enabled', async () => {
  113. render(<SettingsPage />);
  114. expect(await screen.findByText(restoreLabel)).toBeInTheDocument();
  115. });
  116. it('hides the toggle when finish photos are switched off', async () => {
  117. // It only describes how the finish photo is framed, so it is meaningless
  118. // when no finish photo is taken at all.
  119. server.use(
  120. http.get('/api/v1/settings/', () =>
  121. HttpResponse.json({ ...mockSettings, capture_finish_photo: false })
  122. )
  123. );
  124. render(<SettingsPage />);
  125. await screen.findByRole('heading', { name: 'Settings' });
  126. await waitFor(() => {
  127. expect(screen.queryByText(restoreLabel)).not.toBeInTheDocument();
  128. });
  129. });
  130. it('defaults to on when the backend has never stored the setting', async () => {
  131. // Existing installs have no row for it; the UI must not read that as off.
  132. render(<SettingsPage />);
  133. const label = await screen.findByText(restoreLabel);
  134. const row = label.closest('div')!.parentElement!;
  135. expect(within(row).getByRole('checkbox')).toBeChecked();
  136. });
  137. it('sends the new value on save', async () => {
  138. let saved: Record<string, unknown> | null = null;
  139. server.use(
  140. http.put('/api/v1/settings/', async ({ request }) => {
  141. saved = (await request.json()) as Record<string, unknown>;
  142. return HttpResponse.json({ ...mockSettings, ...saved });
  143. })
  144. );
  145. render(<SettingsPage />);
  146. const label = await screen.findByText(restoreLabel);
  147. // The page suppresses auto-save for 100ms after the settings load, so a
  148. // click landing inside that window is swallowed with no re-trigger.
  149. await new Promise((resolve) => setTimeout(resolve, 200));
  150. const row = label.closest('div')!.parentElement!;
  151. await userEvent.click(within(row).getByRole('checkbox'));
  152. // The page auto-saves on a 500ms debounce, so the default 1s waitFor
  153. // window is only just wide enough — give the request room to land.
  154. await waitFor(() => {
  155. expect(saved).not.toBeNull();
  156. }, { timeout: 3000 });
  157. expect(saved!.finish_photo_restore_plate).toBe(false);
  158. });
  159. });
  160. describe('general settings', () => {
  161. it('shows date format setting', async () => {
  162. render(<SettingsPage />);
  163. await waitFor(() => {
  164. expect(screen.getByText('Date Format')).toBeInTheDocument();
  165. });
  166. });
  167. it('shows time format setting', async () => {
  168. render(<SettingsPage />);
  169. await waitFor(() => {
  170. expect(screen.getByText('Time Format')).toBeInTheDocument();
  171. });
  172. });
  173. it('no longer offers Camera View Mode, which moved to the printer card', async () => {
  174. // The camera button on each printer card is a split control now, so the
  175. // choice is made per stream rather than once for the whole install. The
  176. // External Cameras section is still here, which is what keeps this from
  177. // passing merely because the Camera card failed to render.
  178. render(<SettingsPage />);
  179. await waitFor(() => {
  180. expect(screen.getByText('External Cameras')).toBeInTheDocument();
  181. });
  182. expect(screen.queryByText('Camera View Mode')).toBeNull();
  183. });
  184. it('shows default printer setting', async () => {
  185. render(<SettingsPage />);
  186. await waitFor(() => {
  187. expect(screen.getByText('Default Printer')).toBeInTheDocument();
  188. });
  189. });
  190. it('shows preferred slicer setting on Workflow tab', async () => {
  191. const user = userEvent.setup();
  192. render(<SettingsPage />);
  193. await waitFor(() => {
  194. expect(screen.getByText('Workflow')).toBeInTheDocument();
  195. });
  196. await user.click(screen.getByText('Workflow'));
  197. await waitFor(() => {
  198. expect(screen.getByText('Preferred Slicer')).toBeInTheDocument();
  199. });
  200. });
  201. it('shows slicer dropdown with both options on Workflow tab', async () => {
  202. const user = userEvent.setup();
  203. render(<SettingsPage />);
  204. await waitFor(() => {
  205. expect(screen.getByText('Workflow')).toBeInTheDocument();
  206. });
  207. await user.click(screen.getByText('Workflow'));
  208. await waitFor(() => {
  209. const slicerSelect = screen.getAllByDisplayValue('Bambu Studio');
  210. expect(slicerSelect.length).toBeGreaterThan(0);
  211. });
  212. });
  213. it('shows appearance section', async () => {
  214. render(<SettingsPage />);
  215. await waitFor(() => {
  216. expect(screen.getByText('Appearance')).toBeInTheDocument();
  217. });
  218. });
  219. it('shows updates section with firmware toggle', async () => {
  220. render(<SettingsPage />);
  221. await waitFor(() => {
  222. expect(screen.getByText('Updates')).toBeInTheDocument();
  223. expect(screen.getByText('Check for updates')).toBeInTheDocument();
  224. expect(screen.getByText('Check printer firmware')).toBeInTheDocument();
  225. });
  226. });
  227. it('hides a Bambuddy sidebar page from Sidebar', async () => {
  228. const user = userEvent.setup();
  229. render(<SettingsPage />);
  230. await screen.findByRole('heading', { name: 'Sidebar' });
  231. await screen.findAllByText('Visible in sidebar');
  232. vi.mocked(localStorage.setItem).mockClear();
  233. await user.click((await screen.findAllByLabelText('Hide page'))[0]);
  234. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, JSON.stringify(['printers']));
  235. expect(screen.getByText('Hidden from sidebar')).toBeInTheDocument();
  236. });
  237. it('shows a previously hidden Bambuddy sidebar page from Sidebar', async () => {
  238. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  239. if (key === SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY) return JSON.stringify(['printers']);
  240. return null;
  241. });
  242. const user = userEvent.setup();
  243. render(<SettingsPage />);
  244. await screen.findByRole('heading', { name: 'Sidebar' });
  245. await screen.findByText('Hidden from sidebar');
  246. vi.mocked(localStorage.setItem).mockClear();
  247. await user.click(await screen.findByLabelText('Show page'));
  248. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, JSON.stringify([]));
  249. expect(screen.getAllByText('Visible in sidebar').length).toBeGreaterThan(0);
  250. });
  251. it('does not allow Settings to be hidden from Sidebar', async () => {
  252. render(<SettingsPage />);
  253. await screen.findByRole('heading', { name: 'Sidebar' });
  254. await screen.findByText('Required in sidebar');
  255. const settingsVisibilityButton = await screen.findByLabelText('Settings cannot be hidden');
  256. expect(settingsVisibilityButton).toBeDisabled();
  257. expect(screen.getByText('Required in sidebar')).toBeInTheDocument();
  258. });
  259. it('presents external links and Bambuddy pages in saved sidebar order', async () => {
  260. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  261. if (key === SIDEBAR_ORDER_KEY) return JSON.stringify(['ext-7', 'printers', 'settings']);
  262. return null;
  263. });
  264. server.use(
  265. http.get('/api/v1/external-links/', () =>
  266. HttpResponse.json([
  267. {
  268. id: 7,
  269. name: 'Docs',
  270. url: 'https://docs.example.test',
  271. icon: 'Link',
  272. open_in_new_tab: true,
  273. custom_icon: null,
  274. sort_order: 0,
  275. created_at: '2026-01-01T00:00:00Z',
  276. updated_at: '2026-01-01T00:00:00Z',
  277. },
  278. ]),
  279. ),
  280. );
  281. render(<SettingsPage />);
  282. await screen.findByRole('heading', { name: 'Sidebar' });
  283. const docs = await screen.findByText('Docs');
  284. const printers = screen.getAllByText('Printers').find(element => element.closest('[draggable="true"]'));
  285. expect(printers).toBeDefined();
  286. expect(docs.compareDocumentPosition(printers) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
  287. });
  288. it('saves mixed Sidebar order when items are dragged', async () => {
  289. server.use(
  290. http.get('/api/v1/external-links/', () =>
  291. HttpResponse.json([
  292. {
  293. id: 7,
  294. name: 'Docs',
  295. url: 'https://docs.example.test',
  296. icon: 'Link',
  297. open_in_new_tab: true,
  298. custom_icon: null,
  299. sort_order: 0,
  300. created_at: '2026-01-01T00:00:00Z',
  301. updated_at: '2026-01-01T00:00:00Z',
  302. },
  303. ]),
  304. ),
  305. );
  306. render(<SettingsPage />);
  307. await screen.findByRole('heading', { name: 'Sidebar' });
  308. const docsRow = (await screen.findByText('Docs')).closest('[draggable="true"]');
  309. const printersRow = screen.getAllByText('Printers')
  310. .find(element => element.closest('[draggable="true"]'))
  311. ?.closest('[draggable="true"]');
  312. expect(docsRow).not.toBeNull();
  313. expect(printersRow).not.toBeNull();
  314. vi.mocked(localStorage.setItem).mockClear();
  315. const dataTransfer = {
  316. effectAllowed: '',
  317. dropEffect: '',
  318. setData: vi.fn(),
  319. };
  320. fireEvent.dragStart(docsRow!, { dataTransfer });
  321. fireEvent.dragOver(printersRow!, { dataTransfer });
  322. fireEvent.drop(printersRow!, { dataTransfer });
  323. expect(localStorage.setItem).toHaveBeenCalledWith(
  324. SIDEBAR_ORDER_KEY,
  325. JSON.stringify(['ext-7', 'printers', 'inventory', 'archives', 'queue', 'projects', 'files', 'makerworld', 'profiles', 'maintenance', 'stats', 'finance', 'notifications', 'settings']),
  326. );
  327. });
  328. it('resets Sidebar to all pages first and configured links at the bottom', async () => {
  329. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  330. if (key === SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY) return JSON.stringify(['printers', 'stats']);
  331. if (key === SIDEBAR_ORDER_KEY) return JSON.stringify(['ext-7', 'settings', 'printers']);
  332. return null;
  333. });
  334. server.use(
  335. http.get('/api/v1/external-links/', () =>
  336. HttpResponse.json([
  337. {
  338. id: 7,
  339. name: 'Docs',
  340. url: 'https://docs.example.test',
  341. icon: 'Link',
  342. open_in_new_tab: true,
  343. custom_icon: null,
  344. sort_order: 0,
  345. created_at: '2026-01-01T00:00:00Z',
  346. updated_at: '2026-01-01T00:00:00Z',
  347. },
  348. ]),
  349. ),
  350. );
  351. const user = userEvent.setup();
  352. render(<SettingsPage />);
  353. const heading = await screen.findByRole('heading', { name: 'Sidebar' });
  354. const card = heading.closest('#card-sidebar-links');
  355. expect(card).not.toBeNull();
  356. await screen.findByText('Docs');
  357. vi.mocked(localStorage.setItem).mockClear();
  358. await user.click(within(card as HTMLElement).getByRole('button', { name: /reset/i }));
  359. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, JSON.stringify([]));
  360. expect(localStorage.setItem).toHaveBeenCalledWith(
  361. SIDEBAR_ORDER_KEY,
  362. JSON.stringify(['printers', 'inventory', 'archives', 'queue', 'projects', 'files', 'makerworld', 'profiles', 'maintenance', 'stats', 'finance', 'notifications', 'settings', 'ext-7']),
  363. );
  364. const settingsRow = screen.getAllByText('Settings')
  365. .find(element => element.closest('[draggable="true"]'))
  366. ?.closest('[draggable="true"]');
  367. const docsRow = screen.getByText('Docs').closest('[draggable="true"]');
  368. expect(settingsRow).not.toBeNull();
  369. expect(docsRow).not.toBeNull();
  370. expect(settingsRow!.compareDocumentPosition(docsRow!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
  371. expect(screen.queryByText('Hidden from sidebar')).not.toBeInTheDocument();
  372. });
  373. it('sets the current Sidebar order as the backend default for settings admins', async () => {
  374. let defaultSidebarOrderPayload: string | null = null;
  375. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  376. if (key === SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY) return JSON.stringify(['stats']);
  377. return null;
  378. });
  379. server.use(
  380. http.get('/api/v1/auth/status', () =>
  381. HttpResponse.json({ auth_enabled: true, requires_setup: false }),
  382. ),
  383. http.get('/api/v1/auth/me', () =>
  384. HttpResponse.json({
  385. id: 1,
  386. username: 'admin',
  387. role: 'admin',
  388. is_active: true,
  389. is_admin: false,
  390. groups: [{ id: 1, name: 'Administrators' }],
  391. permissions: ['settings:update'],
  392. created_at: '2026-01-01T00:00:00Z',
  393. }),
  394. ),
  395. http.get('/api/v1/settings/', () =>
  396. HttpResponse.json({ ...mockSettings, default_sidebar_order: '' }),
  397. ),
  398. http.put('/api/v1/settings/', async ({ request }) => {
  399. const body = await request.json() as { default_sidebar_order?: string };
  400. defaultSidebarOrderPayload = body.default_sidebar_order ?? null;
  401. return HttpResponse.json({ ...mockSettings, ...body });
  402. }),
  403. );
  404. setAuthToken('test-token');
  405. const user = userEvent.setup();
  406. render(<SettingsPage />);
  407. const heading = await screen.findByRole('heading', { name: 'Sidebar' });
  408. const card = heading.closest('#card-sidebar-links');
  409. expect(card).not.toBeNull();
  410. await user.click(within(card as HTMLElement).getByRole('switch', { name: 'Set Default' }));
  411. await waitFor(() => {
  412. expect(defaultSidebarOrderPayload).not.toBeNull();
  413. });
  414. expect(JSON.parse(defaultSidebarOrderPayload!)).toEqual({
  415. order: [
  416. 'printers',
  417. 'inventory',
  418. 'archives',
  419. 'queue',
  420. 'projects',
  421. 'files',
  422. 'makerworld',
  423. 'profiles',
  424. 'maintenance',
  425. 'stats',
  426. 'finance',
  427. 'notifications',
  428. 'settings',
  429. ],
  430. hiddenSystemItemIds: ['stats'],
  431. });
  432. });
  433. });
  434. describe('update CTA per deployment shape', () => {
  435. // The update card branches on the deployment shape returned by
  436. // /updates/check. Each branch is mutually exclusive — verify the right
  437. // one wins so HA addon users never see the docker-compose snippet
  438. // (which they can't run from inside an HA addon container) and Docker
  439. // users never see the in-app Install button (which would no-op).
  440. const renderWithUpdateCheck = async (
  441. checkBody: Record<string, unknown>,
  442. settingsOverrides: Record<string, unknown> = {},
  443. ) => {
  444. server.use(
  445. http.get('/api/v1/settings/', () =>
  446. HttpResponse.json({ ...mockSettings, check_updates: true, ...settingsOverrides }),
  447. ),
  448. http.get('/api/v1/updates/check', () => HttpResponse.json(checkBody)),
  449. );
  450. render(<SettingsPage />);
  451. await waitFor(() => {
  452. expect(screen.getByText('Updates')).toBeInTheDocument();
  453. });
  454. };
  455. it('shows the HA Supervisor message when running as an HA addon', async () => {
  456. await renderWithUpdateCheck({
  457. update_available: true,
  458. current_version: '0.2.4',
  459. latest_version: '0.2.5',
  460. release_name: '0.2.5',
  461. release_notes: '',
  462. release_url: 'https://example.invalid/r',
  463. published_at: '2099-01-01T00:00:00Z',
  464. is_docker: true,
  465. is_ha_addon: true,
  466. update_method: 'ha_addon',
  467. });
  468. await waitFor(() => {
  469. expect(
  470. screen.getByText(/Home Assistant Supervisor/i),
  471. ).toBeInTheDocument();
  472. });
  473. // Docker hint must NOT render — HA branch wins.
  474. expect(screen.queryByText('docker compose pull && docker compose up -d')).not.toBeInTheDocument();
  475. expect(screen.queryByRole('button', { name: /install update/i })).not.toBeInTheDocument();
  476. });
  477. it('shows the docker-compose snippet for Docker (non-HA) deployments', async () => {
  478. await renderWithUpdateCheck({
  479. update_available: true,
  480. current_version: '0.2.4',
  481. latest_version: '0.2.5',
  482. release_name: '0.2.5',
  483. release_notes: '',
  484. release_url: 'https://example.invalid/r',
  485. published_at: '2099-01-01T00:00:00Z',
  486. is_docker: true,
  487. is_ha_addon: false,
  488. update_method: 'docker',
  489. });
  490. await waitFor(() => {
  491. expect(screen.getByText('docker compose pull && docker compose up -d')).toBeInTheDocument();
  492. });
  493. expect(screen.queryByText(/Home Assistant Supervisor/i)).not.toBeInTheDocument();
  494. expect(screen.queryByRole('button', { name: /install update/i })).not.toBeInTheDocument();
  495. });
  496. // #2664: the bare command only works if the user is already standing in
  497. // the directory holding their compose file, which is exactly the thing
  498. // they came to the page not knowing.
  499. const DOCKER_CHECK = {
  500. update_available: true,
  501. current_version: '0.2.4',
  502. latest_version: '0.2.5',
  503. release_name: '0.2.5',
  504. release_notes: '',
  505. release_url: 'https://example.invalid/r',
  506. published_at: '2099-01-01T00:00:00Z',
  507. is_docker: true,
  508. is_ha_addon: false,
  509. update_method: 'docker',
  510. };
  511. it('prefixes the command with cd when the backend detected a compose directory', async () => {
  512. await renderWithUpdateCheck({ ...DOCKER_CHECK, compose_dir_detected: '/opt/bambuddy' });
  513. await waitFor(() => {
  514. expect(
  515. screen.getByText('cd /opt/bambuddy && docker compose pull && docker compose up -d'),
  516. ).toBeInTheDocument();
  517. });
  518. });
  519. it('prefers the saved directory over the detected one', async () => {
  520. await renderWithUpdateCheck(
  521. { ...DOCKER_CHECK, compose_dir_detected: '/opt/guessed' },
  522. { docker_compose_dir: '/srv/stacks/bambuddy' },
  523. );
  524. await waitFor(() => {
  525. expect(
  526. screen.getByText('cd /srv/stacks/bambuddy && docker compose pull && docker compose up -d'),
  527. ).toBeInTheDocument();
  528. });
  529. expect(screen.queryByText(/\/opt\/guessed/)).not.toBeInTheDocument();
  530. });
  531. it('quotes a directory containing a space so the cd does not split', async () => {
  532. await renderWithUpdateCheck(DOCKER_CHECK, { docker_compose_dir: '/srv/bambu buddy' });
  533. await waitFor(() => {
  534. expect(
  535. screen.getByText('cd "/srv/bambu buddy" && docker compose pull && docker compose up -d'),
  536. ).toBeInTheDocument();
  537. });
  538. });
  539. it('copies the full command including the cd', async () => {
  540. const writeText = vi.fn().mockResolvedValue(undefined);
  541. Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
  542. Object.defineProperty(window, 'isSecureContext', { value: true, configurable: true });
  543. await renderWithUpdateCheck({ ...DOCKER_CHECK, compose_dir_detected: '/opt/bambuddy' });
  544. const copy = await screen.findByRole('button', { name: /copy update command/i });
  545. await userEvent.click(copy);
  546. expect(writeText).toHaveBeenCalledWith(
  547. 'cd /opt/bambuddy && docker compose pull && docker compose up -d',
  548. );
  549. });
  550. it('offers an editable compose directory field seeded with the detected path', async () => {
  551. await renderWithUpdateCheck({ ...DOCKER_CHECK, compose_dir_detected: '/opt/bambuddy' });
  552. const field = await screen.findByPlaceholderText('/opt/bambuddy');
  553. // Placeholder, not value — the detected path is a guess the user has
  554. // not accepted, so saving must not silently adopt it.
  555. expect(field).toHaveValue('');
  556. });
  557. it('shows the installer-download link for Windows installer installs', async () => {
  558. const downloadUrl =
  559. 'https://github.com/maziggy/bambuddy/releases/download/v0.2.5/bambuddy-0.2.5-windows-x64-setup.exe';
  560. await renderWithUpdateCheck({
  561. update_available: true,
  562. current_version: '0.2.4',
  563. latest_version: '0.2.5',
  564. release_name: '0.2.5',
  565. release_notes: '',
  566. release_url: 'https://github.com/maziggy/bambuddy/releases/tag/v0.2.5',
  567. published_at: '2099-01-01T00:00:00Z',
  568. is_docker: false,
  569. is_ha_addon: false,
  570. is_windows_installer: true,
  571. update_method: 'windows_installer',
  572. installer_download_url: downloadUrl,
  573. });
  574. const link = await screen.findByRole('link', { name: /download installer for v0\.2\.5/i });
  575. expect(link).toHaveAttribute('href', downloadUrl);
  576. expect(link).toHaveAttribute('target', '_blank');
  577. expect(link).toHaveAttribute('rel', expect.stringContaining('noopener'));
  578. // The in-app update button must NOT render — the git-fetch path can't
  579. // work from an installer payload.
  580. expect(screen.queryByRole('button', { name: /install update/i })).not.toBeInTheDocument();
  581. expect(screen.queryByText(/Home Assistant Supervisor/i)).not.toBeInTheDocument();
  582. expect(screen.queryByText('docker compose pull && docker compose up -d')).not.toBeInTheDocument();
  583. });
  584. });
  585. describe('tabs navigation', () => {
  586. it('can switch to Network tab', async () => {
  587. const user = userEvent.setup();
  588. render(<SettingsPage />);
  589. // Wait for settings to load first
  590. await waitFor(() => {
  591. expect(screen.getByText('Date Format')).toBeInTheDocument();
  592. });
  593. await user.click(screen.getByText('Network'));
  594. await waitFor(() => {
  595. // Network tab contains MQTT Publishing section
  596. expect(screen.getByText('MQTT Publishing')).toBeInTheDocument();
  597. });
  598. });
  599. it('can switch to Smart Plugs tab', async () => {
  600. const user = userEvent.setup();
  601. render(<SettingsPage />);
  602. await waitFor(() => {
  603. expect(screen.getByText('Smart Plugs')).toBeInTheDocument();
  604. });
  605. await user.click(screen.getByText('Smart Plugs'));
  606. await waitFor(() => {
  607. expect(screen.getByText('Add Smart Plug')).toBeInTheDocument();
  608. });
  609. });
  610. it('can switch to Notifications tab', async () => {
  611. const user = userEvent.setup();
  612. render(<SettingsPage />);
  613. await waitFor(() => {
  614. expect(screen.getAllByText('Notifications').length).toBeGreaterThan(0);
  615. });
  616. // Click the tab button (not the mobile dropdown option)
  617. const notificationButtons = screen.getAllByText('Notifications');
  618. const tabButton = notificationButtons.find(el => el.tagName === 'BUTTON') || notificationButtons[0];
  619. await user.click(tabButton);
  620. await waitFor(() => {
  621. expect(screen.getByText('Add Provider')).toBeInTheDocument();
  622. });
  623. });
  624. it('can switch to Filament tab', async () => {
  625. const user = userEvent.setup();
  626. render(<SettingsPage />);
  627. await waitFor(() => {
  628. expect(screen.getAllByText('Filament').length).toBeGreaterThan(0);
  629. });
  630. await user.click(screen.getAllByText('Filament')[0]);
  631. await waitFor(() => {
  632. expect(screen.getByText('AMS Display Thresholds')).toBeInTheDocument();
  633. });
  634. });
  635. // #2770: an AMS reads 15-20% while its own heater runs, so a drying
  636. // threshold set below that can never be met and auto-drying ends one
  637. // cycle only to arm the next. The default of 60 must stay quiet.
  638. const openFilamentTab = async (humidityFair: number) => {
  639. server.use(
  640. http.get('/api/v1/settings/', () =>
  641. HttpResponse.json({ ...mockSettings, ams_humidity_fair: humidityFair })
  642. )
  643. );
  644. const user = userEvent.setup();
  645. render(<SettingsPage />);
  646. await waitFor(() => {
  647. expect(screen.getAllByText('Filament').length).toBeGreaterThan(0);
  648. });
  649. await user.click(screen.getAllByText('Filament')[0]);
  650. await waitFor(() => {
  651. expect(screen.getByText('AMS Display Thresholds')).toBeInTheDocument();
  652. });
  653. };
  654. it('warns when the humidity threshold is below what a drying AMS reports', async () => {
  655. await openFilamentTab(14);
  656. expect(await screen.findByText(/Auto-drying cannot reach this value/)).toBeInTheDocument();
  657. });
  658. it('stays quiet for a humidity threshold auto-drying can actually reach', async () => {
  659. await openFilamentTab(60);
  660. expect(screen.queryByText(/Auto-drying cannot reach this value/)).not.toBeInTheDocument();
  661. });
  662. // #2905: the alarm threshold is a separate value from the Fair display
  663. // band, and unset means "use Fair" rather than "never alarm". Everything
  664. // below turns on telling those two apart.
  665. const openFilamentTabWith = async (overrides: Record<string, unknown>) => {
  666. server.use(
  667. http.get('/api/v1/settings/', () => HttpResponse.json({ ...mockSettings, ...overrides }))
  668. );
  669. const user = userEvent.setup();
  670. render(<SettingsPage />);
  671. await waitFor(() => {
  672. expect(screen.getAllByText('Filament').length).toBeGreaterThan(0);
  673. });
  674. await user.click(screen.getAllByText('Filament')[0]);
  675. await waitFor(() => {
  676. expect(screen.getByText('AMS Display Thresholds')).toBeInTheDocument();
  677. });
  678. };
  679. const alarmInput = () =>
  680. within(screen.getByText('Alarm above').parentElement!).getByRole('spinbutton');
  681. it('shows the fair threshold as the placeholder while the alarm threshold is unset', async () => {
  682. // The fallback has to be visible in the field itself. Blank with no hint
  683. // reads as "no alarm", which is the opposite of what unset does.
  684. await openFilamentTabWith({ ams_temp_fair: 38, ams_temp_alarm: null });
  685. const input = alarmInput();
  686. expect(input).toHaveValue(null);
  687. expect(input).toHaveAttribute('placeholder', '38');
  688. });
  689. it('sends the typed alarm threshold on save', async () => {
  690. let saved: Record<string, unknown> | null = null;
  691. server.use(
  692. http.put('/api/v1/settings/', async ({ request }) => {
  693. saved = (await request.json()) as Record<string, unknown>;
  694. return HttpResponse.json({ ...mockSettings, ...saved });
  695. })
  696. );
  697. await openFilamentTabWith({ ams_temp_alarm: null });
  698. // The page suppresses auto-save for 100ms after the settings load.
  699. await new Promise((resolve) => setTimeout(resolve, 200));
  700. await userEvent.type(alarmInput(), '45');
  701. // Assert on the value rather than merely on a save having happened: two
  702. // keystrokes can straddle the 500ms debounce on a slow runner, and the
  703. // first save would then carry 4. Waiting for 45 rides that out.
  704. await waitFor(() => {
  705. expect(saved?.ams_temp_alarm).toBe(45);
  706. }, { timeout: 3000 });
  707. });
  708. it('sends null when the alarm threshold is cleared', async () => {
  709. // The one path the backend tests cannot reach on their own: clearing has
  710. // to send an explicit null, not omit the key, or the old threshold stays.
  711. let saved: Record<string, unknown> | null = null;
  712. server.use(
  713. http.put('/api/v1/settings/', async ({ request }) => {
  714. saved = (await request.json()) as Record<string, unknown>;
  715. return HttpResponse.json({ ...mockSettings, ...saved });
  716. })
  717. );
  718. await openFilamentTabWith({ ams_temp_alarm: 45 });
  719. await new Promise((resolve) => setTimeout(resolve, 200));
  720. await userEvent.clear(alarmInput());
  721. await waitFor(() => {
  722. expect(saved).not.toBeNull();
  723. expect(saved!.ams_temp_alarm).toBeNull();
  724. }, { timeout: 3000 });
  725. });
  726. it('warns that a non-positive alarm threshold is ignored', async () => {
  727. // The backend refuses <= 0 and falls back to Fair. Saying so beats a min=
  728. // attribute the browser only enforces on submit.
  729. await openFilamentTabWith({ ams_temp_alarm: 0 });
  730. expect(await screen.findByText(/A threshold of 0 or less is ignored/)).toBeInTheDocument();
  731. });
  732. it('stays quiet for an alarm threshold the backend will honour', async () => {
  733. await openFilamentTabWith({ ams_temp_alarm: 45 });
  734. expect(screen.queryByText(/A threshold of 0 or less is ignored/)).not.toBeInTheDocument();
  735. });
  736. });
  737. describe('Workflow tab', () => {
  738. it('can switch to Workflow tab', async () => {
  739. const user = userEvent.setup();
  740. render(<SettingsPage />);
  741. await waitFor(() => {
  742. expect(screen.getByText('Workflow')).toBeInTheDocument();
  743. });
  744. await user.click(screen.getByText('Workflow'));
  745. await waitFor(() => {
  746. expect(screen.getByText('Staggered Start')).toBeInTheDocument();
  747. });
  748. });
  749. it('shows stagger settings on Workflow tab', async () => {
  750. const user = userEvent.setup();
  751. render(<SettingsPage />);
  752. await waitFor(() => {
  753. expect(screen.getByText('Workflow')).toBeInTheDocument();
  754. });
  755. await user.click(screen.getByText('Workflow'));
  756. await waitFor(() => {
  757. expect(screen.getByText('Staggered Start')).toBeInTheDocument();
  758. expect(screen.getByText('Group size')).toBeInTheDocument();
  759. expect(screen.getByText('Interval (minutes)')).toBeInTheDocument();
  760. });
  761. });
  762. it('shows auto-drying settings on Workflow tab', async () => {
  763. const user = userEvent.setup();
  764. render(<SettingsPage />);
  765. await waitFor(() => {
  766. expect(screen.getByText('Workflow')).toBeInTheDocument();
  767. });
  768. await user.click(screen.getByText('Workflow'));
  769. await waitFor(() => {
  770. expect(screen.getByText('Queue Auto-Drying')).toBeInTheDocument();
  771. });
  772. });
  773. it('shows per-filament humidity threshold editor on Workflow tab (#1605)', async () => {
  774. const user = userEvent.setup();
  775. render(<SettingsPage />);
  776. await waitFor(() => {
  777. expect(screen.getByText('Workflow')).toBeInTheDocument();
  778. });
  779. await user.click(screen.getByText('Workflow'));
  780. await waitFor(() => {
  781. expect(screen.getByText('Humidity Thresholds')).toBeInTheDocument();
  782. // Default row is unique to the humidity editor (drying presets has no
  783. // default row), so we can pin it without disambiguating from the
  784. // adjacent drying-presets table that also lists PLA/ASA/etc.
  785. expect(screen.getByText('Default (unknown types)')).toBeInTheDocument();
  786. // Filament rows render in both tables — assert by count instead of
  787. // a single getByText. 8 default filaments × 2 tables = 16 PLAs etc.
  788. expect(screen.getAllByText('PLA').length).toBeGreaterThanOrEqual(2);
  789. expect(screen.getAllByText('ASA').length).toBeGreaterThanOrEqual(2);
  790. });
  791. });
  792. it('shows default print options on Workflow tab', async () => {
  793. const user = userEvent.setup();
  794. render(<SettingsPage />);
  795. await waitFor(() => {
  796. expect(screen.getByText('Workflow')).toBeInTheDocument();
  797. });
  798. await user.click(screen.getByText('Workflow'));
  799. await waitFor(() => {
  800. expect(screen.getByText('Default Print Options')).toBeInTheDocument();
  801. expect(screen.getByText('Bed Levelling')).toBeInTheDocument();
  802. expect(screen.getByText('Flow Calibration')).toBeInTheDocument();
  803. expect(screen.getByText('Vibration Calibration')).toBeInTheDocument();
  804. expect(screen.getByText('First Layer Inspection')).toBeInTheDocument();
  805. expect(screen.getByText('Timelapse')).toBeInTheDocument();
  806. });
  807. });
  808. it('shows default print options description', async () => {
  809. const user = userEvent.setup();
  810. render(<SettingsPage />);
  811. await waitFor(() => {
  812. expect(screen.getByText('Workflow')).toBeInTheDocument();
  813. });
  814. await user.click(screen.getByText('Workflow'));
  815. await waitFor(() => {
  816. expect(screen.getByText(/overridden per print in the print dialog/)).toBeInTheDocument();
  817. });
  818. });
  819. });
  820. describe('sustained-minutes input drafts while typing (#2518)', () => {
  821. const openWorkflowTab = async (user: ReturnType<typeof userEvent.setup>) => {
  822. render(<SettingsPage />);
  823. await waitFor(() => {
  824. expect(screen.getByText('Workflow')).toBeInTheDocument();
  825. });
  826. await user.click(screen.getByText('Workflow'));
  827. await waitFor(() => {
  828. expect(screen.getByText('Queue Auto-Drying')).toBeInTheDocument();
  829. });
  830. // 15 is unique to this input in the mock settings below
  831. return screen.getByDisplayValue('15') as HTMLInputElement;
  832. };
  833. beforeEach(() => {
  834. server.use(
  835. http.get('/api/v1/settings/', () => {
  836. return HttpResponse.json({
  837. ...mockSettings,
  838. ambient_drying_enabled: true,
  839. ambient_drying_sustained_minutes: 15,
  840. });
  841. })
  842. );
  843. });
  844. it('seeds a new sustained wait at 15 minutes when enabled from off', async () => {
  845. const user = userEvent.setup();
  846. let saved: Record<string, unknown> | null = null;
  847. server.use(
  848. http.get('/api/v1/settings/', () =>
  849. HttpResponse.json({
  850. ...mockSettings,
  851. ambient_drying_enabled: true,
  852. ambient_drying_sustained_minutes: 0,
  853. })
  854. ),
  855. http.put('/api/v1/settings/', async ({ request }) => {
  856. saved = (await request.json()) as Record<string, unknown>;
  857. return HttpResponse.json({ ...mockSettings, ...saved });
  858. })
  859. );
  860. render(<SettingsPage />);
  861. await user.click(await screen.findByText('Workflow'));
  862. const label = await screen.findByText('Require sustained humidity');
  863. const row = label.closest('div')!.parentElement!;
  864. const toggle = within(row).getByRole('checkbox');
  865. expect(toggle).not.toBeChecked();
  866. // Wait out the page's initial-load save suppression before toggling.
  867. await new Promise((resolve) => setTimeout(resolve, 200));
  868. await user.click(toggle);
  869. expect(toggle).toBeChecked();
  870. expect(screen.getByDisplayValue('15')).toBeInTheDocument();
  871. await waitFor(() => {
  872. expect(saved).not.toBeNull();
  873. }, { timeout: 3000 });
  874. expect(saved!.ambient_drying_sustained_minutes).toBe(15);
  875. });
  876. it('clearing the field does not snap it to a value mid-edit', async () => {
  877. const user = userEvent.setup();
  878. const input = await openWorkflowTab(user);
  879. await user.clear(input);
  880. // The old per-keystroke clamp rewrote '' to 10 immediately.
  881. expect(input.value).toBe('');
  882. });
  883. it('intermediate below-minimum digits are not rewritten while typing', async () => {
  884. const user = userEvent.setup();
  885. const input = await openWorkflowTab(user);
  886. await user.clear(input);
  887. await user.type(input, '2');
  888. // The old clamp turned the '2' (on the way to '25') into 5.
  889. expect(input.value).toBe('2');
  890. await user.type(input, '5');
  891. expect(input.value).toBe('25');
  892. await user.tab();
  893. await waitFor(() => {
  894. expect(input.value).toBe('25');
  895. });
  896. });
  897. it('blur with an empty field reverts to the saved value instead of inventing one', async () => {
  898. const user = userEvent.setup();
  899. const input = await openWorkflowTab(user);
  900. await user.clear(input);
  901. await user.tab();
  902. await waitFor(() => {
  903. expect(input.value).toBe('15');
  904. });
  905. });
  906. it('still clamps an out-of-range value on blur', async () => {
  907. const user = userEvent.setup();
  908. const input = await openWorkflowTab(user);
  909. await user.clear(input);
  910. await user.type(input, '500');
  911. await user.tab();
  912. await waitFor(() => {
  913. expect(input.value).toBe('240');
  914. });
  915. });
  916. });
  917. describe('API Keys tab', () => {
  918. it('can switch to API Keys tab', async () => {
  919. const user = userEvent.setup();
  920. render(<SettingsPage />);
  921. await waitFor(() => {
  922. expect(screen.getByText('API Keys')).toBeInTheDocument();
  923. });
  924. await user.click(screen.getByText('API Keys'));
  925. await waitFor(() => {
  926. // Button text is "Create Key"
  927. expect(screen.getByText('Create Key')).toBeInTheDocument();
  928. });
  929. });
  930. });
  931. describe('SpoolBuddy tab badge', () => {
  932. const baseDevice = {
  933. id: 1,
  934. device_id: 'sb-0001',
  935. hostname: 'sb-kitchen',
  936. ip_address: '10.0.0.1',
  937. backend_url: null,
  938. firmware_version: '1.0.0',
  939. has_nfc: true,
  940. has_scale: true,
  941. tare_offset: 0,
  942. calibration_factor: 1.0,
  943. nfc_reader_type: null,
  944. nfc_connection: null,
  945. display_brightness: 100,
  946. display_blank_timeout: 0,
  947. has_backlight: false,
  948. last_calibrated_at: null,
  949. last_seen: new Date().toISOString(),
  950. pending_command: null,
  951. nfc_ok: true,
  952. scale_ok: true,
  953. uptime_s: 100,
  954. update_status: null,
  955. update_message: null,
  956. system_stats: null,
  957. online: true,
  958. created_at: '2024-01-01T00:00:00Z',
  959. updated_at: '2024-01-01T00:00:00Z',
  960. };
  961. it('shows device count and green bullet when at least one device is online', async () => {
  962. server.use(
  963. http.get('/api/v1/spoolbuddy/devices', () => {
  964. return HttpResponse.json([
  965. { ...baseDevice, id: 1, device_id: 'sb-0001', hostname: 'sb-kitchen', online: true },
  966. { ...baseDevice, id: 2, device_id: 'sb-0002', hostname: 'sb-ghost', online: false },
  967. ]);
  968. })
  969. );
  970. render(<SettingsPage />);
  971. // Find the tab button (not the header) — it's the <button> containing the SpoolBuddy text
  972. const tabButton = await waitFor(() => {
  973. const buttons = screen.getAllByRole('button').filter((b) => b.textContent?.includes('SpoolBuddy'));
  974. expect(buttons.length).toBeGreaterThan(0);
  975. return buttons[0];
  976. });
  977. // Count pill rendered
  978. await waitFor(() => {
  979. expect(tabButton.textContent).toContain('2');
  980. });
  981. // Green status bullet (at least one device online)
  982. await waitFor(() => {
  983. expect(tabButton.querySelector('.bg-green-400')).not.toBeNull();
  984. });
  985. });
  986. it('shows gray bullet when all devices are offline', async () => {
  987. server.use(
  988. http.get('/api/v1/spoolbuddy/devices', () => {
  989. return HttpResponse.json([{ ...baseDevice, online: false }]);
  990. })
  991. );
  992. render(<SettingsPage />);
  993. const tabButton = await waitFor(() => {
  994. const buttons = screen.getAllByRole('button').filter((b) => b.textContent?.includes('SpoolBuddy'));
  995. expect(buttons.length).toBeGreaterThan(0);
  996. return buttons[0];
  997. });
  998. await waitFor(() => {
  999. expect(tabButton.querySelector('.bg-gray-500')).not.toBeNull();
  1000. expect(tabButton.querySelector('.bg-green-400')).toBeNull();
  1001. });
  1002. });
  1003. it('hides the count pill when no devices are registered', async () => {
  1004. server.use(
  1005. http.get('/api/v1/spoolbuddy/devices', () => HttpResponse.json([]))
  1006. );
  1007. render(<SettingsPage />);
  1008. const tabButton = await waitFor(() => {
  1009. const buttons = screen.getAllByRole('button').filter((b) => b.textContent?.includes('SpoolBuddy'));
  1010. expect(buttons.length).toBeGreaterThan(0);
  1011. return buttons[0];
  1012. });
  1013. // The only numeric content should NOT be present — tab label only
  1014. await waitFor(() => {
  1015. expect(tabButton.textContent).toBe('SpoolBuddy');
  1016. });
  1017. });
  1018. });
  1019. describe('API Keys tab — delete flow', () => {
  1020. // Without setQueryData on success the deleted row stayed visible until a
  1021. // manual reload — invalidateQueries didn't reliably trigger a UI swap on
  1022. // every browser. Pin the synchronous-removal contract here.
  1023. it('removes a deleted key from the list without a page reload', async () => {
  1024. const initialKeys = [
  1025. {
  1026. id: 42,
  1027. name: 'CI deploy key',
  1028. key_prefix: 'bk_abcd1234',
  1029. can_queue: true,
  1030. can_control_printer: false,
  1031. can_read_status: true,
  1032. printer_ids: null,
  1033. enabled: true,
  1034. last_used: null,
  1035. created_at: '2026-01-01T00:00:00Z',
  1036. expires_at: null,
  1037. },
  1038. ];
  1039. let deleteCallCount = 0;
  1040. server.use(
  1041. http.get('/api/v1/api-keys/', () => HttpResponse.json(initialKeys)),
  1042. http.delete('/api/v1/api-keys/:id', ({ params }) => {
  1043. deleteCallCount += 1;
  1044. expect(params.id).toBe('42');
  1045. return HttpResponse.json({ message: 'API key deleted' });
  1046. })
  1047. );
  1048. const user = userEvent.setup();
  1049. render(<SettingsPage />);
  1050. // Switch to API Keys tab. Both desktop tab + mobile dropdown render
  1051. // the label, so just grab the button form.
  1052. await waitFor(() => {
  1053. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  1054. });
  1055. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  1056. expect(tabButton).toBeDefined();
  1057. await user.click(tabButton!);
  1058. // Key is listed
  1059. await waitFor(() => {
  1060. expect(screen.getByText('CI deploy key')).toBeInTheDocument();
  1061. });
  1062. // Click the trash button on the row
  1063. const cards = screen.getByText('CI deploy key').closest('.flex.items-center.justify-between');
  1064. expect(cards).not.toBeNull();
  1065. const trashButton = cards!.querySelectorAll('button');
  1066. await user.click(trashButton[trashButton.length - 1]);
  1067. // Confirm the deletion in the modal
  1068. const confirmButton = await screen.findByRole('button', { name: /delete/i });
  1069. await user.click(confirmButton);
  1070. // The deleted key disappears from the list immediately — no manual
  1071. // reload required. setQueryData drops it before any refetch could fire.
  1072. await waitFor(() => {
  1073. expect(screen.queryByText('CI deploy key')).not.toBeInTheDocument();
  1074. });
  1075. expect(deleteCallCount).toBe(1);
  1076. });
  1077. });
  1078. describe('API Keys tab — #1182 cloud access + ownership UI', () => {
  1079. // The list now exposes two new bits of information per row:
  1080. // - "Cloud" badge when can_access_cloud=true
  1081. // - "Legacy" badge when user_id IS NULL (created before per-user ownership)
  1082. // These tell the operator at a glance which keys can read /cloud/* data
  1083. // and which keys need to be recreated to gain that capability.
  1084. it('renders the Cloud badge for keys with can_access_cloud=true and the Legacy badge for ownerless keys', async () => {
  1085. const keys = [
  1086. {
  1087. id: 1,
  1088. name: 'cloud-reader',
  1089. key_prefix: 'bk_cloud123',
  1090. user_id: 7,
  1091. can_queue: false,
  1092. can_control_printer: false,
  1093. can_read_status: true,
  1094. can_access_cloud: true,
  1095. printer_ids: null,
  1096. enabled: true,
  1097. last_used: null,
  1098. created_at: '2026-04-30T00:00:00Z',
  1099. expires_at: null,
  1100. },
  1101. {
  1102. id: 2,
  1103. name: 'legacy-key',
  1104. key_prefix: 'bk_legacy01',
  1105. user_id: null,
  1106. can_queue: true,
  1107. can_control_printer: false,
  1108. can_read_status: true,
  1109. can_access_cloud: false,
  1110. printer_ids: null,
  1111. enabled: true,
  1112. last_used: null,
  1113. created_at: '2025-01-01T00:00:00Z',
  1114. expires_at: null,
  1115. },
  1116. ];
  1117. server.use(http.get('/api/v1/api-keys/', () => HttpResponse.json(keys)));
  1118. const user = userEvent.setup();
  1119. render(<SettingsPage />);
  1120. await waitFor(() => {
  1121. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  1122. });
  1123. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  1124. await user.click(tabButton!);
  1125. await waitFor(() => {
  1126. expect(screen.getByText('cloud-reader')).toBeInTheDocument();
  1127. expect(screen.getByText('legacy-key')).toBeInTheDocument();
  1128. });
  1129. // Cloud-enabled key gets the Cloud badge but NOT the Legacy badge.
  1130. const cloudRow = screen.getByText('cloud-reader').closest('.flex.items-center.justify-between');
  1131. expect(cloudRow).not.toBeNull();
  1132. expect(cloudRow!.textContent).toContain('Cloud');
  1133. expect(cloudRow!.textContent).not.toContain('Legacy');
  1134. // Ownerless key gets Legacy but NOT Cloud (can_access_cloud=false).
  1135. const legacyRow = screen.getByText('legacy-key').closest('.flex.items-center.justify-between');
  1136. expect(legacyRow).not.toBeNull();
  1137. expect(legacyRow!.textContent).toContain('Legacy');
  1138. // Strip the Cloud-flag check by limiting to badge area — the
  1139. // "Allow cloud access" text from the create form isn't visible here.
  1140. expect(legacyRow!.querySelector('.bg-purple-500\\/20')).toBeNull();
  1141. });
  1142. it('passes can_access_cloud through to the create call when the toggle is checked', async () => {
  1143. let posted: { name?: string; can_access_cloud?: boolean } | null = null;
  1144. server.use(
  1145. http.get('/api/v1/api-keys/', () => HttpResponse.json([])),
  1146. http.post('/api/v1/api-keys/', async ({ request }) => {
  1147. posted = (await request.json()) as { name?: string; can_access_cloud?: boolean };
  1148. return HttpResponse.json({
  1149. id: 99,
  1150. key: 'bk_returnedkey',
  1151. name: posted.name,
  1152. key_prefix: 'bk_returne',
  1153. user_id: 1,
  1154. can_queue: true,
  1155. can_control_printer: false,
  1156. can_read_status: true,
  1157. can_access_cloud: posted.can_access_cloud ?? false,
  1158. printer_ids: null,
  1159. enabled: true,
  1160. last_used: null,
  1161. created_at: '2026-05-01T00:00:00Z',
  1162. expires_at: null,
  1163. });
  1164. })
  1165. );
  1166. const user = userEvent.setup();
  1167. render(<SettingsPage />);
  1168. await waitFor(() => {
  1169. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  1170. });
  1171. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  1172. await user.click(tabButton!);
  1173. // Open the create form. With an empty key list the empty-state card
  1174. // shows "Create Your First Key" — click that to open the form.
  1175. const openButton = await screen.findByRole('button', { name: /Create Your First Key/i });
  1176. await user.click(openButton);
  1177. // Tick the new "Allow cloud access" checkbox. The label wraps the
  1178. // input AND a sibling description div, so getByLabelText doesn't
  1179. // resolve via implicit-label traversal — locate via text + closest
  1180. // label, then grab the checkbox from the same scope.
  1181. const cloudLabelText = await screen.findByText(/Allow cloud access/i);
  1182. const cloudLabel = cloudLabelText.closest('label');
  1183. expect(cloudLabel).not.toBeNull();
  1184. const cloudCheckbox = cloudLabel!.querySelector('input[type="checkbox"]') as HTMLInputElement;
  1185. expect(cloudCheckbox).not.toBeNull();
  1186. await user.click(cloudCheckbox);
  1187. // Submit. Two "Create Key" buttons exist once the form is open (header
  1188. // CTA + form footer); the form-footer one is the actual submit and
  1189. // calls the mutation — find it by walking up from the cloud checkbox
  1190. // we just clicked, since both share the same form container.
  1191. const submitButtons = screen.getAllByRole('button', { name: /^Create Key$/i });
  1192. // Footer submit is the one inside the same form section as the
  1193. // checkbox. The header CTA is in a separate flex row.
  1194. const formSubmit = submitButtons.find(
  1195. (b) => b.closest('div')?.contains(cloudCheckbox) || cloudLabel?.parentElement?.parentElement?.contains(b),
  1196. );
  1197. await user.click(formSubmit ?? submitButtons[submitButtons.length - 1]);
  1198. await waitFor(() => {
  1199. expect(posted).not.toBeNull();
  1200. expect(posted!.can_access_cloud).toBe(true);
  1201. });
  1202. });
  1203. });
  1204. describe('API Keys tab — #1356 energy-cost write scope', () => {
  1205. /**
  1206. * The narrowly-scoped settings-write toggle. We pin two contracts here:
  1207. *
  1208. * 1. The "Energy" badge renders for keys that have can_update_energy_cost=true.
  1209. * Without a visible signal, an operator can't tell which key in their
  1210. * list is the one their HA automation depends on.
  1211. * 2. The create form sends can_update_energy_cost=true to the backend
  1212. * when the toggle is checked. The whole point of #1356 is that the
  1213. * flag must actually be persisted — a UI that drops it silently
  1214. * would put us right back where the bug started.
  1215. */
  1216. it('renders the Energy badge for keys with can_update_energy_cost=true', async () => {
  1217. const keys = [
  1218. {
  1219. id: 1,
  1220. name: 'tariff-pusher',
  1221. key_prefix: 'bk_tariff01',
  1222. user_id: 7,
  1223. can_queue: false,
  1224. can_control_printer: false,
  1225. can_read_status: true,
  1226. can_access_cloud: false,
  1227. can_update_energy_cost: true,
  1228. printer_ids: null,
  1229. enabled: true,
  1230. last_used: null,
  1231. created_at: '2026-05-15T00:00:00Z',
  1232. expires_at: null,
  1233. },
  1234. ];
  1235. server.use(http.get('/api/v1/api-keys/', () => HttpResponse.json(keys)));
  1236. const user = userEvent.setup();
  1237. render(<SettingsPage />);
  1238. await waitFor(() => {
  1239. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  1240. });
  1241. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  1242. await user.click(tabButton!);
  1243. await waitFor(() => {
  1244. expect(screen.getByText('tariff-pusher')).toBeInTheDocument();
  1245. });
  1246. const row = screen.getByText('tariff-pusher').closest('.flex.items-center.justify-between');
  1247. expect(row).not.toBeNull();
  1248. expect(row!.textContent).toContain('Energy');
  1249. });
  1250. it('passes can_update_energy_cost through to the create call when the toggle is checked', async () => {
  1251. let posted: { name?: string; can_update_energy_cost?: boolean } | null = null;
  1252. server.use(
  1253. http.get('/api/v1/api-keys/', () => HttpResponse.json([])),
  1254. http.post('/api/v1/api-keys/', async ({ request }) => {
  1255. posted = (await request.json()) as { name?: string; can_update_energy_cost?: boolean };
  1256. return HttpResponse.json({
  1257. id: 99,
  1258. key: 'bk_returnedkey',
  1259. name: posted.name,
  1260. key_prefix: 'bk_returne',
  1261. user_id: 1,
  1262. can_queue: true,
  1263. can_control_printer: false,
  1264. can_read_status: true,
  1265. can_access_cloud: false,
  1266. can_update_energy_cost: posted.can_update_energy_cost ?? false,
  1267. printer_ids: null,
  1268. enabled: true,
  1269. last_used: null,
  1270. created_at: '2026-05-15T00:00:00Z',
  1271. expires_at: null,
  1272. });
  1273. })
  1274. );
  1275. const user = userEvent.setup();
  1276. render(<SettingsPage />);
  1277. await waitFor(() => {
  1278. expect(screen.getAllByText('API Keys').length).toBeGreaterThan(0);
  1279. });
  1280. const tabButton = screen.getAllByText('API Keys').find((el) => el.tagName === 'BUTTON');
  1281. await user.click(tabButton!);
  1282. const openButton = await screen.findByRole('button', { name: /Create Your First Key/i });
  1283. await user.click(openButton);
  1284. const energyLabelText = await screen.findByText(/Update electricity price/i);
  1285. const energyLabel = energyLabelText.closest('label');
  1286. expect(energyLabel).not.toBeNull();
  1287. const energyCheckbox = energyLabel!.querySelector('input[type="checkbox"]') as HTMLInputElement;
  1288. expect(energyCheckbox).not.toBeNull();
  1289. await user.click(energyCheckbox);
  1290. const submitButtons = screen.getAllByRole('button', { name: /^Create Key$/i });
  1291. const formSubmit = submitButtons.find(
  1292. (b) => b.closest('div')?.contains(energyCheckbox) || energyLabel?.parentElement?.parentElement?.contains(b),
  1293. );
  1294. await user.click(formSubmit ?? submitButtons[submitButtons.length - 1]);
  1295. await waitFor(() => {
  1296. expect(posted).not.toBeNull();
  1297. expect(posted!.can_update_energy_cost).toBe(true);
  1298. });
  1299. });
  1300. });
  1301. describe('external camera snapshot URL override (#1177)', () => {
  1302. /**
  1303. * The snapshot URL input only appears for stream camera types where the
  1304. * MJPEG warm-up problem can occur (mjpeg / rtsp / usb). Pure HTTP
  1305. * snapshot sources don't need an override since their stream URL is
  1306. * already a single-frame endpoint.
  1307. */
  1308. const mjpegPrinter = {
  1309. id: 7,
  1310. name: 'go2rtc Cam',
  1311. serial_number: 'TEST123',
  1312. ip_address: '192.168.1.100',
  1313. access_code: 'XXXX',
  1314. model: 'P1S',
  1315. location: null,
  1316. nozzle_count: 1,
  1317. is_active: true,
  1318. auto_archive: true,
  1319. external_camera_url: 'http://192.168.1.61:1984/api/stream.mjpeg?src=printer',
  1320. external_camera_type: 'mjpeg',
  1321. external_camera_enabled: true,
  1322. external_camera_snapshot_url: null,
  1323. camera_rotation: 0,
  1324. plate_detection_enabled: false,
  1325. created_at: '2026-01-01T00:00:00Z',
  1326. updated_at: '2026-01-01T00:00:00Z',
  1327. };
  1328. it('renders the snapshot URL input when camera_type is mjpeg', async () => {
  1329. server.use(
  1330. http.get('/api/v1/printers/', () => HttpResponse.json([mjpegPrinter])),
  1331. );
  1332. render(<SettingsPage />);
  1333. await waitFor(() => {
  1334. expect(screen.getByPlaceholderText(/api\/frame\.jpeg\?src=printer/)).toBeInTheDocument();
  1335. });
  1336. });
  1337. it('hides the snapshot URL input when camera_type is snapshot (already a single-frame source)', async () => {
  1338. server.use(
  1339. http.get('/api/v1/printers/', () =>
  1340. HttpResponse.json([{ ...mjpegPrinter, external_camera_type: 'snapshot' }]),
  1341. ),
  1342. );
  1343. render(<SettingsPage />);
  1344. // Wait for the live-stream URL placeholder to render so we know the
  1345. // camera section finished mounting before asserting absence of the
  1346. // snapshot input below.
  1347. await waitFor(() => {
  1348. expect(screen.getByPlaceholderText(/Camera URL/i)).toBeInTheDocument();
  1349. });
  1350. expect(screen.queryByPlaceholderText(/api\/frame\.jpeg\?src=printer/)).not.toBeInTheDocument();
  1351. });
  1352. it(
  1353. 'PATCHes the printer with external_camera_snapshot_url when the user types into the input',
  1354. async () => {
  1355. let receivedBody: Record<string, unknown> | null = null;
  1356. server.use(
  1357. http.get('/api/v1/printers/', () => HttpResponse.json([mjpegPrinter])),
  1358. http.patch('/api/v1/printers/7', async ({ request }) => {
  1359. receivedBody = (await request.json()) as Record<string, unknown>;
  1360. return HttpResponse.json({ ...mjpegPrinter, ...receivedBody });
  1361. }),
  1362. );
  1363. render(<SettingsPage />);
  1364. const input = await waitFor(() =>
  1365. screen.getByPlaceholderText(/api\/frame\.jpeg\?src=printer/),
  1366. );
  1367. const user = userEvent.setup();
  1368. await user.type(input, 'http://192.168.1.61:1984/api/frame.jpeg?src=printer');
  1369. // Save is debounced by 800ms; assert the PATCH eventually fires with
  1370. // the typed snapshot URL.
  1371. await waitFor(
  1372. () => {
  1373. expect(receivedBody).not.toBeNull();
  1374. expect(receivedBody!.external_camera_snapshot_url).toBe(
  1375. 'http://192.168.1.61:1984/api/frame.jpeg?src=printer',
  1376. );
  1377. },
  1378. { timeout: 5000 },
  1379. );
  1380. },
  1381. // Per-test timeout raised to 15s — `user.type()` of a 49-char URL plus
  1382. // the 800ms save debounce fits in 5s locally (~2.3s typical) but blows
  1383. // past it on slow GitHub Actions runners (5000ms timeout was the failure
  1384. // mode on PR #1263).
  1385. 15_000,
  1386. );
  1387. });
  1388. describe('theme mode buttons', () => {
  1389. it('renders Dark, Light, and System buttons', async () => {
  1390. render(<SettingsPage />);
  1391. await waitFor(() => {
  1392. expect(screen.getByRole('button', { name: 'Dark' })).toBeInTheDocument();
  1393. expect(screen.getByRole('button', { name: 'Light' })).toBeInTheDocument();
  1394. expect(screen.getByRole('button', { name: 'System' })).toBeInTheDocument();
  1395. });
  1396. });
  1397. it('highlights the active mode button with green border', async () => {
  1398. render(<SettingsPage />);
  1399. const user = userEvent.setup();
  1400. await waitFor(() => {
  1401. expect(screen.getByRole('button', { name: 'System' })).toBeInTheDocument();
  1402. });
  1403. await user.click(screen.getByRole('button', { name: 'System' }));
  1404. await waitFor(() => {
  1405. const systemBtn = screen.getByRole('button', { name: 'System' });
  1406. expect(systemBtn.className).toContain('border-bambu-green');
  1407. });
  1408. });
  1409. it('clicking a theme button switches mode', async () => {
  1410. localStorage.setItem('theme-mode', 'dark');
  1411. render(<SettingsPage />);
  1412. const user = userEvent.setup();
  1413. await waitFor(() => {
  1414. const darkBtn = screen.getByRole('button', { name: 'Dark' });
  1415. expect(darkBtn.className).toContain('border-bambu-green');
  1416. });
  1417. const lightBtn = screen.getByRole('button', { name: 'Light' });
  1418. await user.click(lightBtn);
  1419. await waitFor(() => {
  1420. expect(lightBtn.className).toContain('border-bambu-green');
  1421. });
  1422. });
  1423. it('shows a toast when theme button is clicked', async () => {
  1424. render(<SettingsPage />);
  1425. const user = userEvent.setup();
  1426. await waitFor(() => {
  1427. expect(screen.getByRole('button', { name: 'System' })).toBeInTheDocument();
  1428. });
  1429. await user.click(screen.getByRole('button', { name: 'System' }));
  1430. await waitFor(() => {
  1431. expect(screen.getByText('Settings saved')).toBeInTheDocument();
  1432. });
  1433. });
  1434. });
  1435. // --------------------------------------------------------------------
  1436. // Slicer Pipelines (#1425) — Workflow tab sub-tabs
  1437. // --------------------------------------------------------------------
  1438. describe('workflow sub-tabs (#1425)', () => {
  1439. beforeEach(() => {
  1440. // Endpoints the Pipelines panel calls (#1425).
  1441. server.use(
  1442. http.get('/api/v1/slicer-pipelines/', () => HttpResponse.json({ pipelines: [] })),
  1443. http.get('/api/v1/slicer/presets', () =>
  1444. HttpResponse.json({
  1445. orca_cloud: { printer: [], process: [], filament: [] },
  1446. cloud: { printer: [], process: [], filament: [] },
  1447. local: { printer: [], process: [], filament: [] },
  1448. standard: { printer: [], process: [], filament: [] },
  1449. cloud_status: 'ok',
  1450. orca_cloud_status: 'ok',
  1451. }),
  1452. ),
  1453. );
  1454. });
  1455. it('renders Queue & Dispatch + Pipelines sub-tabs under Workflow', async () => {
  1456. render(<SettingsPage />);
  1457. const user = userEvent.setup();
  1458. await waitFor(() => {
  1459. // Workflow tab in the sidebar — exact match to avoid colliding with
  1460. // "Print Queue" or "Queue Settings" labels elsewhere on the page.
  1461. expect(screen.getByRole('button', { name: 'Workflow' })).toBeInTheDocument();
  1462. });
  1463. await user.click(screen.getByRole('button', { name: 'Workflow' }));
  1464. await waitFor(() => {
  1465. expect(screen.getByRole('button', { name: /Queue & Dispatch/i })).toBeInTheDocument();
  1466. expect(screen.getByRole('button', { name: /^Pipelines$/i })).toBeInTheDocument();
  1467. });
  1468. });
  1469. it('clicking Pipelines sub-tab shows the empty-state hint and updates the URL', async () => {
  1470. render(<SettingsPage />);
  1471. const user = userEvent.setup();
  1472. await waitFor(() => expect(screen.getByRole('button', { name: 'Workflow' })).toBeInTheDocument());
  1473. await user.click(screen.getByRole('button', { name: 'Workflow' }));
  1474. await user.click(screen.getByRole('button', { name: /^Pipelines$/i }));
  1475. await waitFor(() => {
  1476. expect(screen.getByText(/No pipelines yet/i)).toBeInTheDocument();
  1477. // Deep-link URL carries both ?tab=queue and ?sub=pipelines
  1478. expect(window.location.search).toContain('tab=queue');
  1479. expect(window.location.search).toContain('sub=pipelines');
  1480. });
  1481. });
  1482. });
  1483. // --------------------------------------------------------------------
  1484. // Ask for the outcome of prints Bambuddy did not start (#1898)
  1485. // --------------------------------------------------------------------
  1486. describe('outcome prompt for external prints (#1898)', () => {
  1487. const externalLabel = 'Also ask for prints started outside Bambuddy';
  1488. const openDefaultPrintOptions = async () => {
  1489. render(<SettingsPage />);
  1490. const user = userEvent.setup();
  1491. await waitFor(() => expect(screen.getByRole('button', { name: 'Workflow' })).toBeInTheDocument());
  1492. await user.click(screen.getByRole('button', { name: 'Workflow' }));
  1493. return user;
  1494. };
  1495. it('offers the toggle alongside the per-job outcome default', async () => {
  1496. await openDefaultPrintOptions();
  1497. expect(await screen.findByText(externalLabel)).toBeInTheDocument();
  1498. expect(screen.getByText('Ask for Outcome')).toBeInTheDocument();
  1499. });
  1500. it('shows it off when the backend has no value for it', async () => {
  1501. // Default false: an install that never touches it keeps today's
  1502. // behaviour, where only queued prints are asked about.
  1503. await openDefaultPrintOptions();
  1504. const label = await screen.findByText(externalLabel);
  1505. const row = label.closest('div')!.parentElement!;
  1506. expect(within(row).getByRole('checkbox')).not.toBeChecked();
  1507. });
  1508. it('sends the new value on save', async () => {
  1509. let saved: Record<string, unknown> | null = null;
  1510. server.use(
  1511. http.put('/api/v1/settings/', async ({ request }) => {
  1512. saved = (await request.json()) as Record<string, unknown>;
  1513. return HttpResponse.json({ ...mockSettings, ...saved });
  1514. })
  1515. );
  1516. const user = await openDefaultPrintOptions();
  1517. const label = await screen.findByText(externalLabel);
  1518. // The page suppresses auto-save for 100ms after the settings load.
  1519. await new Promise((resolve) => setTimeout(resolve, 200));
  1520. const row = label.closest('div')!.parentElement!;
  1521. await user.click(within(row).getByRole('checkbox'));
  1522. await waitFor(() => {
  1523. expect(saved).not.toBeNull();
  1524. }, { timeout: 3000 });
  1525. expect(saved!.confirm_outcome_external_prints).toBe(true);
  1526. });
  1527. it('reflects a value the backend already has', async () => {
  1528. server.use(
  1529. http.get('/api/v1/settings/', () =>
  1530. HttpResponse.json({ ...mockSettings, confirm_outcome_external_prints: true })
  1531. )
  1532. );
  1533. await openDefaultPrintOptions();
  1534. const label = await screen.findByText(externalLabel);
  1535. const row = label.closest('div')!.parentElement!;
  1536. expect(within(row).getByRole('checkbox')).toBeChecked();
  1537. });
  1538. });
  1539. // --------------------------------------------------------------------
  1540. // The plate-clear default answers outcome prompts on its own (#1898), so
  1541. // its help text has to name that consequence — the farm case was a user
  1542. // who had it on and could not work out why Telegram said "already used".
  1543. // --------------------------------------------------------------------
  1544. describe('plate-clear outcome default help text (#1898)', () => {
  1545. it('warns that a later Telegram or link answer only shows the result', async () => {
  1546. render(<SettingsPage />);
  1547. const user = userEvent.setup();
  1548. await waitFor(() => expect(screen.getByRole('button', { name: 'Workflow' })).toBeInTheDocument());
  1549. await user.click(screen.getByRole('button', { name: 'Workflow' }));
  1550. const label = await screen.findByText('Count unanswered outcomes as good on plate release');
  1551. const row = label.closest('div')!;
  1552. expect(row).toHaveTextContent(
  1553. /a Telegram or link answer after that only shows the recorded result/i,
  1554. );
  1555. });
  1556. });
  1557. });
  1558. /**
  1559. * Location sensor cards on Settings -> Sensors read the live readings
  1560. * endpoint (reachable-aware) rather than the sensor row's last_state, so an
  1561. * entity Home Assistant has stopped reporting shows "Unavailable" instead of
  1562. * silently keeping its last colorized value on screen forever.
  1563. */
  1564. describe('SettingsPage — location sensor reachability', () => {
  1565. beforeEach(() => {
  1566. window.history.replaceState({}, '', '/');
  1567. });
  1568. const locationSensor = {
  1569. id: 1,
  1570. location_id: 7,
  1571. name: 'Drybox 1 Temperature',
  1572. entity_id: 'sensor.drybox_1_temperature',
  1573. kind: 'numeric',
  1574. device_class: 'temperature',
  1575. unit: '°C',
  1576. alert_state: null,
  1577. alert_above: 30,
  1578. alert_below: 20,
  1579. notify_on_alert: false,
  1580. show_on_card: true,
  1581. sort_order: 0,
  1582. last_state: '65.0',
  1583. last_changed: null,
  1584. last_checked: null,
  1585. created_at: '',
  1586. updated_at: '',
  1587. };
  1588. it('shows "Unavailable" for an unreachable sensor instead of its stale last value', async () => {
  1589. server.use(
  1590. http.get('/api/v1/location-ha-sensors/', () => HttpResponse.json([locationSensor])),
  1591. http.get('/api/v1/location-ha-sensors/by-location/7/readings', () =>
  1592. HttpResponse.json([
  1593. {
  1594. id: 1,
  1595. name: 'Drybox 1 Temperature',
  1596. entity_id: 'sensor.drybox_1_temperature',
  1597. kind: 'numeric',
  1598. device_class: 'temperature',
  1599. unit: '°C',
  1600. state: null,
  1601. value: null,
  1602. alerting: false,
  1603. reachable: false,
  1604. alert_state: null,
  1605. alert_above: 30,
  1606. alert_below: 20,
  1607. last_changed: null,
  1608. },
  1609. ])
  1610. ),
  1611. http.get('/api/v1/inventory/locations', () =>
  1612. HttpResponse.json([{ id: 7, name: 'Drybox 1', identifier: null, spool_count: 0, created_at: '', updated_at: '' }])
  1613. )
  1614. );
  1615. const user = userEvent.setup();
  1616. render(<SettingsPage />);
  1617. await user.click(await screen.findByText('Sensors'));
  1618. await screen.findByText('sensor.drybox_1_temperature');
  1619. expect(await screen.findByText('Unavailable')).toBeInTheDocument();
  1620. expect(screen.queryByText('65.00 °C')).not.toBeInTheDocument();
  1621. });
  1622. it('shows the live value, not last_state, when the sensor is reachable', async () => {
  1623. server.use(
  1624. http.get('/api/v1/location-ha-sensors/', () => HttpResponse.json([locationSensor])),
  1625. http.get('/api/v1/location-ha-sensors/by-location/7/readings', () =>
  1626. HttpResponse.json([
  1627. {
  1628. id: 1,
  1629. name: 'Drybox 1 Temperature',
  1630. entity_id: 'sensor.drybox_1_temperature',
  1631. kind: 'numeric',
  1632. device_class: 'temperature',
  1633. unit: '°C',
  1634. state: '24.5',
  1635. value: 24.5,
  1636. alerting: false,
  1637. reachable: true,
  1638. alert_state: null,
  1639. alert_above: 30,
  1640. alert_below: 20,
  1641. last_changed: null,
  1642. },
  1643. ])
  1644. ),
  1645. http.get('/api/v1/inventory/locations', () =>
  1646. HttpResponse.json([{ id: 7, name: 'Drybox 1', identifier: null, spool_count: 0, created_at: '', updated_at: '' }])
  1647. )
  1648. );
  1649. const user = userEvent.setup();
  1650. render(<SettingsPage />);
  1651. await user.click(await screen.findByText('Sensors'));
  1652. await screen.findByText('sensor.drybox_1_temperature');
  1653. expect(await screen.findByText('24.50 °C')).toBeInTheDocument();
  1654. expect(screen.queryByText('Unavailable')).not.toBeInTheDocument();
  1655. });
  1656. it('shows the entity id in the overview row, with the display name as its hover title', async () => {
  1657. server.use(
  1658. http.get('/api/v1/location-ha-sensors/', () => HttpResponse.json([locationSensor])),
  1659. http.get('/api/v1/location-ha-sensors/by-location/7/readings', () => HttpResponse.json([])),
  1660. http.get('/api/v1/inventory/locations', () =>
  1661. HttpResponse.json([{ id: 7, name: 'Drybox 1', identifier: null, spool_count: 0, created_at: '', updated_at: '' }])
  1662. )
  1663. );
  1664. const user = userEvent.setup();
  1665. render(<SettingsPage />);
  1666. await user.click(await screen.findByText('Sensors'));
  1667. const entityIdText = await screen.findByText('sensor.drybox_1_temperature');
  1668. expect(entityIdText).toHaveAttribute('title', 'Drybox 1 Temperature');
  1669. expect(screen.queryByText('Drybox 1 Temperature')).not.toBeInTheDocument();
  1670. });
  1671. it('refreshes the sensor list even when a bulk delete partially fails', async () => {
  1672. let sensors = [
  1673. { ...locationSensor, id: 1, name: 'Drybox 1 Temperature' },
  1674. {
  1675. ...locationSensor,
  1676. id: 2,
  1677. name: 'Drybox 1 Humidity',
  1678. entity_id: 'sensor.drybox_1_humidity',
  1679. device_class: 'humidity',
  1680. unit: '%',
  1681. },
  1682. ];
  1683. server.use(
  1684. http.get('/api/v1/location-ha-sensors/', () => HttpResponse.json(sensors)),
  1685. http.get('/api/v1/location-ha-sensors/by-location/7/readings', () => HttpResponse.json([])),
  1686. http.get('/api/v1/inventory/locations', () =>
  1687. HttpResponse.json([{ id: 7, name: 'Drybox 1', identifier: null, spool_count: 0, created_at: '', updated_at: '' }])
  1688. ),
  1689. // The first delete succeeds and actually removes the row; the second
  1690. // fails, simulating a partial failure partway through the sequential
  1691. // delete loop.
  1692. http.delete('/api/v1/location-ha-sensors/1', () => {
  1693. sensors = sensors.filter((s) => s.id !== 1);
  1694. return HttpResponse.json({ message: 'Sensor removed' });
  1695. }),
  1696. http.delete('/api/v1/location-ha-sensors/2', () => new HttpResponse(null, { status: 500 }))
  1697. );
  1698. const user = userEvent.setup();
  1699. render(<SettingsPage />);
  1700. await user.click(await screen.findByText('Sensors'));
  1701. await screen.findByText('sensor.drybox_1_temperature');
  1702. await screen.findByText('sensor.drybox_1_humidity');
  1703. await user.click(screen.getByRole('button', { name: 'Delete' }));
  1704. await user.click(await screen.findByRole('button', { name: 'Confirm' }));
  1705. // The sensor that actually got deleted on the backend must not linger on
  1706. // screen just because the batch as a whole reported an error.
  1707. await waitFor(() => expect(screen.queryByText('sensor.drybox_1_temperature')).not.toBeInTheDocument());
  1708. expect(screen.getByText('sensor.drybox_1_humidity')).toBeInTheDocument();
  1709. });
  1710. it('orders location cards by location, not by the order their sensors were created', async () => {
  1711. // Sensor for location 8 ("Drybox 10") appears in the array before the
  1712. // sensor for location 7 ("Drybox 2") — a naive Map-insertion-order
  1713. // render would put "Drybox 10" first. Card order must follow the
  1714. // (naturally sorted) locations list instead.
  1715. const sensors = [
  1716. {
  1717. id: 1,
  1718. location_id: 8,
  1719. name: 'Drybox 10 Temperature',
  1720. entity_id: 'sensor.drybox_10_temperature',
  1721. device_class: 'temperature',
  1722. unit: '°C',
  1723. },
  1724. {
  1725. id: 2,
  1726. location_id: 7,
  1727. name: 'Drybox 2 Temperature',
  1728. entity_id: 'sensor.drybox_2_temperature',
  1729. device_class: 'temperature',
  1730. unit: '°C',
  1731. },
  1732. ];
  1733. server.use(
  1734. http.get('/api/v1/location-ha-sensors/', () => HttpResponse.json(sensors)),
  1735. http.get('/api/v1/location-ha-sensors/by-location/7/readings', () => HttpResponse.json([])),
  1736. http.get('/api/v1/location-ha-sensors/by-location/8/readings', () => HttpResponse.json([])),
  1737. http.get('/api/v1/inventory/locations', () =>
  1738. HttpResponse.json([
  1739. { id: 7, name: 'Drybox 2', identifier: null, spool_count: 0, created_at: '', updated_at: '' },
  1740. { id: 8, name: 'Drybox 10', identifier: null, spool_count: 0, created_at: '', updated_at: '' },
  1741. ])
  1742. )
  1743. );
  1744. const user = userEvent.setup();
  1745. const { container } = render(<SettingsPage />);
  1746. await user.click(await screen.findByText('Sensors'));
  1747. await screen.findByText('sensor.drybox_10_temperature');
  1748. const cardTitles = Array.from(container.querySelectorAll('.text-white.font-medium.truncate')).map(
  1749. (el) => el.textContent
  1750. );
  1751. const drybox2Index = cardTitles.indexOf('Drybox 2');
  1752. const drybox10Index = cardTitles.indexOf('Drybox 10');
  1753. expect(drybox2Index).toBeGreaterThanOrEqual(0);
  1754. expect(drybox10Index).toBeGreaterThanOrEqual(0);
  1755. expect(drybox2Index).toBeLessThan(drybox10Index);
  1756. });
  1757. });
  1758. /**
  1759. * Sponsor banner on Settings -> General.
  1760. *
  1761. * Below the fleet threshold it makes the community/donation ask; at or above it
  1762. * the same slot makes the commercial ask and points at business.html. A print
  1763. * farm asked to chip in $5 is a wasted impression, and a hobbyist pitched a
  1764. * support contract is an annoyed user — so both directions are pinned.
  1765. */
  1766. describe('SettingsPage — sponsor banner audience', () => {
  1767. beforeEach(() => {
  1768. // BrowserRouter shares window.location across tests and the banner only
  1769. // renders on the General tab — without this reset a prior test's ?tab=queue
  1770. // leaks in and the banner never mounts.
  1771. window.history.replaceState({}, '', '/');
  1772. });
  1773. const fleet = (count: number) =>
  1774. server.use(
  1775. http.get('/api/v1/printers/', () =>
  1776. HttpResponse.json(
  1777. Array.from({ length: count }, (_, i) => ({
  1778. id: i + 1,
  1779. name: `Printer ${i + 1}`,
  1780. serial_number: `SN${i + 1}`,
  1781. ip_address: '192.168.1.10',
  1782. model: 'X1C',
  1783. is_active: true,
  1784. })),
  1785. ),
  1786. ),
  1787. );
  1788. it('shows the community ask for a small fleet', async () => {
  1789. fleet(2);
  1790. render(<SettingsPage />);
  1791. const banner = await screen.findByRole('link', { name: /Independent & community-funded/i });
  1792. expect(banner).toHaveAttribute('href', 'https://bambuddy.cool/sponsors.html?from=app-settings');
  1793. expect(screen.queryByText(/Bambuddy for business/i)).not.toBeInTheDocument();
  1794. });
  1795. it('shows the commercial ask for a business-sized fleet', async () => {
  1796. fleet(6);
  1797. render(<SettingsPage />);
  1798. const banner = await screen.findByRole('link', { name: /Bambuddy for business/i });
  1799. expect(banner).toHaveAttribute('href', 'https://bambuddy.cool/business.html?from=app-settings');
  1800. // The donation copy is replaced, not merely supplemented.
  1801. expect(screen.queryByText(/Independent & community-funded/i)).not.toBeInTheDocument();
  1802. // The ask names the fleet back to them.
  1803. expect(screen.getByText(/6 printers/i)).toBeInTheDocument();
  1804. });
  1805. });
  1806. describe('SettingsPage — settings changed outside the page (#2716)', () => {
  1807. const restoreLabel = 'Restore plate for finish photo';
  1808. // external_url is deliberately populated: when the server has none the page
  1809. // detects one from the browser and saves it unprompted, which would show up
  1810. // as a PUT in tests that assert none was made. That behaviour has its own
  1811. // test at the end of this block.
  1812. const baseSettings = { ...mockSettings, external_url: window.location.origin };
  1813. let queryClient: QueryClient;
  1814. let puts: Record<string, unknown>[];
  1815. let served: Record<string, unknown>;
  1816. function renderPage() {
  1817. queryClient = new QueryClient({
  1818. defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false } },
  1819. });
  1820. return rtlRender(
  1821. <QueryClientProvider client={queryClient}>
  1822. <BrowserRouter>
  1823. <AuthProvider>
  1824. <ThemeProvider>
  1825. <ToastProvider>
  1826. <SettingsPage />
  1827. </ToastProvider>
  1828. </ThemeProvider>
  1829. </AuthProvider>
  1830. </BrowserRouter>
  1831. </QueryClientProvider>
  1832. );
  1833. }
  1834. /** Change the settings row server-side and let the page's query observe it. */
  1835. async function changeOnServer(patch: Record<string, unknown>) {
  1836. served = { ...served, ...patch };
  1837. await act(async () => {
  1838. await queryClient.invalidateQueries({ queryKey: ['settings'] });
  1839. });
  1840. }
  1841. /** Wait out the 100ms initial-load suppression, then flip a checkbox. */
  1842. async function toggleRestorePlate() {
  1843. const label = await screen.findByText(restoreLabel);
  1844. await new Promise((resolve) => setTimeout(resolve, 200));
  1845. const row = label.closest('div')!.parentElement!;
  1846. await userEvent.click(within(row).getByRole('checkbox'));
  1847. }
  1848. beforeEach(() => {
  1849. window.history.replaceState({}, '', '/');
  1850. localStorage.clear();
  1851. setAuthToken(null);
  1852. puts = [];
  1853. served = { ...baseSettings };
  1854. server.use(
  1855. http.get('/api/v1/settings/', () => HttpResponse.json(served)),
  1856. http.put('/api/v1/settings/', async ({ request }) => {
  1857. const body = (await request.json()) as Record<string, unknown>;
  1858. puts.push(body);
  1859. served = { ...served, ...body };
  1860. return HttpResponse.json(served);
  1861. })
  1862. );
  1863. });
  1864. it('does not write its stale copy back over a server-side change', async () => {
  1865. // The defect: the page diffed the live query cache against its own copy, so
  1866. // a refetch that carried someone else's change read as a local edit and was
  1867. // reverted ~500ms later with no user interaction at all.
  1868. renderPage();
  1869. await screen.findByText(restoreLabel);
  1870. await new Promise((resolve) => setTimeout(resolve, 200));
  1871. await changeOnServer({ currency: 'EUR' });
  1872. // Well past the 500ms debounce.
  1873. await new Promise((resolve) => setTimeout(resolve, 1200));
  1874. expect(puts).toEqual([]);
  1875. });
  1876. it('adopts the server value, so a later save carries it rather than the stale one', async () => {
  1877. renderPage();
  1878. await new Promise((resolve) => setTimeout(resolve, 200));
  1879. await changeOnServer({ currency: 'EUR' });
  1880. await toggleRestorePlate();
  1881. await waitFor(() => expect(puts).toHaveLength(1), { timeout: 3000 });
  1882. // The user's edit is saved...
  1883. expect(puts[0].finish_photo_restore_plate).toBe(false);
  1884. // ...and the field they never touched goes back as the server's value, not
  1885. // the USD the page loaded with.
  1886. expect(puts[0].currency).toBe('EUR');
  1887. });
  1888. it('never reverts a pending user edit that the server changed too', async () => {
  1889. renderPage();
  1890. await toggleRestorePlate();
  1891. // Lands while the edit is still sitting in the 500ms debounce, i.e. before
  1892. // the page has committed it. Adopting the server's value here would throw
  1893. // the edit away silently.
  1894. await changeOnServer({ finish_photo_restore_plate: true });
  1895. await waitFor(() => expect(puts.length).toBeGreaterThan(0), { timeout: 3000 });
  1896. await new Promise((resolve) => setTimeout(resolve, 1200));
  1897. // Asserted over every request rather than a particular one: whichever order
  1898. // the refetch and the debounce happen to land in, no write may carry the
  1899. // server's value back over the user's.
  1900. expect(puts.map((p) => p.finish_photo_restore_plate)).toEqual(puts.map(() => false));
  1901. });
  1902. it('saves once per edit — the baseline moves with the saved row', async () => {
  1903. // Guards the failure mode the baseline introduces if it is not advanced on
  1904. // save: every render would diff against the pre-save snapshot and re-send.
  1905. renderPage();
  1906. await toggleRestorePlate();
  1907. await waitFor(() => expect(puts).toHaveLength(1), { timeout: 3000 });
  1908. await new Promise((resolve) => setTimeout(resolve, 1500));
  1909. expect(puts).toHaveLength(1);
  1910. });
  1911. it('still persists the external_url it detects from the browser', async () => {
  1912. // The page seeds external_url from window.location.origin when the server
  1913. // has none and relies on the auto-save to persist it. That only works
  1914. // because the baseline is the raw server row: seed the baseline from the
  1915. // adjusted copy instead and the detected URL matches it, so nothing ever
  1916. // marks it as needing a save.
  1917. served = { ...mockSettings };
  1918. renderPage();
  1919. await screen.findByText(restoreLabel);
  1920. await new Promise((resolve) => setTimeout(resolve, 200));
  1921. // A refetch carrying a field this page does not manage. It is enough to
  1922. // re-run the diff, and the only thing that differs is the detected URL.
  1923. await changeOnServer({ spoolman_url: 'http://spoolman.example' });
  1924. await waitFor(() => expect(puts).toHaveLength(1), { timeout: 3000 });
  1925. expect(puts[0].external_url).toBe(window.location.origin);
  1926. });
  1927. });