SettingsPage.test.tsx 109 KB

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