// @vitest-environment jsdom import '@testing-library/jest-dom/vitest'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { HttpResponse, http } from 'msw'; import { setupServer } from 'msw/node'; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { MediaPage } from '../../apps/dashboard/src/features/media/media-page.js'; const now = Date.now(); const mediaItems = [ { id: 'one', chatUsername: 'alice', chatRoomId: 'room-a', sender: 'alice', timestamp: now - 60_000, originalUrl: 'https://media.example/one.jpg', fileName: 'one.jpg', relativePath: 'one.jpg', createdAt: now - 50_000, urlPath: '/media/one.jpg', }, { id: 'two', chatUsername: 'bob', chatRoomId: 'room-b', sender: 'charlie', timestamp: now - (3 * 86_400_000), originalUrl: 'https://media.example/two.gif', fileName: 'two.gif', relativePath: 'two.gif', createdAt: now - (3 * 86_400_000), urlPath: '/media/two.gif', }, { id: 'three', chatUsername: null, chatRoomId: 'room-c', sender: 'dave', timestamp: now - (40 * 86_400_000), originalUrl: 'https://media.example/three.png', fileName: 'three.png', relativePath: 'three.png', createdAt: now - (40 * 86_400_000), urlPath: '/media/three.png', }, ]; const idleStatus = { isSyncing: false, lastSyncAt: now - 120_000, lastSyncDurationMs: 2_400, lastSyncChats: 3, lastError: null, nextSyncAt: now + 1_800_000, }; const server = setupServer(); function installMediaApi(items = mediaItems) { server.use( http.get('/api/media', () => HttpResponse.json(items)), http.get('/api/media/sync', () => HttpResponse.json(idleStatus)), ); } function renderMedia() { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, }); const view = render( , ); return { ...view, queryClient }; } beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); afterEach(() => { cleanup(); server.resetHandlers(); vi.restoreAllMocks(); }); afterAll(() => server.close()); describe('media page', () => { it('loads authenticated media, keeps it blurred, and supports item and session-local reveals', async () => { let resolveMedia: ((response: Response) => void) | undefined; const credentials: RequestCredentials[] = []; server.use( http.get('/api/media', async ({ request }) => { credentials.push(request.credentials); return new Promise((resolve) => { resolveMedia = resolve; }); }), http.get('/api/media/sync', ({ request }) => { credentials.push(request.credentials); return HttpResponse.json(idleStatus); }), ); const user = userEvent.setup(); const firstView = renderMedia(); expect(screen.getByRole('status', { name: 'Loading media' })).toBeInTheDocument(); await waitFor(() => expect(resolveMedia).toBeTypeOf('function')); resolveMedia?.(HttpResponse.json(mediaItems)); const aliceImage = await screen.findByRole('img', { name: 'Media from alice' }); const charlieImage = screen.getByRole('img', { name: 'Media from charlie' }); for (const profileLink of screen.getAllByRole('link', { name: 'alice' })) { expect(profileLink).toHaveAttribute('href', 'https://www.reddit.com/u/alice'); } expect(aliceImage).toHaveClass('is-blurred'); expect(charlieImage).toHaveClass('is-blurred'); expect(credentials.every((value) => value === 'same-origin')).toBe(true); await user.click(screen.getByRole('button', { name: 'Reveal media from alice' })); expect(aliceImage).not.toHaveClass('is-blurred'); expect(charlieImage).toHaveClass('is-blurred'); await user.click(screen.getByRole('button', { name: 'Reveal all media' })); expect(charlieImage).not.toHaveClass('is-blurred'); firstView.unmount(); installMediaApi(); renderMedia(); expect(await screen.findByRole('img', { name: 'Media from alice' })).toHaveClass('is-blurred'); }); it('opens revealed media in a dismissible full-size preview', async () => { installMediaApi(); const user = userEvent.setup(); renderMedia(); await user.click(await screen.findByRole('button', { name: 'Reveal media from alice' })); await user.click(screen.getByRole('button', { name: 'View media from alice larger' })); const dialog = screen.getByRole('dialog', { name: 'Media from alice' }); expect(within(dialog).getByRole('img', { name: 'Media from alice' })).toHaveAttribute('src', '/media/one.jpg'); await user.keyboard('{Escape}'); expect(screen.queryByRole('dialog', { name: 'Media from alice' })).not.toBeInTheDocument(); }); it('filters by conversation, sender, media type, and age with an explicit no-match state', async () => { installMediaApi(); const user = userEvent.setup(); renderMedia(); expect(await screen.findAllByRole('img')).toHaveLength(3); await user.selectOptions(screen.getByRole('combobox', { name: 'Conversation' }), 'alice'); expect(screen.getAllByRole('img')).toHaveLength(1); expect(screen.getByRole('img', { name: 'Media from alice' })).toBeInTheDocument(); await user.selectOptions(screen.getByRole('combobox', { name: 'Conversation' }), 'all'); await user.selectOptions(screen.getByRole('combobox', { name: 'Sender' }), 'charlie'); expect(screen.getByRole('img', { name: 'Media from charlie' })).toBeInTheDocument(); await user.selectOptions(screen.getByRole('combobox', { name: 'Sender' }), 'all'); await user.selectOptions(screen.getByRole('combobox', { name: 'Media type' }), 'gif'); expect(screen.getAllByRole('img')).toHaveLength(1); await user.selectOptions(screen.getByRole('combobox', { name: 'Media type' }), 'all'); await user.selectOptions(screen.getByRole('combobox', { name: 'Date range' }), '7d'); expect(screen.getAllByRole('img')).toHaveLength(2); await user.selectOptions(screen.getByRole('combobox', { name: 'Conversation' }), 'room-c'); expect(screen.getByText('No media matches these filters.')).toBeInTheDocument(); }); it('shows empty and recoverable error states', async () => { let requests = 0; server.use( http.get('/api/media', () => { requests += 1; return requests === 1 ? HttpResponse.json({ error: 'Media index unavailable' }, { status: 500 }) : HttpResponse.json([]); }), http.get('/api/media/sync', () => HttpResponse.json(idleStatus)), ); const user = userEvent.setup(); renderMedia(); const alert = await screen.findByRole('alert'); expect(alert).toHaveTextContent('Media index unavailable'); await user.click(within(alert).getByRole('button', { name: 'Retry media' })); expect(await screen.findByText('No media yet.')).toBeInTheDocument(); expect(requests).toBe(2); }); it('runs delta sync as the primary action and surfaces query-driven status and mutation outcomes', async () => { installMediaApi(); let deltaRequests = 0; server.use( http.post('/api/media/sync', ({ request }) => { deltaRequests += 1; expect(request.credentials).toBe('same-origin'); return HttpResponse.json({ success: true }); }), ); const user = userEvent.setup(); renderMedia(); const deltaButton = await screen.findByRole('button', { name: 'Sync new media' }); expect(deltaButton).toHaveClass('primary'); expect(screen.getByText('Last synced 3 conversations')).toBeInTheDocument(); await user.click(deltaButton); expect(await screen.findByText('Media sync completed.')).toBeInTheDocument(); expect(deltaRequests).toBe(1); server.use( http.post('/api/media/sync', () => HttpResponse.json({ success: false, reason: 'Sync already in progress' })), ); await user.click(screen.getByRole('button', { name: 'Sync new media' })); expect(await screen.findByRole('alert')).toHaveTextContent('Sync already in progress'); }); it('refreshes shared sync status as soon as a long-running mutation starts', async () => { let statusRequests = 0; let resolveSync: ((response: Response) => void) | undefined; server.use( http.get('/api/media', () => HttpResponse.json(mediaItems)), http.get('/api/media/sync', () => { statusRequests += 1; return HttpResponse.json(statusRequests === 1 ? idleStatus : { ...idleStatus, isSyncing: true }); }), http.post('/api/media/sync', async () => new Promise((resolve) => { resolveSync = resolve; }), ), ); const user = userEvent.setup(); renderMedia(); await user.click(await screen.findByRole('button', { name: 'Sync new media' })); expect(await screen.findByText('Media sync in progress')).toBeInTheDocument(); expect(statusRequests).toBeGreaterThan(1); resolveSync?.(HttpResponse.json({ success: true })); await waitFor(() => expect(screen.getByText('Media sync completed.')).toBeInTheDocument()); }); it('guards a full sync with explicit confirmation', async () => { installMediaApi(); let fullRequests = 0; server.use( http.post('/api/media/sync/full', () => { fullRequests += 1; return HttpResponse.json({ success: true }); }), ); const user = userEvent.setup(); renderMedia(); await user.click(await screen.findByRole('button', { name: 'Full sync' })); const dialog = screen.getByRole('dialog', { name: 'Run full media sync?' }); expect(dialog).toHaveTextContent('every conversation'); expect(fullRequests).toBe(0); await user.click(within(dialog).getByRole('button', { name: 'Cancel' })); expect(fullRequests).toBe(0); await user.click(screen.getByRole('button', { name: 'Full sync' })); await user.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Run full sync' })); expect(await screen.findByText('Full media sync completed.')).toBeInTheDocument(); expect(fullRequests).toBe(1); }); it('closes the full-sync dialog so a failed mutation is clearly visible', async () => { installMediaApi(); server.use( http.post('/api/media/sync/full', () => HttpResponse.json({ error: 'Full sync could not reach Reddit' }, { status: 500 }), ), ); const user = userEvent.setup(); renderMedia(); await user.click(await screen.findByRole('button', { name: 'Full sync' })); await user.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Run full sync' })); expect(await screen.findByRole('alert')).toHaveTextContent('Full sync could not reach Reddit'); expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); }); });