diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 146104a9..62f134a4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -102,7 +102,7 @@ npm run typecheck ### Browser E2E tests -Browser tests live in `playwright/`, separate from the existing Vitest/JSDOM tests under `test/`. The Playwright setup runs one Chromium smoke test against the real local Node server and uses a synthetic signed-out session response; it does not sign in to GitHub or call a real LLM provider. +Browser tests live in `playwright/`, separate from the existing Vitest/JSDOM tests under `test/`. The Playwright suite runs Chromium against the real local Node server. It covers the signed-out landing page, a synthetic GitHub OAuth callback and session, dashboard KPIs/time range/recent jobs, job search/status/pagination, job progress/findings/diffs, repository toggles/model settings, stats charts, and theme persistence. Dashboard API data is mocked in the browser so these flows do not depend on real GitHub or LLM provider credentials. Requirements: Node.js 24+, Docker, and disposable local PostgreSQL and Redis services. @@ -126,7 +126,7 @@ npm run test:e2e docker rm -f codra-e2e-postgres codra-e2e-redis 2>/dev/null || true ``` -`npm run test:e2e` builds the Node server and dashboard, then Playwright starts the Node server on `http://localhost:3000` automatically. The launcher reads `.env.e2e`, generates a throwaway GitHub App private key for server initialization, disables the background review worker and telemetry, and never needs real GitHub, OAuth, or LLM credentials. The smoke test stubs only `GET /api/auth/session` as signed out. No database migration or seeded application data is needed for this first smoke test; keep `DATABASE_URL` pointed at the disposable database above. +`npm run test:e2e` builds the Node server and dashboard, then Playwright starts the Node server on `http://localhost:3000` automatically. The launcher reads `.env.e2e`, generates a throwaway GitHub App private key for server initialization, disables the background review worker and telemetry, and enables a synthetic identity provider only when the launcher sets `CODRA_E2E_AUTH_ENABLED=true` and the Node server is running with `NODE_ENV=test` and `ENVIRONMENT=test`. The OAuth state validation, callback handler, session store, and protected page routes remain real; no GitHub credentials are used. Browser API fixtures provide deterministic jobs, repositories, model configuration, stats, and diff responses. Keep `DATABASE_URL` and `REDIS_URL` pointed at the disposable services above; Redis is used for the OAuth state and session store, while the callback's account-settings write is best-effort. The browser output is written to `test-results/` and `playwright-report/`; both are gitignored. To inspect the HTML report after a run, use `npx playwright show-report`. @@ -137,6 +137,7 @@ The browser output is written to `test-results/` and `playwright-report/`; both All documentation content for [codra.run/docs](https://codra.run/docs) lives in `docs/*.mdx` in this repository. Even though the website repo is private, **all documentation is 100% open source** and deploys automatically when PRs are merged into `main`. ### MDX Guidelines + - **Files & Routes**: Each file in `docs/*.mdx` maps directly to a route (e.g. `docs/docker.mdx` -> `codra.run/docs/docker`). - **Headings with IDs**: Use explicit HTML `

Heading

` for major sections to ensure working anchor links and sidebar navigation. Use standard markdown `###` for subheadings. - **Callouts**: Use ``, ``, or `` (standard blockquotes `> ` also render as info callouts). diff --git a/apps/node/src/e2e-identity-provider.ts b/apps/node/src/e2e-identity-provider.ts new file mode 100644 index 00000000..a0011b05 --- /dev/null +++ b/apps/node/src/e2e-identity-provider.ts @@ -0,0 +1,47 @@ +import type { + DashboardSessionUser, + IdentityProvider, +} from "@codraoss/core/ports"; + +/** + * Synthetic identity provider used only by the disposable Playwright server. + * It exercises the real OAuth state/callback/session path without contacting + * GitHub or requiring user credentials. + */ +export class E2EIdentityProvider implements IdentityProvider { + private readonly identity: DashboardSessionUser = { + provider: "github", + providerUserId: "90000001", + login: "codra-e2e", + name: "Codra E2E User", + avatarUrl: null, + email: "codra-e2e@example.invalid", + signedInAt: "2026-01-01T00:00:00.000Z", + metadata: { + githubUserId: 90000001, + githubUsername: "codra-e2e", + }, + }; + + async beginAuthorization( + redirectUri: string, + state: string, + ): Promise<{ url: string }> { + const url = new URL("https://codra-e2e.invalid/authorize"); + url.searchParams.set("redirect_uri", redirectUri); + url.searchParams.set("state", state); + return { url: url.toString() }; + } + + async completeAuthorization( + code: string, + state: string, + expectedState: string, + ): Promise<{ identity: DashboardSessionUser }> { + if (code !== "codra-e2e-code" || state !== expectedState) { + throw new Error("Invalid synthetic E2E authorization callback."); + } + + return { identity: { ...this.identity } }; + } +} diff --git a/apps/node/src/index.ts b/apps/node/src/index.ts index b061e47d..07c82cc4 100644 --- a/apps/node/src/index.ts +++ b/apps/node/src/index.ts @@ -56,6 +56,16 @@ const stubs = { }; const env: NodeAppBindings = createNodeEnv(stubs); +// This switch is set only by scripts/start-e2e-server.mjs for the disposable +// E2E environment. Never enable the synthetic identity provider in production. +if ( + process.env.CODRA_E2E_AUTH_ENABLED === "true" && + process.env.NODE_ENV === "test" && + env.ENVIRONMENT === "test" +) { + const { E2EIdentityProvider } = await import("./e2e-identity-provider"); + env.IDENTITY_PROVIDER = new E2EIdentityProvider(); +} env.REVIEW_ORCHESTRATOR = new NodeOrchestrator( createReviewRuntime(env), stubs.REVIEW_QUEUE, @@ -141,17 +151,29 @@ if (process.env.START_API !== "false") { } // Model registry refresh in background (zero DB impact, unreferenced interval) -import("@codraoss/models").then(({ ModelRegistryService }) => { - const service = ModelRegistryService.getInstance(); - service.refreshFromRemote().catch(() => {}); - const timer = setInterval(() => service.refreshFromRemote().catch(() => {}), 60 * 60 * 1000); - (timer as unknown as { unref?: () => void }).unref?.(); -}).catch(() => {}); - -const withTimeout = async (promise: Promise, timeoutMs: number, label: string): Promise => { +import("@codraoss/models") + .then(({ ModelRegistryService }) => { + const service = ModelRegistryService.getInstance(); + service.refreshFromRemote().catch(() => {}); + const timer = setInterval( + () => service.refreshFromRemote().catch(() => {}), + 60 * 60 * 1000, + ); + (timer as unknown as { unref?: () => void }).unref?.(); + }) + .catch(() => {}); + +const withTimeout = async ( + promise: Promise, + timeoutMs: number, + label: string, +): Promise => { let timer: NodeJS.Timeout | undefined; const timeoutPromise = new Promise((_, reject) => { - timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs); + timer = setTimeout( + () => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), + timeoutMs, + ); timer.unref?.(); }); try { @@ -176,7 +198,9 @@ const shutdown = async (signal?: string) => { shutdownStartTime = now; const globalShutdownTimeout = setTimeout(() => { - logger.error("Global shutdown timed out after 10000ms. Forcing immediate exit."); + logger.error( + "Global shutdown timed out after 10000ms. Forcing immediate exit.", + ); process.exit(1); }, 10000); globalShutdownTimeout.unref?.(); @@ -201,12 +225,16 @@ const shutdown = async (signal?: string) => { }; const drainTimer = setTimeout(() => { - (server as unknown as { closeAllConnections?: () => void })?.closeAllConnections?.(); + ( + server as unknown as { closeAllConnections?: () => void } + )?.closeAllConnections?.(); }, 3000); drainTimer.unref?.(); const hardTimer = setTimeout(() => { - finish(new Error("HTTP server listener close timed out after 5000ms")); + finish( + new Error("HTTP server listener close timed out after 5000ms"), + ); }, 5000); hardTimer.unref?.(); diff --git a/playwright/dashboard-flows.spec.ts b/playwright/dashboard-flows.spec.ts new file mode 100644 index 00000000..a5c50721 --- /dev/null +++ b/playwright/dashboard-flows.spec.ts @@ -0,0 +1,499 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; +import { + detailJob, + detailJobId, + globalModelFixture, + jobDiffFixture, + jobSummaries, + modelsFixture, + repoFixture, + statsFixture, +} from "./fixtures"; + +const e2eCode = "codra-e2e-code"; + +async function fulfillJson( + route: Route, + body: unknown, + headers?: Record, + status = 200, +) { + await route.fulfill({ + status, + contentType: "application/json", + headers, + body: JSON.stringify(body), + }); +} + +async function installApiMocks(page: Page) { + const repo = structuredClone(repoFixture); + + await page.route("**/api/**", async (route) => { + const request = route.request(); + const url = new URL(request.url()); + const { pathname, searchParams } = url; + + // Keep session lookup real: it verifies the cookie created by the OAuth callback. + if (pathname === "/api/auth/session") { + await route.continue(); + return; + } + + if (pathname === "/api/jobs" && request.method() === "GET") { + let jobs = [...jobSummaries]; + const search = searchParams.get("search")?.toLowerCase(); + const status = searchParams.get("status"); + + if (search) { + jobs = jobs.filter((job) => + `${job.prTitle ?? ""} ${job.owner}/${job.repo} #${job.prNumber}` + .toLowerCase() + .includes(search), + ); + } + + if (status) { + jobs = jobs.filter((job) => job.status === status); + } + + const total = jobs.length; + const offset = Number(searchParams.get("offset") ?? 0); + const limit = Number(searchParams.get("limit") ?? 20); + + await fulfillJson(route, { + jobs: jobs.slice(offset, offset + limit), + total, + }); + return; + } + + if (pathname === `/api/jobs/${detailJobId}` && request.method() === "GET") { + await fulfillJson(route, { job: detailJob }, { etag: '"codra-e2e-job"' }); + return; + } + + if ( + pathname === `/api/jobs/${detailJobId}/diffs` && + request.method() === "GET" + ) { + await fulfillJson(route, jobDiffFixture); + return; + } + + if (pathname === "/api/stats" && request.method() === "GET") { + await fulfillJson(route, { stats: statsFixture }); + return; + } + + if (pathname === "/api/auth/updates-email" && request.method() === "GET") { + await fulfillJson(route, { + status: "subscribed", + email: "codra-e2e@example.invalid", + updatedAt: "2026-11-18T10:00:00.000Z", + }); + return; + } + + if (pathname === "/api/repos" && request.method() === "GET") { + await fulfillJson(route, { repos: [repo] }); + return; + } + + if (pathname === "/api/models" && request.method() === "GET") { + await fulfillJson(route, modelsFixture); + return; + } + + if (pathname === "/api/models/global" && request.method() === "GET") { + await fulfillJson(route, globalModelFixture); + return; + } + + if ( + pathname === `/api/repos/${repo.owner}/${repo.repo}/config` && + request.method() === "PATCH" + ) { + const payload = request.postDataJSON() as { + enabled?: boolean; + model?: { main?: string | null }; + }; + + if (payload.enabled !== undefined) { + repo.enabled = payload.enabled; + } + + if (payload.model?.main !== undefined) { + repo.mainModel = payload.model.main; + } + + await fulfillJson(route, { ok: true }); + return; + } + + // Fail closed for unexpected API traffic so tests never leak into a real backend. + await fulfillJson( + route, + { error: `Unmocked E2E endpoint: ${request.method()} ${pathname}` }, + undefined, + 501, + ); + }); +} + +async function signInThroughSyntheticOAuth(page: Page) { + const authStart = await page.request.get( + new URL("/auth/github", page.url()).toString(), + { maxRedirects: 0 }, + ); + + expect(authStart.status()).toBe(302); + + const authorizationUrl = authStart.headers().location; + expect(authorizationUrl).toBeTruthy(); + + const state = new URL(authorizationUrl!).searchParams.get("state"); + expect(state).toBeTruthy(); + + await page.goto( + `/auth/github/callback?code=${e2eCode}&state=${encodeURIComponent(state!)}`, + ); + + await expect(page).toHaveURL(/\/dashboard$/); + await expect( + page.getByRole("link", { name: "Codra dashboard" }), + ).toBeVisible(); +} + +async function openAuthenticatedPage(page: Page, path: string) { + await installApiMocks(page); + await page.goto("/"); + await signInThroughSyntheticOAuth(page); + await page.goto(path); +} + +test.describe("Codra browser flows", () => { + test("landing page and synthetic GitHub OAuth callback reach the dashboard", async ({ + page, + }) => { + await installApiMocks(page); + await page.goto("/"); + + await expect( + page.getByRole("heading", { name: "Sign in to Codra" }), + ).toBeVisible(); + + await expect( + page.getByRole("link", { name: "Continue with GitHub" }), + ).toHaveAttribute("href", "/auth/github"); + + await signInThroughSyntheticOAuth(page); + + const sessionResponse = await page.request.get( + new URL("/api/auth/session", page.url()).toString(), + ); + + expect(sessionResponse.status()).toBe(200); + expect((await sessionResponse.json()).user.login).toBe("codra-e2e"); + }); + + test("dashboard overview displays KPIs and recent reviews and changes its time range", async ({ + page, + }) => { + await openAuthenticatedPage(page, "/dashboard"); + + await expect( + page.getByRole("heading", { name: "Dashboard" }), + ).toBeVisible(); + + await expect(page.getByText("Total reviews")).toBeVisible(); + await expect(page.getByText("Input tokens")).toBeVisible(); + await expect(page.getByText("Output tokens")).toBeVisible(); + await expect(page.getByText("Comments posted")).toBeVisible(); + + await expect( + page.getByRole("heading", { name: "Recent reviews" }), + ).toBeVisible(); + + await expect( + page.getByRole("link", { name: "Harden dashboard authorization" }), + ).toBeVisible(); + + const selectedRangeRequest = page.waitForRequest((request) => { + const requestUrl = new URL(request.url()); + + return ( + requestUrl.pathname === "/api/stats" && + requestUrl.searchParams.get("days") === "30" + ); + }); + + await page.getByRole("button", { name: "Last 14 days" }).click(); + await page.getByRole("option", { name: "Last 30 days" }).click(); + + await selectedRangeRequest; + }); + + test("jobs can be searched, filtered by status, and paginated", async ({ + page, + }) => { + await openAuthenticatedPage(page, "/jobs"); + + await expect(page.getByRole("heading", { name: "Jobs" })).toBeVisible(); + + const search = page.getByRole("textbox", { + name: "Search jobs by title or number", + }); + + const searchRequest = page.waitForRequest((request) => { + const requestUrl = new URL(request.url()); + + return ( + requestUrl.pathname === "/api/jobs" && + requestUrl.searchParams.get("search") === + "Harden dashboard authorization" + ); + }); + + await search.fill("Harden dashboard authorization"); + await searchRequest; + + await expect( + page.getByRole("link", { name: "Harden dashboard authorization" }), + ).toBeVisible(); + + await expect( + page.getByRole("link", { name: "Update dashboard module 2" }), + ).toHaveCount(0); + + const clearedSearchRequest = page.waitForRequest((request) => { + const requestUrl = new URL(request.url()); + + return ( + requestUrl.pathname === "/api/jobs" && + !requestUrl.searchParams.has("search") + ); + }); + + await search.fill(""); + await clearedSearchRequest; + + await page.getByRole("button", { name: "All statuses" }).click(); + await page.getByRole("option", { name: "Failed" }).click(); + + await expect( + page.getByRole("link", { name: "Update dashboard module 3" }), + ).toBeVisible(); + + await expect( + page.getByRole("link", { name: "Update dashboard module 2" }), + ).toHaveCount(0); + + const allStatusesRequest = page.waitForRequest((request) => { + const requestUrl = new URL(request.url()); + + return ( + requestUrl.pathname === "/api/jobs" && + !requestUrl.searchParams.has("status") && + !requestUrl.searchParams.has("search") + ); + }); + + await page.getByRole("button", { name: "Failed" }).click(); + await page.getByRole("option", { name: "All statuses" }).click(); + + await allStatusesRequest; + + const nextPageRequest = page.waitForRequest((request) => { + const requestUrl = new URL(request.url()); + + return ( + requestUrl.pathname === "/api/jobs" && + requestUrl.searchParams.get("offset") === "10" + ); + }); + + await page.getByRole("button", { name: "Next page" }).click(); + await nextPageRequest; + + await expect(page.getByText("2 / 2")).toBeVisible(); + + await expect( + page.getByRole("link", { name: "Update dashboard module 11" }), + ).toBeVisible(); + + // Navigate back to the first page. + const previousPageRequest = page.waitForRequest((request) => { + const requestUrl = new URL(request.url()); + + return ( + requestUrl.pathname === "/api/jobs" && + requestUrl.searchParams.get("offset") === "0" + ); + }); + + await page.getByRole("button", { name: "Previous page" }).click(); + await previousPageRequest; + + await expect(page.getByText("1 / 2")).toBeVisible(); + + await expect( + page.getByRole("link", { name: "Update dashboard module 1" }), + ).toBeVisible(); + }); + + test("job detail shows progress, findings, and the changed-file diff viewer", async ({ + page, + }) => { + await openAuthenticatedPage(page, `/jobs/${detailJobId}`); + + await expect( + page.getByRole("heading", { name: "Add account menu protections" }), + ).toBeVisible(); + + await expect(page.getByText("Progress steps")).toBeVisible(); + await expect(page.getByText("Fetch pull request")).toBeVisible(); + await expect(page.getByText("Review changed files")).toBeVisible(); + + await expect(page.getByRole("heading", { name: "Findings" })).toBeVisible(); + + await page.getByText("src/components/AccountMenu.tsx").first().click(); + + await expect(page.getByText("Inline comments (1)")).toBeVisible(); + + await expect( + page.getByText("Check authorization before opening the menu"), + ).toBeVisible(); + + await page.getByRole("tab", { name: "Severity" }).click(); + + // Scope the severity assertion to the finding article to avoid matching + // the same P1 label in other UI elements such as filters. + await expect( + page.getByRole("article").getByText("P1", { exact: true }).first(), + ).toBeVisible(); + + await page.getByRole("tab", { name: "Files", exact: true }).click(); + + await page.getByRole("tab", { name: "Files changed" }).click(); + + await expect(page.getByRole("heading", { name: "Files" })).toBeVisible(); + + await expect(page.getByText("if (!canOpen) return null;")).toBeVisible(); + }); + + test("repository review can be paused and its model strategy can be updated", async ({ + page, + }) => { + await openAuthenticatedPage(page, "/repos"); + + await expect( + page.getByRole("heading", { name: "Repositories" }), + ).toBeVisible(); + + await expect(page.getByText("acme/web-app")).toBeVisible(); + + // Scope to the application root to avoid matching the "Enabled" dropdown option. + await expect( + page.locator("#root").getByText("Enabled", { exact: true }).first(), + ).toBeVisible(); + + await page + .getByRole("switch", { name: "Pause reviews for acme/web-app" }) + .click(); + + await expect( + page.locator("#root").getByText("Paused", { exact: true }).first(), + ).toBeVisible(); + + await page.getByRole("button", { name: "Edit" }).click(); + + const dialog = page.getByRole("dialog"); + + await expect(dialog.getByText("Edit model strategy")).toBeVisible(); + await expect(dialog.getByText("acme/web-app")).toBeVisible(); + await expect(dialog.getByText("Provider")).toBeVisible(); + await expect(dialog.getByText("Model", { exact: true })).toBeVisible(); + + // Select a different model from the configured test fixtures. + await dialog.getByRole("button", { name: /GPT-4o mini/ }).click(); + + // The Select options are rendered in a portal outside the dialog. + await page.getByRole("option", { name: "GPT-4.1 mini" }).click(); + + const updateResponse = page.waitForResponse((response) => { + return ( + response.request().method() === "PATCH" && + new URL(response.url()).pathname === "/api/repos/acme/web-app/config" + ); + }); + + const updateRequest = page.waitForRequest((request) => { + return ( + request.method() === "PATCH" && + new URL(request.url()).pathname === "/api/repos/acme/web-app/config" + ); + }); + + await dialog.getByRole("button", { name: "Apply" }).click(); + + const [request, response] = await Promise.all([ + updateRequest, + updateResponse, + ]); + + expect(response.status()).toBe(200); + + expect(request.postDataJSON()).toMatchObject({ + model: { + main: "gpt-4.1-mini", + }, + }); + }); + + test("stats charts render without browser errors", async ({ page }) => { + const pageErrors: string[] = []; + + page.on("pageerror", (error) => pageErrors.push(error.message)); + + await openAuthenticatedPage(page, "/stats"); + + await expect( + page.getByRole("heading", { name: "Review metrics" }), + ).toBeVisible(); + + await expect(page.getByText("Review Flow")).toBeVisible(); + await expect(page.getByText("Token Volume")).toBeVisible(); + + await expect(page.locator("svg.recharts-surface").first()).toBeVisible(); + await expect(page.locator(".recharts-area-area")).toHaveCount(2); + await expect(page.locator(".recharts-bar-rectangle").first()).toBeVisible(); + + expect(pageErrors).toEqual([]); + }); + + test("theme preference persists after reload", async ({ page }) => { + await openAuthenticatedPage(page, "/dashboard"); + + const root = page.locator("html"); + const originalTheme = await root.getAttribute("data-theme"); + + await page.getByRole("button", { name: "Toggle theme" }).first().click(); + + await expect + .poll(() => root.getAttribute("data-theme")) + .not.toBe(originalTheme); + + const selectedTheme = await root.getAttribute("data-theme"); + + expect(["light", "dark"]).toContain(selectedTheme); + + expect(await page.evaluate(() => localStorage.getItem("codra-theme"))).toBe( + selectedTheme, + ); + + await page.reload(); + + await expect(root).toHaveAttribute("data-theme", selectedTheme!); + }); +}); diff --git a/playwright/fixtures.ts b/playwright/fixtures.ts new file mode 100644 index 00000000..f906de84 --- /dev/null +++ b/playwright/fixtures.ts @@ -0,0 +1,283 @@ +import { + defaultRepoConfig, + type JobDetail, + type JobSummary, + type RepoConfigRecord, + type StatsPayload, +} from "@codraoss/schema"; + +const createdAt = "2026-11-18T10:00:00.000Z"; +const updatedAt = "2026-11-18T10:05:00.000Z"; + +export const detailJobId = "00000000-0000-4000-8000-000000000101"; + +export function makeJobSummary(index: number): JobSummary { + const number = index + 1; + return { + id: `00000000-0000-4000-8000-${String(200 + number).padStart(12, "0")}`, + owner: "acme", + repo: "web-app", + installationId: "1001", + prNumber: 100 + number, + prTitle: + number === 1 + ? "Harden dashboard authorization" + : `Update dashboard module ${number}`, + prAuthor: "octocat", + commitSha: "a1b2c3d4e5f6789012345678901234567890abcd", + trigger: "auto", + status: number % 3 === 0 ? "failed" : "done", + verdict: number % 3 === 0 ? "comment" : "approve", + fileCount: 2, + commentCount: number % 3 === 0 ? 1 : 0, + totalInputTokens: 1200 + number, + totalOutputTokens: 450 + number, + createdAt, + updatedAt, + nextRetryAt: null, + startedAt: createdAt, + finishedAt: updatedAt, + errorMessage: null, + overallConfidenceScore: 0.94, + overallCorrectness: "correct", + steps: [], + checkRunId: null, + configSnapshot: null, + retryOfJobId: null, + }; +} + +export const jobSummaries = Array.from({ length: 12 }, (_, index) => + makeJobSummary(index), +); + +export const detailJob: JobDetail = { + id: detailJobId, + owner: "acme", + repo: "web-app", + installationId: "1001", + prNumber: 142, + prTitle: "Add account menu protections", + prAuthor: "octocat", + commitSha: "d4c3b2a109876543210fedcba09876543210abcd", + trigger: "auto", + status: "done", + verdict: "comment", + fileCount: 1, + commentCount: 1, + totalInputTokens: 2400, + totalOutputTokens: 820, + createdAt, + updatedAt, + nextRetryAt: null, + startedAt: createdAt, + finishedAt: updatedAt, + errorMessage: null, + overallConfidenceScore: 0.96, + overallCorrectness: "correct", + steps: [ + { + name: "Fetch pull request", + status: "done", + startedAt: createdAt, + finishedAt: "2026-11-18T10:00:10.000Z", + error: null, + }, + { + name: "Review changed files", + status: "done", + startedAt: "2026-11-18T10:00:10.000Z", + finishedAt: updatedAt, + error: null, + }, + ], + baseSha: "1111111111111111111111111111111111111111", + headRef: "feature/account-menu", + baseRef: "main", + summaryMarkdown: "The review found one authorization issue worth addressing.", + configSnapshot: null, + reviewId: 501, + retryOfJobId: null, + summaryModel: "gpt-4o-mini", + files: [ + { + id: "00000000-0000-4000-8000-000000000301", + jobId: detailJobId, + filePath: "src/components/AccountMenu.tsx", + fileStatus: "done", + modelUsed: "gpt-4o-mini", + modelProvider: "OpenAI", + diffLineCount: 8, + diffInput: null, + rawAiOutput: null, + parsedComments: [ + { + path: "src/components/AccountMenu.tsx", + line: 18, + severity: "P1", + category: "security", + title: "Check authorization before opening the menu", + body: "The menu action should verify the current user's permissions before exposing account data.", + codeSuggestion: null, + confidenceScore: 0.96, + evidence: "setMenuOpen(true)", + fingerprint: "account-menu-auth-check", + anchorHash: "account-menu-line-18", + posted: true, + claimType: null, + contextSnippet: null, + disposition: null, + verifyReason: null, + humanLabel: null, + fingerprintV2: null, + source: "llm", + reviewerModel: null, + ruleId: null, + }, + ], + inputTokens: 1200, + outputTokens: 420, + durationMs: 1800, + verdict: "comment", + fileSummary: "The account menu is rendered after the permission check.", + overallCorrectness: "correct", + confidenceScore: 0.96, + batchSize: 1, + withheldCounts: null, + degraded: null, + errorMessage: null, + createdAt, + }, + ], +}; + +const trend = Array.from({ length: 14 }, (_, index) => { + const day = new Date(Date.UTC(2026, 10, index + 1)) + .toISOString() + .slice(0, 10); + + return { + day, + endDay: day, + jobs: index + 1, + inputTokens: (index + 1) * 100, + outputTokens: (index + 1) * 45, + comments: index % 3, + }; +}); + +export const statsFixture: StatsPayload = { + totals: { + jobs: 12, + inputTokens: 13500, + outputTokens: 6200, + comments: 7, + }, + trend, + trendBucketDays: 1, + verdicts: [ + { verdict: "approve", count: 8 }, + { verdict: "comment", count: 4 }, + ], + models: [ + { + modelUsed: "gpt-4o-mini", + provider: "OpenAI", + calls: 12, + inputTokens: 13500, + outputTokens: 6200, + }, + ], + topRepos: [{ owner: "acme", repo: "web-app", jobs: 12 }], + statuses: [ + { status: "done", count: 9 }, + { status: "failed", count: 3 }, + ], + triggers: [{ trigger: "auto", count: 12 }], + severities: [ + { severity: "P1", count: 2 }, + { severity: "P2", count: 5 }, + ], + categories: [ + { category: "security", count: 2 }, + { category: "quality", count: 5 }, + ], + performance: { + avgDurationMs: 1800, + p95DurationMs: 3200, + avgConfidence: 0.94, + }, +}; + +export const repoFixture: RepoConfigRecord = { + installationId: "1001", + owner: "acme", + repo: "web-app", + parsedJson: defaultRepoConfig, + updatedAt, + lastJobCreatedAt: updatedAt, + lastJobVerdict: "approve", + mainModel: null, + fallbackModels: null, + sizeOverrides: null, + enabled: true, +}; + +export const providerId = "00000000-0000-4000-8000-000000000401"; + +export const modelsFixture = { + providers: [ + { + id: providerId, + name: "OpenAI", + apiFormat: "openai" as const, + baseUrl: "https://api.openai.com/v1", + enabled: true, + hasApiKey: true, + createdAt, + updatedAt, + }, + ], + configs: [ + { + modelId: "gpt-4o-mini", + providerId, + providerName: "OpenAI", + apiFormat: "openai" as const, + modelName: "GPT-4o mini", + updatedAt, + }, + { + modelId: "gpt-4.1-mini", + providerId, + providerName: "OpenAI", + apiFormat: "openai" as const, + modelName: "GPT-4.1 mini", + updatedAt, + }, + ], +}; + +export const globalModelFixture = { + config: { + main: "gpt-4o-mini", + fallbacks: [], + size_overrides: [], + secondary: null, + }, +}; + +export const jobDiffFixture = { + diffs: { + "src/components/AccountMenu.tsx": [ + "diff --git a/src/components/AccountMenu.tsx b/src/components/AccountMenu.tsx", + "index 1111111..2222222 100644", + "--- a/src/components/AccountMenu.tsx", + "+++ b/src/components/AccountMenu.tsx", + "@@ -14,4 +14,6 @@ export function AccountMenu() {", + " const canOpen = permissions.includes('account.read');", + "+if (!canOpen) return null;", + "+setMenuOpen(true);", + ].join("\n"), + }, +}; diff --git a/scripts/start-e2e-server.mjs b/scripts/start-e2e-server.mjs index 4b2aed5e..3ad45e94 100644 --- a/scripts/start-e2e-server.mjs +++ b/scripts/start-e2e-server.mjs @@ -5,7 +5,10 @@ import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; -const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const rootDir = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "..", +); const envPath = path.join(rootDir, ".env.e2e"); const REQUIRED_KEYS = [ @@ -39,7 +42,12 @@ function loadE2eEnvironment() { try { source = readFileSync(envPath, "utf8"); } catch (error) { - if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") { + if ( + error && + typeof error === "object" && + "code" in error && + error.code === "ENOENT" + ) { throw new Error( "Missing .env.e2e. Copy .env.e2e.example to .env.e2e and start the disposable Postgres and Redis services first.", { cause: error }, @@ -58,7 +66,8 @@ function loadE2eEnvironment() { if (separator < 1) continue; const key = trimmed.slice(0, separator).trim(); - if (SENSITIVE_KEYS.has(key.toUpperCase()) || !ALLOWED_E2E_KEYS.has(key)) continue; + if (SENSITIVE_KEYS.has(key.toUpperCase()) || !ALLOWED_E2E_KEYS.has(key)) + continue; let value = trimmed.slice(separator + 1).trim(); if ( @@ -128,6 +137,7 @@ childEnv.START_API = "true"; childEnv.START_WORKER = "false"; childEnv.TELEMETRY_DISABLED = "true"; childEnv.NODE_ENV = "test"; +childEnv.CODRA_E2E_AUTH_ENABLED = "true"; // Spawn the built Node server entrypoint directly rather than through tsup --watch const serverEntry = path.join(rootDir, "apps", "node", "dist", "index.js"); @@ -147,13 +157,23 @@ const child = spawn(process.execPath, [serverEntry], { let stopping = false; let killed = false; function killChildTree(signal = "SIGTERM") { - if (killed || !child.pid || child.exitCode !== null || child.signalCode !== null) return; + if ( + killed || + !child.pid || + child.exitCode !== null || + child.signalCode !== null + ) + return; if (process.platform === "win32") { - const result = spawnSync("taskkill", ["/pid", String(child.pid), "/t", "/f"], { - stdio: "ignore", - windowsHide: true, - }); + const result = spawnSync( + "taskkill", + ["/pid", String(child.pid), "/t", "/f"], + { + stdio: "ignore", + windowsHide: true, + }, + ); if (result.error || result.status !== 0) child.kill(); killed = true; return; diff --git a/test/e2e/dashboard.spec.tsx b/test/e2e/dashboard.spec.tsx index a7d64d45..4b49ca73 100644 --- a/test/e2e/dashboard.spec.tsx +++ b/test/e2e/dashboard.spec.tsx @@ -1,8 +1,9 @@ /** * @vitest-environment jsdom */ +import { OverviewStats } from "@client/components/features/stats/overview-stats"; import { expect, it, describe, vi, beforeEach } from "vitest"; -import { render, screen } from "@testing-library/react"; +import { render, screen, waitFor } from "@testing-library/react"; import { LandingPage } from "@client/pages/landing"; import { DashboardPage } from "@client/pages/dashboard"; import { MemoryRouter } from "react-router-dom"; @@ -23,13 +24,21 @@ vi.mock("@client/lib/api", () => ({ describe("Frontend UI Flows (JSDOM)", () => { beforeEach(() => { + Object.defineProperty(document, "visibilityState", { + configurable: true, + value: "visible", + }); + vi.clearAllMocks(); + vi.mocked(api.getUpdatesEmailStatus).mockResolvedValue({ status: "subscribed", email: "user@example.com", updatedAt: new Date().toISOString(), }); + vi.mocked(api.getRepos).mockResolvedValue({ repos: [] }); + vi.mocked(api.getModelConfigs).mockResolvedValue({ providers: [], configs: [], @@ -50,7 +59,39 @@ describe("Frontend UI Flows (JSDOM)", () => { }); expect(signInLink.getAttribute("href")).toBe("/auth/github"); }); + it("renders overview stats when data is provided", () => { + const stats = { + totals: { + jobs: 10, + inputTokens: 500, + outputTokens: 250, + comments: 5, + }, + trend: [], + trendBucketDays: 1, + verdicts: [], + models: [], + topRepos: [], + statuses: [], + triggers: [], + severities: [], + categories: [], + performance: { + avgDurationMs: null, + p95DurationMs: null, + avgConfidence: null, + }, + }; + render( + + + , + ); + + expect(screen.getByText(/^(10|\u0661\u0660)$/)).toBeDefined(); + expect(screen.getByText(/^(500|\u0665\u0660\u0660)$/)).toBeDefined(); + }); it("displays the dashboard with stats and activity", async () => { vi.mocked(api.getStats).mockResolvedValue({ stats: { @@ -98,9 +139,13 @@ describe("Frontend UI Flows (JSDOM)", () => { expect(await screen.findByText("Dashboard")).toBeDefined(); - expect(screen.getByText("10")).toBeDefined(); - expect(screen.getByText("500")).toBeDefined(); + expect(api.getStats).toHaveBeenCalled(); + expect(api.getJobs).toHaveBeenCalled(); + await waitFor(() => { + expect(screen.getByText(/^(10|\u0661\u0660)$/)).toBeDefined(); + expect(screen.getByText(/^(500|\u0665\u0660\u0660)$/)).toBeDefined(); + }); // Rendered in both mobile and desktop layouts, hence getAllByText. expect(screen.getAllByText("test-owner/test-repo").length).toBeGreaterThan( 0,