Layout.test.tsx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. /**
  2. * Tests for the Layout component.
  3. */
  4. import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
  5. import { screen, waitFor } from '@testing-library/react';
  6. import { render } from '../utils';
  7. import { Layout } from '../../components/Layout';
  8. import { getAuthToken, setAuthToken } from '../../api/client';
  9. import { http, HttpResponse } from 'msw';
  10. import { server } from '../mocks/server';
  11. import { SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, SIDEBAR_ORDER_KEY } from '../../utils/sidebarLayout';
  12. describe('Layout', () => {
  13. beforeEach(() => {
  14. vi.mocked(localStorage.getItem).mockReset();
  15. vi.mocked(localStorage.setItem).mockReset();
  16. vi.mocked(localStorage.removeItem).mockReset();
  17. vi.mocked(localStorage.clear).mockReset();
  18. localStorage.clear();
  19. server.use(
  20. http.get('/api/v1/printers/', () => {
  21. return HttpResponse.json([
  22. { id: 1, name: 'X1 Carbon', model: 'X1C', enabled: true },
  23. ]);
  24. }),
  25. http.get('/api/v1/printers/:id/status', () => {
  26. return HttpResponse.json({
  27. connected: true,
  28. state: 'IDLE',
  29. });
  30. }),
  31. http.get('/api/v1/version', () => {
  32. return HttpResponse.json({ version: '0.1.6', build: 'test' });
  33. }),
  34. http.get('/api/v1/settings/', () => {
  35. return HttpResponse.json({
  36. check_updates: false,
  37. check_printer_firmware: false,
  38. auto_archive: true,
  39. });
  40. }),
  41. // What the sidebar actually gates on. Layout used to read these from
  42. // /settings/, which a non-admin cannot fetch (#3023).
  43. http.get('/api/v1/settings/ui-flags', () => {
  44. return HttpResponse.json({
  45. check_updates: false,
  46. billing_enabled: false,
  47. user_notifications_enabled: true,
  48. currency: 'EUR',
  49. });
  50. }),
  51. http.get('/api/v1/external-links/', () => {
  52. return HttpResponse.json([]);
  53. }),
  54. http.get('/api/v1/smart-plugs/', () => {
  55. return HttpResponse.json([]);
  56. }),
  57. http.get('/api/v1/support/debug-logging', () => {
  58. return HttpResponse.json({ enabled: false });
  59. }),
  60. http.get('/api/v1/queue/', () => {
  61. return HttpResponse.json([]);
  62. }),
  63. http.get('/api/v1/pending-uploads/count', () => {
  64. return HttpResponse.json({ count: 0 });
  65. }),
  66. http.get('/api/v1/updates/check', () => {
  67. return HttpResponse.json({ update_available: false });
  68. }),
  69. http.get('/api/v1/auth/status', () => {
  70. return HttpResponse.json({ auth_enabled: false, requires_setup: false });
  71. }),
  72. http.get('/api/v1/printers/developer-mode-warnings', () => {
  73. return HttpResponse.json([]);
  74. })
  75. );
  76. });
  77. describe('rendering', () => {
  78. it('renders the sidebar', async () => {
  79. render(<Layout />);
  80. // Layout renders as a flex container with sidebar
  81. await waitFor(() => {
  82. const sidebar = document.querySelector('aside');
  83. expect(sidebar).toBeInTheDocument();
  84. });
  85. });
  86. it('renders navigation links', async () => {
  87. render(<Layout />);
  88. await waitFor(() => {
  89. // Navigation links should be present
  90. const links = document.querySelectorAll('a');
  91. expect(links.length).toBeGreaterThan(0);
  92. });
  93. });
  94. });
  95. describe('navigation', () => {
  96. it('has navigation items', async () => {
  97. render(<Layout />);
  98. await waitFor(() => {
  99. // Should have multiple navigation links
  100. const navLinks = document.querySelectorAll('a[href]');
  101. expect(navLinks.length).toBeGreaterThan(0);
  102. });
  103. });
  104. it('includes settings link', async () => {
  105. render(<Layout />);
  106. await waitFor(() => {
  107. // Settings link should exist (route /settings)
  108. const settingsLink = document.querySelector('a[href="/settings"]');
  109. expect(settingsLink).toBeInTheDocument();
  110. });
  111. });
  112. it('hides system nav items stored in sidebar layout preferences', async () => {
  113. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  114. if (key === SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY) return JSON.stringify(['printers']);
  115. return null;
  116. });
  117. render(<Layout />);
  118. await waitFor(() => {
  119. const sidebar = document.querySelector('aside');
  120. expect(sidebar).toBeInTheDocument();
  121. expect(sidebar?.querySelector('a[href="/inventory"]')).toBeInTheDocument();
  122. });
  123. expect(document.querySelector('aside a[href="/"]')).toBeNull();
  124. });
  125. it('applies admin default sidebar hidden state with the default order', async () => {
  126. const storage: Record<string, string> = {};
  127. vi.mocked(localStorage.getItem).mockImplementation((key) => storage[key] ?? null);
  128. vi.mocked(localStorage.setItem).mockImplementation((key, value) => {
  129. storage[key] = value;
  130. });
  131. server.use(
  132. http.get('/api/v1/settings/default-sidebar-order', () =>
  133. HttpResponse.json({
  134. default_sidebar_order: JSON.stringify({
  135. order: ['inventory', 'printers', 'settings'],
  136. hiddenSystemItemIds: ['printers'],
  137. }),
  138. }),
  139. ),
  140. );
  141. render(<Layout />);
  142. await waitFor(() => {
  143. const sidebar = document.querySelector('aside');
  144. expect(sidebar).toBeInTheDocument();
  145. expect(sidebar?.querySelector('a[href="/inventory"]')).toBeInTheDocument();
  146. });
  147. await waitFor(() => {
  148. expect(document.querySelector('aside a[href="/"]')).toBeNull();
  149. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_ORDER_KEY, JSON.stringify(['inventory', 'printers', 'settings']));
  150. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, JSON.stringify(['printers']));
  151. });
  152. });
  153. });
  154. describe('finance nav item', () => {
  155. it('stays out of the sidebar while billing is off', async () => {
  156. // billing_enabled defaults to false and the Finance page has nothing to
  157. // show without it, so the entry must not be there at all.
  158. render(<Layout />);
  159. await waitFor(() => {
  160. expect(document.querySelector('aside a[href="/stats"]')).toBeInTheDocument();
  161. });
  162. expect(document.querySelector('aside a[href="/finance"]')).toBeNull();
  163. });
  164. it('appears between Statistics and Settings once billing is on', async () => {
  165. server.use(
  166. http.get('/api/v1/settings/ui-flags', () =>
  167. HttpResponse.json({
  168. check_updates: false,
  169. billing_enabled: true,
  170. user_notifications_enabled: true,
  171. currency: 'EUR',
  172. }),
  173. ),
  174. );
  175. render(<Layout />);
  176. await waitFor(() => {
  177. expect(document.querySelector('aside a[href="/finance"]')).toBeInTheDocument();
  178. });
  179. const sidebar = document.querySelector('aside');
  180. const hrefs = Array.from(sidebar?.querySelectorAll('a[href]') ?? []).map((a) => a.getAttribute('href'));
  181. expect(hrefs.indexOf('/finance')).toBeGreaterThan(hrefs.indexOf('/stats'));
  182. expect(hrefs.indexOf('/finance')).toBeLessThan(hrefs.indexOf('/settings'));
  183. });
  184. });
  185. describe('Sidebar gates survive a user who cannot read /settings (#3023)', () => {
  186. // Every gate below used to be fed by GET /settings, which requires
  187. // settings:read. A non-admin gets 403 there, so the value arrived
  188. // undefined and each gate silently took its fallback -- in opposite
  189. // directions, which is why only one of the two was ever reported.
  190. let priorToken: string | null = null;
  191. const asNonAdmin = (permissions: string[]) => {
  192. server.use(
  193. http.get('/api/v1/auth/status', () =>
  194. HttpResponse.json({ auth_enabled: true, requires_setup: false }),
  195. ),
  196. http.get('/api/v1/auth/me', () =>
  197. HttpResponse.json({
  198. id: 2,
  199. username: 'operator',
  200. role: 'user',
  201. is_active: true,
  202. is_admin: false,
  203. groups: [{ id: 2, name: 'Operators' }],
  204. permissions,
  205. created_at: '2026-01-01T00:00:00Z',
  206. }),
  207. ),
  208. // The 403 that started it. Layout must not need this call at all.
  209. http.get('/api/v1/settings/', () =>
  210. HttpResponse.json({ detail: 'Not enough permissions' }, { status: 403 }),
  211. ),
  212. );
  213. // localStorage is a no-op mock in setup.ts, so writing the key there
  214. // authenticates nobody. Set the client's token directly.
  215. priorToken = getAuthToken();
  216. setAuthToken('test-token', 'session');
  217. };
  218. afterEach(() => {
  219. setAuthToken(priorToken, 'session');
  220. priorToken = null;
  221. });
  222. it('shows Finance to a user with cost_centers:read_own and no settings:read', async () => {
  223. asNonAdmin(['cost_centers:read_own']);
  224. server.use(
  225. http.get('/api/v1/settings/ui-flags', () =>
  226. HttpResponse.json({ billing_enabled: true, user_notifications_enabled: true }),
  227. ),
  228. );
  229. render(<Layout />);
  230. await waitFor(() => {
  231. expect(document.querySelector('aside a[href="/finance"]')).toBeInTheDocument();
  232. });
  233. });
  234. it('still hides Finance from that user when billing is off', async () => {
  235. // Waits on Notifications appearing rather than on the sidebar existing.
  236. // Asserting absence the moment <aside> renders passes before the flags
  237. // query has even resolved, which makes the assertion prove nothing.
  238. asNonAdmin(['cost_centers:read_own', 'notifications:user_email']);
  239. server.use(
  240. http.get('/api/v1/auth/advanced-auth/status', () =>
  241. HttpResponse.json({ advanced_auth_enabled: true }),
  242. ),
  243. http.get('/api/v1/settings/ui-flags', () =>
  244. HttpResponse.json({ billing_enabled: false, user_notifications_enabled: true }),
  245. ),
  246. );
  247. render(<Layout />);
  248. await waitFor(() => {
  249. expect(document.querySelector('aside a[href="/notifications"]')).toBeInTheDocument();
  250. });
  251. expect(document.querySelector('aside a[href="/finance"]')).toBeNull();
  252. });
  253. it('hides Notifications from that user when user notifications are off', async () => {
  254. // The same 403, landing the other way up: this gate tests `=== false`,
  255. // which undefined never satisfies, so an administrator who switched user
  256. // notifications off still left the entry showing to the non-admins it
  257. // governs. Unreported, and invisible to an admin testing it.
  258. asNonAdmin(['notifications:user_email', 'cost_centers:read_own']);
  259. server.use(
  260. http.get('/api/v1/auth/advanced-auth/status', () =>
  261. HttpResponse.json({ advanced_auth_enabled: true }),
  262. ),
  263. http.get('/api/v1/settings/ui-flags', () =>
  264. HttpResponse.json({ billing_enabled: true, user_notifications_enabled: false }),
  265. ),
  266. );
  267. render(<Layout />);
  268. // Finance appearing is the proof that the flags arrived; only then does
  269. // the absence of Notifications mean anything.
  270. await waitFor(() => {
  271. expect(document.querySelector('aside a[href="/finance"]')).toBeInTheDocument();
  272. });
  273. expect(document.querySelector('aside a[href="/notifications"]')).toBeNull();
  274. });
  275. it('shows Notifications to that user when they are on', async () => {
  276. asNonAdmin(['notifications:user_email']);
  277. server.use(
  278. http.get('/api/v1/auth/advanced-auth/status', () =>
  279. HttpResponse.json({ advanced_auth_enabled: true }),
  280. ),
  281. http.get('/api/v1/settings/ui-flags', () =>
  282. HttpResponse.json({ billing_enabled: false, user_notifications_enabled: true }),
  283. ),
  284. );
  285. render(<Layout />);
  286. await waitFor(() => {
  287. expect(document.querySelector('aside a[href="/notifications"]')).toBeInTheDocument();
  288. });
  289. });
  290. });
  291. describe('version display', () => {
  292. it('shows version info', async () => {
  293. render(<Layout />);
  294. await waitFor(() => {
  295. // Version info is displayed in sidebar
  296. expect(document.body).toBeInTheDocument();
  297. });
  298. });
  299. });
  300. describe('theme toggle', () => {
  301. it('has theme toggle button', async () => {
  302. render(<Layout />);
  303. await waitFor(() => {
  304. // Theme toggle should be present
  305. const buttons = document.querySelectorAll('button');
  306. expect(buttons.length).toBeGreaterThan(0);
  307. });
  308. });
  309. it('cycles through dark → light → system → dark', async () => {
  310. localStorage.setItem('theme-mode', 'dark');
  311. render(<Layout />);
  312. await waitFor(() => {
  313. // In dark mode, title should say "Switch to light mode"
  314. const btn = document.querySelector('button[title="Switch to light mode"]');
  315. expect(btn).toBeInTheDocument();
  316. });
  317. // Click to go from dark → light
  318. const lightBtn = document.querySelector('button[title="Switch to light mode"]')!;
  319. lightBtn.click();
  320. await waitFor(() => {
  321. // In light mode, title should say "Switch to system mode"
  322. const btn = document.querySelector('button[title="Switch to system mode"]');
  323. expect(btn).toBeInTheDocument();
  324. });
  325. // Click to go from light → system
  326. const systemBtn = document.querySelector('button[title="Switch to system mode"]')!;
  327. systemBtn.click();
  328. await waitFor(() => {
  329. // In system mode, title should say "Switch to dark mode"
  330. const btn = document.querySelector('button[title="Switch to dark mode"]');
  331. expect(btn).toBeInTheDocument();
  332. });
  333. // Click to go from system → dark
  334. const darkBtn = document.querySelector('button[title="Switch to dark mode"]')!;
  335. darkBtn.click();
  336. await waitFor(() => {
  337. // Back to dark mode
  338. const btn = document.querySelector('button[title="Switch to light mode"]');
  339. expect(btn).toBeInTheDocument();
  340. });
  341. });
  342. });
  343. describe('plate detection alert modal', () => {
  344. it('shows modal when plate-not-empty event is dispatched', async () => {
  345. render(<Layout />);
  346. // Dispatch the plate-not-empty event
  347. window.dispatchEvent(
  348. new CustomEvent('plate-not-empty', {
  349. detail: {
  350. printer_id: 1,
  351. printer_name: 'Test Printer',
  352. message: 'Objects detected on build plate',
  353. },
  354. })
  355. );
  356. await waitFor(() => {
  357. // Modal should appear with "Print Paused!" text
  358. expect(document.body.textContent).toContain('Print Paused!');
  359. expect(document.body.textContent).toContain('Test Printer');
  360. });
  361. });
  362. it('closes modal when I Understand button is clicked', async () => {
  363. render(<Layout />);
  364. // Dispatch the plate-not-empty event
  365. window.dispatchEvent(
  366. new CustomEvent('plate-not-empty', {
  367. detail: {
  368. printer_id: 1,
  369. printer_name: 'Test Printer',
  370. message: 'Objects detected on build plate',
  371. },
  372. })
  373. );
  374. await waitFor(() => {
  375. expect(document.body.textContent).toContain('Print Paused!');
  376. });
  377. // Click the "I Understand" button
  378. const button = document.querySelector('button');
  379. if (button && button.textContent?.includes('I Understand')) {
  380. button.click();
  381. }
  382. // Find and click the "I Understand" button by searching all buttons
  383. const buttons = document.querySelectorAll('button');
  384. buttons.forEach((btn) => {
  385. if (btn.textContent?.includes('I Understand')) {
  386. btn.click();
  387. }
  388. });
  389. await waitFor(() => {
  390. // Modal should be closed
  391. expect(document.body.textContent).not.toContain('Print Paused!');
  392. });
  393. });
  394. });
  395. describe('developer mode warning banner', () => {
  396. it('shows warning banner when printers lack developer mode', async () => {
  397. server.use(
  398. http.get('/api/v1/printers/developer-mode-warnings', () => {
  399. return HttpResponse.json([
  400. { printer_id: 1, name: 'X1 Carbon' },
  401. ]);
  402. })
  403. );
  404. render(<Layout />);
  405. await waitFor(() => {
  406. expect(document.body.textContent).toContain('Developer LAN mode is not enabled on');
  407. expect(document.body.textContent).toContain('X1 Carbon');
  408. });
  409. });
  410. it('shows multiple printer names in warning banner', async () => {
  411. server.use(
  412. http.get('/api/v1/printers/developer-mode-warnings', () => {
  413. return HttpResponse.json([
  414. { printer_id: 1, name: 'X1 Carbon' },
  415. { printer_id: 2, name: 'P1S' },
  416. ]);
  417. })
  418. );
  419. render(<Layout />);
  420. await waitFor(() => {
  421. expect(document.body.textContent).toContain('X1 Carbon');
  422. expect(document.body.textContent).toContain('P1S');
  423. });
  424. });
  425. it('hides warning banner when no printers lack developer mode', async () => {
  426. // Default handler returns empty array
  427. render(<Layout />);
  428. await waitFor(() => {
  429. const sidebar = document.querySelector('aside');
  430. expect(sidebar).toBeInTheDocument();
  431. });
  432. // Banner should not be present
  433. expect(document.body.textContent).not.toContain('Developer LAN mode is not enabled on');
  434. });
  435. it('shows how to enable link in warning banner', async () => {
  436. server.use(
  437. http.get('/api/v1/printers/developer-mode-warnings', () => {
  438. return HttpResponse.json([
  439. { printer_id: 1, name: 'X1 Carbon' },
  440. ]);
  441. })
  442. );
  443. render(<Layout />);
  444. await waitFor(() => {
  445. expect(document.body.textContent).toContain('How to enable');
  446. const link = document.querySelector('a[href*="enable-developer-mode"]');
  447. expect(link).toBeInTheDocument();
  448. });
  449. });
  450. });
  451. describe('update banner suppression for HA addon', () => {
  452. // HA Supervisor surfaces its own update notification natively in the HA
  453. // UI, so the in-app banner would be duplicate noise that links to a page
  454. // that just says "update via HA". Suppress it for HA addon deployments.
  455. it('hides the update-available banner when running as an HA addon', async () => {
  456. server.use(
  457. http.get('/api/v1/updates/check', () => {
  458. return HttpResponse.json({
  459. update_available: true,
  460. current_version: '0.2.4',
  461. latest_version: '0.2.5',
  462. is_docker: true,
  463. is_ha_addon: true,
  464. update_method: 'ha_addon',
  465. });
  466. }),
  467. );
  468. render(<Layout />);
  469. await waitFor(() => {
  470. const sidebar = document.querySelector('aside');
  471. expect(sidebar).toBeInTheDocument();
  472. });
  473. expect(document.body.textContent).not.toContain('Update available');
  474. });
  475. it('still shows the update-available banner for plain Docker deployments', async () => {
  476. server.use(
  477. http.get('/api/v1/updates/check', () => {
  478. return HttpResponse.json({
  479. update_available: true,
  480. current_version: '0.2.4',
  481. latest_version: '0.2.5',
  482. is_docker: true,
  483. is_ha_addon: false,
  484. update_method: 'docker',
  485. });
  486. }),
  487. );
  488. render(<Layout />);
  489. await waitFor(() => {
  490. expect(document.body.textContent).toContain('0.2.5');
  491. });
  492. });
  493. });
  494. describe('MakerWorld sidebar permission gate (#1175)', () => {
  495. // The MakerWorld sidebar entry was visible to every authenticated user
  496. // regardless of group permissions because Layout's `navPermissions` map
  497. // had no entry for `makerworld`. Backend routes already gated on
  498. // `makerworld:view`, so users without the permission saw the entry,
  499. // clicked, and got 403'd by every API call inside the page. The fix
  500. // adds `makerworld: 'makerworld:view'` to the map so the entry is
  501. // hidden when the permission is absent — same shape as every other
  502. // sidebar entry.
  503. const enableAuthWithUser = (permissions: string[]) => {
  504. server.use(
  505. http.get('/api/v1/auth/status', () =>
  506. HttpResponse.json({ auth_enabled: true, requires_setup: false }),
  507. ),
  508. http.get('/api/v1/auth/me', () =>
  509. HttpResponse.json({
  510. id: 1,
  511. username: 'tester',
  512. role: 'user',
  513. is_active: true,
  514. is_admin: false,
  515. groups: [{ id: 2, name: 'Standard Users' }],
  516. permissions,
  517. created_at: '2026-01-01T00:00:00Z',
  518. }),
  519. ),
  520. );
  521. // AuthProvider needs a token in localStorage to fetch /auth/me; the
  522. // value isn't validated by the mocked server.
  523. window.localStorage.setItem('auth_token', 'test-token');
  524. };
  525. const findMakerWorldNavLink = () => {
  526. // Sidebar nav links use react-router's `to` prop, which renders as a
  527. // plain `<a href="/model-sources">`. Match on the href so the test isn't
  528. // coupled to whatever locale string is rendered. The page was
  529. // MakerWorld-only until Manyfold joined it as a second tab (#1471).
  530. return document.querySelector('aside a[href="/model-sources"]');
  531. };
  532. it('hides the Model Sources nav entry when the user has neither source permission', async () => {
  533. // Standard user without the MakerWorld permission. Every other
  534. // permission they hold (library:read, etc.) is irrelevant here — the
  535. // gate is per-entry and the MakerWorld entry must not render.
  536. enableAuthWithUser(['library:read', 'archives:read', 'queue:read']);
  537. render(<Layout />);
  538. await waitFor(() => {
  539. // Wait for the auth resolution + sidebar render. Some other nav
  540. // entry (Files / Archives) confirms the sidebar finished mounting.
  541. const sidebar = document.querySelector('aside');
  542. expect(sidebar).toBeInTheDocument();
  543. expect(sidebar?.querySelector('a[href="/files"]')).toBeInTheDocument();
  544. });
  545. await waitFor(() => expect(findMakerWorldNavLink()).toBeNull());
  546. });
  547. it('shows the MakerWorld nav entry when the user has makerworld:view', async () => {
  548. enableAuthWithUser([
  549. 'library:read',
  550. 'archives:read',
  551. 'queue:read',
  552. 'makerworld:view',
  553. ]);
  554. render(<Layout />);
  555. await waitFor(() => {
  556. expect(findMakerWorldNavLink()).toBeInTheDocument();
  557. });
  558. });
  559. it('shows the Model Sources nav entry with manyfold:view alone (#1471)', async () => {
  560. enableAuthWithUser(['library:read', 'manyfold:view']);
  561. render(<Layout />);
  562. await waitFor(() => {
  563. expect(findMakerWorldNavLink()).toBeInTheDocument();
  564. });
  565. });
  566. });
  567. describe('Sidebar gate accepts granular read tiers (#1755)', () => {
  568. // Default Operators group is seeded with `*:read_own` only — never the
  569. // legacy `*:read`. Previously the sidebar gate checked the legacy alone,
  570. // so Archives / Queue / Files were hidden from every non-admin even
  571. // though the underlying API endpoints accepted their requests. These
  572. // tests pin that the gate accepts ANY of the three tiers (legacy /
  573. // _own / _all) for the three resources that ship granular variants.
  574. const enableAuthWithUser = (permissions: string[]) => {
  575. server.use(
  576. http.get('/api/v1/auth/status', () =>
  577. HttpResponse.json({ auth_enabled: true, requires_setup: false }),
  578. ),
  579. http.get('/api/v1/auth/me', () =>
  580. HttpResponse.json({
  581. id: 1,
  582. username: 'tester',
  583. role: 'user',
  584. is_active: true,
  585. is_admin: false,
  586. groups: [{ id: 2, name: 'Operators' }],
  587. permissions,
  588. created_at: '2026-01-01T00:00:00Z',
  589. }),
  590. ),
  591. );
  592. window.localStorage.setItem('auth_token', 'test-token');
  593. };
  594. const sidebarLink = (href: string) =>
  595. document.querySelector(`aside a[href="${href}"]`);
  596. it('shows Files in the sidebar when the user only has library:read_own', async () => {
  597. enableAuthWithUser(['library:read_own']);
  598. render(<Layout />);
  599. await waitFor(() => {
  600. expect(document.querySelector('aside')).toBeInTheDocument();
  601. expect(sidebarLink('/files')).toBeInTheDocument();
  602. });
  603. });
  604. it('shows Files in the sidebar when the user only has library:read_all', async () => {
  605. enableAuthWithUser(['library:read_all']);
  606. render(<Layout />);
  607. await waitFor(() => {
  608. expect(sidebarLink('/files')).toBeInTheDocument();
  609. });
  610. });
  611. it('shows Archives in the sidebar when the user only has archives:read_own', async () => {
  612. enableAuthWithUser(['archives:read_own']);
  613. render(<Layout />);
  614. await waitFor(() => {
  615. expect(sidebarLink('/archives')).toBeInTheDocument();
  616. });
  617. });
  618. it('shows Queue in the sidebar when the user only has queue:read_own', async () => {
  619. enableAuthWithUser(['queue:read_own']);
  620. render(<Layout />);
  621. await waitFor(() => {
  622. expect(sidebarLink('/queue')).toBeInTheDocument();
  623. });
  624. });
  625. it('still hides Files when the user has none of the three read tiers', async () => {
  626. enableAuthWithUser(['printers:read']);
  627. render(<Layout />);
  628. await waitFor(() => {
  629. expect(document.querySelector('aside')).toBeInTheDocument();
  630. });
  631. expect(sidebarLink('/files')).toBeNull();
  632. expect(sidebarLink('/archives')).toBeNull();
  633. expect(sidebarLink('/queue')).toBeNull();
  634. });
  635. });
  636. describe('outcome confirmation deep link (#1898)', () => {
  637. // The URL a Pushover / Bark notification opens in a brand new tab. Layout
  638. // is the PARENT of the page that renders at /archives, and React flushes a
  639. // child's effects before its parent's — so while the page owned this deep
  640. // link it dispatched `print-confirm-request` before Layout had added the
  641. // listener, and then stripped the parameter, leaving nothing to recover.
  642. // These tests pin the read where the dialog state lives.
  643. const archive = {
  644. id: 42,
  645. printer_id: 1,
  646. filename: 'bracket.gcode.3mf',
  647. print_name: 'Bracket',
  648. status: 'completed',
  649. photos: null,
  650. user_verdict: null,
  651. user_verdict_source: null,
  652. confirm_requested: true,
  653. };
  654. beforeEach(() => {
  655. server.use(
  656. http.get('/api/v1/archives/42', () => HttpResponse.json(archive))
  657. );
  658. });
  659. afterEach(() => {
  660. window.history.replaceState({}, '', '/');
  661. });
  662. it('opens the dialog on a cold load, with no page mounted to relay the event', async () => {
  663. window.history.replaceState({}, '', '/archives?confirm=42');
  664. render(<Layout />);
  665. expect(await screen.findByTestId('confirm-outcome-dialog')).toBeInTheDocument();
  666. });
  667. it('strips the parameter but keeps the rest of the query', async () => {
  668. window.history.replaceState({}, '', '/archives?confirm=42&status=completed');
  669. render(<Layout />);
  670. await screen.findByTestId('confirm-outcome-dialog');
  671. await waitFor(() => {
  672. expect(window.location.search).toBe('?status=completed');
  673. });
  674. expect(window.location.pathname).toBe('/archives');
  675. });
  676. it('ignores a confirm parameter that is not an archive id', async () => {
  677. window.history.replaceState({}, '', '/archives?confirm=not-an-id');
  678. render(<Layout />);
  679. await waitFor(() => {
  680. expect(document.querySelector('aside')).toBeInTheDocument();
  681. });
  682. expect(screen.queryByTestId('confirm-outcome-dialog')).toBeNull();
  683. // Nothing was consumed, so nothing is rewritten either.
  684. expect(window.location.search).toBe('?confirm=not-an-id');
  685. });
  686. // Round 4: the dialog's only outcome for a user who may not record a
  687. // verdict is a 403 from the PATCH, so it is gated like plate-not-empty —
  688. // on archives:update_all / archives:update_own, the names the June
  689. // permission migration left in the default groups.
  690. describe('without permission to record a verdict', () => {
  691. const withPermissions = (permissions: string[]) => {
  692. server.use(
  693. http.get('/api/v1/auth/status', () =>
  694. HttpResponse.json({ auth_enabled: true, requires_setup: false }),
  695. ),
  696. http.get('/api/v1/auth/me', () =>
  697. HttpResponse.json({
  698. id: 1,
  699. username: 'tester',
  700. role: 'user',
  701. is_active: true,
  702. is_admin: false,
  703. groups: [{ id: 2, name: 'Standard Users' }],
  704. permissions,
  705. created_at: '2026-01-01T00:00:00Z',
  706. }),
  707. ),
  708. );
  709. // localStorage is a mock in this suite, so the token goes through the
  710. // client the way the app sets it — AuthProvider will not fetch
  711. // /auth/me without one, and the permissions would stay empty.
  712. setAuthToken('test-token');
  713. };
  714. afterEach(() => {
  715. setAuthToken(null);
  716. });
  717. it('ignores the event', async () => {
  718. withPermissions(['archives:read_all']);
  719. render(<Layout />);
  720. await waitFor(() => {
  721. expect(document.querySelector('aside')).toBeInTheDocument();
  722. });
  723. window.dispatchEvent(
  724. new CustomEvent('print-confirm-request', { detail: { archive_id: 42 } })
  725. );
  726. await waitFor(() => {
  727. expect(screen.queryByTestId('confirm-outcome-dialog')).toBeNull();
  728. });
  729. });
  730. it('consumes the deep link without opening anything', async () => {
  731. withPermissions(['archives:read_all']);
  732. window.history.replaceState({}, '', '/archives?confirm=42');
  733. render(<Layout />);
  734. // The parameter still goes: a link that can open nothing should not
  735. // survive a reload either.
  736. await waitFor(() => {
  737. expect(window.location.search).toBe('');
  738. });
  739. expect(screen.queryByTestId('confirm-outcome-dialog')).toBeNull();
  740. });
  741. it('opens for a user who may update their own archives', async () => {
  742. withPermissions(['archives:read_own', 'archives:update_own']);
  743. render(<Layout />);
  744. await waitFor(() => {
  745. expect(document.querySelector('aside')).toBeInTheDocument();
  746. });
  747. window.dispatchEvent(
  748. new CustomEvent('print-confirm-request', { detail: { archive_id: 42 } })
  749. );
  750. expect(await screen.findByTestId('confirm-outcome-dialog')).toBeInTheDocument();
  751. });
  752. });
  753. it('still opens from the WebSocket event, which carries no URL', async () => {
  754. render(<Layout />);
  755. await waitFor(() => {
  756. expect(document.querySelector('aside')).toBeInTheDocument();
  757. });
  758. window.dispatchEvent(
  759. new CustomEvent('print-confirm-request', { detail: { archive_id: 42 } })
  760. );
  761. expect(await screen.findByTestId('confirm-outcome-dialog')).toBeInTheDocument();
  762. });
  763. });
  764. });