SettingsPage.test.tsx 105 KB

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