diff --git a/AGENTS.md b/AGENTS.md index 6a91f08a..0e2d3d12 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -286,8 +286,9 @@ describe('Team API', () => { - Located in `apps/web/e2e/**/*.spec.ts`, organized by domain under `tests//` (e.g. `auth`, `project`). - Run via `bun run test:e2e`. -- **Fixtures**: Use the `owner` and `project` fixtures for setup — they seed data through API calls (no slow UI setup). UI interactions are only allowed in the flow under test. +- **Fixtures**: Use the `owner`, `project`, and `file` fixtures for setup — they seed data through API calls/DB (no slow UI setup). UI interactions are only allowed in the flow under test. - **DB isolation**: Each test truncates all tables via the auto `prisma` fixture, so fixtures must create their data per-test. App projects run with `workers: 1` because all tests share a single database. +- **Documentation**: Every test case MUST be documented in [`apps/web/e2e/README.md`](apps/web/e2e/README.md). Add or update the corresponding entry in the README whenever you add, rename, or remove a spec. ## Prisma Configuration & Migrations diff --git a/apps/web/e2e/README.md b/apps/web/e2e/README.md new file mode 100644 index 00000000..8f938b8e --- /dev/null +++ b/apps/web/e2e/README.md @@ -0,0 +1,81 @@ +# Web App E2E Tests + +Fullstack end-to-end tests for the Shumai web app. They run against a real backend +(pgvector container + local S3 storage) served on `http://localhost:5200` and are +executed with Playwright via `bun run test:e2e`. + +## Structure + +``` +apps/web/e2e/ +├── fixtures.ts # prisma / owner / project / file fixtures +├── serve.ts # starts the test DB container + web app +├── global-teardown.ts # stops the container and cleans up storage +├── helpers/ +│ ├── auth.ts # signup / auth-state injection helpers +│ ├── project.ts # project creation helpers +│ ├── files.ts # share link API helpers +│ ├── team.ts # team member seeding helpers +│ └── ui.ts # common UI flows (signup, login, members dialog) +└── tests// # domain-scoped specs (auth, team, project) +``` + +## Fixtures + +- `prisma` — auto fixture that truncates all tables before each test. Also the + direct way to read/write DB state for assertions and seeding. +- `owner` — an authenticated team owner (seeded through the API), with the session + cookie and auth state injected into the browser context, opened on the team page. +- `project` — `owner` plus a project created through the API (`projectId`, + `projectName`). +- `file` — `project` plus a seeded processed file asset in the project root + (`fileId`, `fileName`). The media kind is configurable per test via + `fileOptions` (default `binary`): + + ```ts + // default binary file (no extension, no proxy) + test('...', async ({ file }) => {}) + + // type-scoped file for future viewer/transcode tests + test('...', { fileOptions: { mediaType: 'image' } }, async ({ file }) => {}) + ``` + + | mediaType | filename | notes | + |---|---|---| + | `binary` (default) | `test-file-` | never transcoded, no proxy | + | `text` | `test-file-.txt` | gets a PDF proxy in real usage | + | `image` | `test-file-.png` | | + | `video` | `test-file-.mp4` | | + | `pdf` | `test-file-.pdf` | | + +## Test Cases + +### auth +| Test | File | +|---|---| +| Sign up as the first user and become the team owner | `tests/auth/signup.spec.ts` | +| Log in with existing credentials | `tests/auth/login.spec.ts` | + +### team +| Test | File | +|---|---| +| Owner invites a member via invite link and the invitee joins | `tests/team/invite-member.spec.ts` | +| Owner removes a member via the members dialog; the membership is deleted from the DB | `tests/team/remove-member.spec.ts` | + +### project +| Test | File | +|---|---| +| Owner creates a project with a cover image | `tests/project/create-project.spec.ts` | +| Owner uploads a file via the "Upload File" context menu action | `tests/project/upload-file.spec.ts` | +| Owner deletes a file, finds it in recently deleted, and restores it | `tests/project/delete-restore.spec.ts` | +| Owner creates a share link from a file context menu and lands on the share page | `tests/project/create-share-link.spec.ts` | +| Owner protects a share with a password; guests must enter it to view | `tests/project/share-password.spec.ts` | +| Owner creates a collection from the sidebar; the collection shows project files | `tests/project/create-collection.spec.ts` | + +## Conventions + +- Seed data via fixtures/API/DB; use the UI only for the flow under test. +- Each test truncates all tables via the auto `prisma` fixture, so fixtures must + create their data per-test. +- App projects run with `workers: 1` because all tests share a single database. +- Every new test case MUST be documented in this README. diff --git a/apps/web/e2e/fixtures.ts b/apps/web/e2e/fixtures.ts index 6ef1600b..8c9808ff 100644 --- a/apps/web/e2e/fixtures.ts +++ b/apps/web/e2e/fixtures.ts @@ -46,11 +46,36 @@ export interface ProjectFixture extends OwnerFixture { projectName: string } +/** The media kind of a seeded test file. */ +export type FileMediaType = 'text' | 'binary' | 'image' | 'video' | 'pdf' + +export interface FileFixtureOptions { + /** Defaults to `binary` (no extension, never transcoded, no proxy). */ + mediaType?: FileMediaType +} + +export interface FileFixture extends ProjectFixture { + fileId: string + fileName: string + fileMediaType: FileMediaType +} + +const FILE_TYPE_MAP: Record = { + text: { ext: 'txt', mime: 'text/plain' }, + binary: { ext: '', mime: 'application/octet-stream' }, + image: { ext: 'png', mime: 'image/png' }, + video: { ext: 'mp4', mime: 'video/mp4' }, + pdf: { ext: 'pdf', mime: 'application/pdf' }, +} + export const test = base.extend<{ prisma: PrismaClient owner: OwnerFixture project: ProjectFixture + fileOptions: FileFixtureOptions + file: FileFixture }>({ + fileOptions: [{ mediaType: 'binary' }, { option: true }], prisma: [ // eslint-disable-next-line no-empty-pattern async ({}, use) => { @@ -112,6 +137,34 @@ export const test = base.extend<{ const project = await apiCreateProject(owner.context.request, owner.teamId, name) await use({ ...owner, projectId: project.id, projectName: name }) }, + /** + * Sets up an owner + project with a seeded processed file asset under the + * project root folder. The media type is configurable per test via + * `fileOptions` (defaults to `binary`). + */ + file: async ({ project, prisma, fileOptions }, use) => { + const mediaType: FileMediaType = fileOptions.mediaType ?? 'binary' + const { ext, mime } = FILE_TYPE_MAP[mediaType] + const fileName = `test-file-${Date.now()}${ext ? `.${ext}` : ''}` + + const projectRow = await prisma.project.findUnique({ where: { id: project.projectId } }) + const rootFolderId = projectRow?.rootFolderId + if (!rootFolderId) throw new Error('Project has no root folder') + + const file = await prisma.asset.create({ + data: { + name: fileName, + type: 'file', + status: 'processed', + sizeByte: 10, + mediaType: mime, + projectId: project.projectId, + parentId: rootFolderId, + }, + }) + + await use({ ...project, fileId: file.id, fileName, fileMediaType: mediaType }) + }, }) export { expect } from '@playwright/test' diff --git a/apps/web/e2e/helpers/files.ts b/apps/web/e2e/helpers/files.ts new file mode 100644 index 00000000..16bf9614 --- /dev/null +++ b/apps/web/e2e/helpers/files.ts @@ -0,0 +1,52 @@ +import type { APIRequestContext, Locator, Page } from '@playwright/test' + +interface CreateShareResponse { + id?: string + name?: string +} + +/** + * Locates a file/folder card by its name. File names are rendered as + * `EditableText` inputs (not text nodes), so `getByText` does not match them. + * The returned locator points at the card wrapper div (right-clickable to open + * the card context menu). + */ +export function fileCard(page: Page, name: string): Locator { + return page + .locator('div.group') + .filter({ has: page.locator(`input[value="${name}"]`) }) + .first() +} + +/** Creates a share link through the API for the authenticated request context. */ +export async function apiCreateShare( + request: APIRequestContext, + projectId: string, + name: string, +): Promise<{ id: string; name: string }> { + const res = await request.post(`/api/projects/${projectId}/shares`, { + data: { name }, + }) + if (!res.ok()) { + throw new Error(`Create share API failed (${res.status()}): ${await res.text()}`) + } + const body = (await res.json()) as CreateShareResponse + if (!body.id || !body.name) { + throw new Error(`Create share returned an unexpected response: ${JSON.stringify(body)}`) + } + return { id: body.id, name: body.name } +} + +/** Adds assets to a share link through the API. */ +export async function apiAddAssetsToShare( + request: APIRequestContext, + shareId: string, + assetIds: string[], +): Promise { + const res = await request.post(`/api/shares/${shareId}/assets`, { + data: { assetIds }, + }) + if (!res.ok()) { + throw new Error(`Add assets to share API failed (${res.status()}): ${await res.text()}`) + } +} diff --git a/apps/web/e2e/helpers/team.ts b/apps/web/e2e/helpers/team.ts new file mode 100644 index 00000000..26343532 --- /dev/null +++ b/apps/web/e2e/helpers/team.ts @@ -0,0 +1,26 @@ +import type { PrismaClient } from '../../../../packages/db/src/generated/prisma/client' +import { uniqueEmail } from './auth' + +export interface SeededMember { + userId: string + email: string +} + +/** + * Seeds a new user with a team membership of the given role directly through + * the database (fast, no UI). The user is not authenticated. + */ +export async function seedTeamMember( + prisma: PrismaClient, + teamId: string, + role: 'owner' | 'editor' | 'reviewer', +): Promise { + const email = uniqueEmail(`member-${role}`) + const user = await prisma.user.create({ + data: { name: email, email, password: 'Password123!' }, + }) + await prisma.teamMember.create({ + data: { teamId, userId: user.id, role, scope: 'team' }, + }) + return { userId: user.id, email } +} diff --git a/apps/web/e2e/tests/project/create-collection.spec.ts b/apps/web/e2e/tests/project/create-collection.spec.ts new file mode 100644 index 00000000..011574ae --- /dev/null +++ b/apps/web/e2e/tests/project/create-collection.spec.ts @@ -0,0 +1,31 @@ +import { expect, test } from '../../fixtures' +import { fileCard } from '../../helpers/files' + +test('owner creates a collection from the sidebar and the collection shows project files', async ({ + file, + prisma, +}) => { + const { page, projectId, fileName } = file + + await page.goto(`/projects/${projectId}`) + await expect(fileCard(page, fileName)).toBeVisible() + + // Create a collection via the sidebar "+" button + await page.getByTestId('create-collection').click() + + await expect(page).toHaveURL(/\/collections\/[^/]+/) + await expect(page.getByText('Collection created')).toBeVisible() + + // The collection page is a recursive files-only view of the project + await expect(fileCard(page, fileName)).toBeVisible() + + const collection = await prisma.collection.findFirst({ where: { projectId } }) + expect(collection).not.toBeNull() + expect(collection?.name).toBe('Untitled Collection') + + const project = await prisma.project.findUnique({ where: { id: projectId } }) + expect(collection?.filter).toMatchObject({ + sourceFolderId: project?.rootFolderId, + searchFilter: { conditions: [], recursively: true }, + }) +}) diff --git a/apps/web/e2e/tests/project/create-share-link.spec.ts b/apps/web/e2e/tests/project/create-share-link.spec.ts new file mode 100644 index 00000000..ea2a799d --- /dev/null +++ b/apps/web/e2e/tests/project/create-share-link.spec.ts @@ -0,0 +1,36 @@ +import { expect, test } from '../../fixtures' +import { fileCard } from '../../helpers/files' + +test('owner creates a share link from a file context menu and lands on the share page', async ({ + file, + prisma, +}) => { + const { page, projectId, fileName, fileId } = file + + await page.goto(`/projects/${projectId}`) + await expect(fileCard(page, fileName)).toBeVisible() + + // Create a share link for the file through the context menu + await fileCard(page, fileName).click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Create Share Link' }).click() + + // The toast offers a "View" action that navigates to the share page + const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' }) + await expect(toast).toBeVisible() + await toast.getByRole('button', { name: 'View' }).click() + + await expect(page).toHaveURL(/\/projects\/[^/]+\/shares\/[^/]+/) + + // The shared file is listed in the share contents + await expect(fileCard(page, fileName)).toBeVisible() + + // DB: the share exists and the file is symlinked under the share root + const share = await prisma.shareLink.findFirst({ where: { projectId } }) + expect(share).not.toBeNull() + + const symlink = await prisma.asset.findFirst({ + where: { parentId: share?.rootFolderId, targetId: fileId }, + }) + expect(symlink).not.toBeNull() + expect(symlink?.type).toBe('symlink') +}) diff --git a/apps/web/e2e/tests/project/delete-restore.spec.ts b/apps/web/e2e/tests/project/delete-restore.spec.ts new file mode 100644 index 00000000..69629d03 --- /dev/null +++ b/apps/web/e2e/tests/project/delete-restore.spec.ts @@ -0,0 +1,45 @@ +import { expect, test } from '../../fixtures' +import { fileCard } from '../../helpers/files' + +test('owner deletes a file, finds it in recently deleted, and restores it', async ({ + file, + prisma, +}) => { + const { page, projectId, fileName, fileId } = file + + await page.goto(`/projects/${projectId}`) + await expect(fileCard(page, fileName)).toBeVisible() + + // Delete through the context menu + confirmation dialog + await fileCard(page, fileName).click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Delete' }).click() + + const deleteDialog = page.getByRole('alertdialog') + await expect(deleteDialog.getByText('Delete Asset?')).toBeVisible() + await deleteDialog.getByRole('button', { name: 'Delete' }).click() + + await expect(fileCard(page, fileName)).not.toBeVisible() + + let asset = await prisma.asset.findUnique({ where: { id: fileId } }) + expect(asset?.isDeleted).toBe(true) + expect(asset?.deletedAt).not.toBeNull() + + // Navigate to the Recently Deleted view + await page.getByText('Recently Deleted').click() + await expect(page).toHaveURL(/\/recently-deleted/) + await expect(fileCard(page, fileName)).toBeVisible() + + // Restore through the context menu + await fileCard(page, fileName).click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Restore' }).click() + + await expect(fileCard(page, fileName)).not.toBeVisible() + + asset = await prisma.asset.findUnique({ where: { id: fileId } }) + expect(asset?.isDeleted).toBe(false) + expect(asset?.deletedAt).toBeNull() + + // Back at the project root the file is visible again + await page.goto(`/projects/${projectId}`) + await expect(fileCard(page, fileName)).toBeVisible() +}) diff --git a/apps/web/e2e/tests/project/share-password.spec.ts b/apps/web/e2e/tests/project/share-password.spec.ts new file mode 100644 index 00000000..ca30231b --- /dev/null +++ b/apps/web/e2e/tests/project/share-password.spec.ts @@ -0,0 +1,51 @@ +import { expect, test } from '../../fixtures' +import { apiAddAssetsToShare, apiCreateShare, fileCard } from '../../helpers/files' + +test('owner protects a share with a password and guests must enter it to view', async ({ + file, + browser, + prisma, +}) => { + const { context, page, projectId, fileName, fileId } = file + + // Seed the share with the file through the API (setup, not the flow under test) + const share = await apiCreateShare(context.request, projectId, 'Shared Doc') + await apiAddAssetsToShare(context.request, share.id, [fileId]) + + await page.goto(`/projects/${projectId}/shares/${share.id}`) + await expect(fileCard(page, fileName)).toBeVisible() + + // Open the Security accordion and enable a password + await page.getByRole('button', { name: 'Security' }).click() + const passwordRow = page.getByText('Password').locator('..') + await passwordRow.getByRole('switch').click() + + const passwordInput = page.getByPlaceholder('Enter password') + await expect(passwordInput).toBeVisible() + await passwordInput.fill('secret123') + await page.getByRole('button', { name: 'Save' }).click() + await expect(page.getByText('Settings updated')).toBeVisible() + + const saved = await prisma.shareLink.findUnique({ where: { id: share.id } }) + expect(saved?.password).toBe('secret123') + + // A guest visiting the public link hits the password gate + const guestContext = await browser.newContext() + const guestPage = await guestContext.newPage() + try { + await guestPage.goto(`/share/${share.id}`) + await expect(guestPage.getByText('Password Protected')).toBeVisible() + + // Wrong password keeps the gate open with an error + await guestPage.getByPlaceholder('Enter password').fill('wrong-password') + await guestPage.getByRole('button', { name: 'Access Share' }).click() + await expect(guestPage.getByText('Incorrect password. Please try again.')).toBeVisible() + + // Correct password grants access to the shared file + await guestPage.getByPlaceholder('Enter password').fill('secret123') + await guestPage.getByRole('button', { name: 'Access Share' }).click() + await expect(fileCard(guestPage, fileName)).toBeVisible() + } finally { + await guestContext.close() + } +}) diff --git a/apps/web/e2e/tests/project/upload-file.spec.ts b/apps/web/e2e/tests/project/upload-file.spec.ts new file mode 100644 index 00000000..63ec0bd4 --- /dev/null +++ b/apps/web/e2e/tests/project/upload-file.spec.ts @@ -0,0 +1,49 @@ +import { expect, test } from '../../fixtures' +import { fileCard } from '../../helpers/files' + +test('owner uploads a file via the "Upload File" context menu action', async ({ + project, + prisma, +}) => { + const { page, projectId } = project + const fileName = `e2e-upload-${Date.now()}.png` + // 5x5 PNG (uploading an image avoids the slow txt->pdf transcode path) + const pngBase64 = + 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAEElEQVR4nGNgmHkGBVHIBwBfNyLesMZaCgAAAABJRU5ErkJggg==' + + await page.goto(`/projects/${projectId}`) + await expect(page.getByText('This folder is empty')).toBeVisible() + + // Open the empty-area context menu and trigger the file picker + await page.getByText('This folder is empty').click({ button: 'right' }) + const [fileChooser] = await Promise.all([ + page.waitForEvent('filechooser'), + page.getByRole('menuitem', { name: 'Upload File' }).click(), + ]) + await fileChooser.setFiles({ + name: fileName, + mimeType: 'image/png', + buffer: Buffer.from(pngBase64, 'base64'), + }) + + // The file card appears immediately (optimistic) and then gets processed + await expect(fileCard(page, fileName)).toBeVisible() + await expect + .poll( + async () => { + const asset = await prisma.asset.findFirst({ where: { name: fileName } }) + return asset?.status + }, + { timeout: 30_000 }, + ) + .toBe('processed') + + // DB: the file is stored in the project root folder + const asset = await prisma.asset.findFirst({ where: { name: fileName } }) + expect(asset).not.toBeNull() + expect(asset!.type).toBe('file') + expect(asset!.projectId).toBe(projectId) + + const projectRow = await prisma.project.findUnique({ where: { id: projectId } }) + expect(asset!.parentId).toBe(projectRow?.rootFolderId) +}) diff --git a/apps/web/e2e/tests/auth/invite-member.spec.ts b/apps/web/e2e/tests/team/invite-member.spec.ts similarity index 100% rename from apps/web/e2e/tests/auth/invite-member.spec.ts rename to apps/web/e2e/tests/team/invite-member.spec.ts diff --git a/apps/web/e2e/tests/team/remove-member.spec.ts b/apps/web/e2e/tests/team/remove-member.spec.ts new file mode 100644 index 00000000..b5352dee --- /dev/null +++ b/apps/web/e2e/tests/team/remove-member.spec.ts @@ -0,0 +1,38 @@ +import { expect, test } from '../../fixtures' +import { openMembersDialog } from '../../helpers/ui' +import { seedTeamMember } from '../../helpers/team' + +test('owner removes a member via the members dialog and the membership is deleted', async ({ + owner, + prisma, +}) => { + const { page, teamId } = owner + const member = await seedTeamMember(prisma, teamId, 'reviewer') + + // Reload so the members dialog fetches the newly seeded member + await page.reload() + const dialog = await openMembersDialog(page) + + const memberRow = dialog + .locator('div.flex.items-center.justify-between') + .filter({ hasText: member.email }) + await expect(memberRow).toBeVisible() + + // The last button in the row is the remove (trash) button + await memberRow.getByRole('button').last().click() + + const removeDialog = page.getByRole('alertdialog') + await expect(removeDialog).toBeVisible() + await expect(removeDialog.getByRole('heading', { name: 'Remove Member' })).toBeVisible() + await removeDialog.getByRole('button', { name: 'Remove' }).click() + + // The member row disappears from the dialog + await expect(memberRow).not.toBeVisible() + + // DB: the owner is the only remaining team member, but the user still exists + const remainingMembers = await prisma.teamMember.count({ where: { teamId } }) + expect(remainingMembers).toBe(1) + + const user = await prisma.user.findUnique({ where: { id: member.userId } }) + expect(user).not.toBeNull() +}) diff --git a/packages/webui/components/folder-tree.tsx b/packages/webui/components/folder-tree.tsx index daf5df59..72143037 100644 --- a/packages/webui/components/folder-tree.tsx +++ b/packages/webui/components/folder-tree.tsx @@ -560,6 +560,7 @@ export function FolderTree({ {canEdit && (