SettingsPage.test.tsx 101 KB

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