import { mkdirSync } from 'node:fs'; import { resolve } from 'node:path'; import { expect, type Page, type Route, test } from '@playwright/test'; const DEFAULT_SCREENSHOT_DIR = process.env.PLAYWRIGHT_SCREENSHOT_DIR || '../../.codex/tmp/playwright-screenshots'; interface MockUserOptions { email: string; name: string; role?: string; sessionId: string; userId: string; } export function makeMockUser({ email, name, role = 'user', sessionId, userId }: MockUserOptions) { const timestamp = '2026-05-19T00:00:00Z'; return { user: { id: userId, email, name, image: null, role, status: 'active', emailVerified: true, createdAt: timestamp, updatedAt: timestamp, }, session: { id: sessionId, userId, expiresAt: new Date(Date.now() + 86_400_000).toISOString(), token: 'mock-token', createdAt: timestamp, updatedAt: timestamp, }, }; } /** `iPhone SE (375x667)` -> `iphone-se-375x667`. */ function slugifyProjectName(projectName: string): string { return projectName .replace(/[^a-zA-Z0-9]+/g, '-') .replace(/^-+|-+$/g, '') .toLowerCase(); } /** * `scopeToProject` prefixes the Playwright project name. * * The `-{width}x{height}` suffix alone does NOT make a filename unique: a * `test.use`-pinned describe renders at the same size under every project, so * running one spec on two projects has them overwrite each other's captures and * a screenshot review silently inspects only whichever ran last. Opt-in rather * than automatic, because the existing audit specs' filenames are referenced * from PR evidence. */ export async function screenshot( page: Page, name: string, options: { scopeToProject?: boolean } = {} ) { await page.waitForTimeout(600); const viewport = page.viewportSize(); const suffix = viewport ? `-${viewport.width}x${viewport.height}` : ''; const prefix = options.scopeToProject ? `${slugifyProjectName(test.info().project.name)}-` : ''; const screenshotDir = resolve(process.cwd(), DEFAULT_SCREENSHOT_DIR); mkdirSync(screenshotDir, { recursive: true }); await page.screenshot({ path: `${screenshotDir}/${prefix}${name}${suffix}.png`, fullPage: true, }); } type MutableCapacityCandidate = { id: string; status: string; capacitySourceId?: string; provider?: string | null; location?: string | null; providerInstanceType?: string | null; providerInstanceSku?: string | null; [key: string]: unknown; }; type MutableCapacitySummary = { pool: { id: string; strategy: string; exhaustionPolicy: string; maxNodes?: number; sourceOrder?: string[] | null; excludedSourceIds?: string[]; revision: number; }; candidates: MutableCapacityCandidate[]; activeCandidateCount: number; }; type MutableCapacityDefaultsResponse = { effective: MutableCapacitySummary | null; defaults: { summary: MutableCapacitySummary | null }[]; }; export type MockCapacityDefaultsUpdate = { policy?: { strategy?: string; exhaustionPolicy?: string; maxNodes?: number }; candidates?: MutableCapacityCandidate[]; catalogAdditions?: Array<{ sourceId: string; provider: string; location: string; providerInstanceType: string; providerInstanceSku?: string | null; }>; sourceOrder?: string[] | null; excludedSourceIds?: string[] | null; }; export function applyMockCapacityDefaultsUpdate( current: T, update: MockCapacityDefaultsUpdate ): T { const next = JSON.parse(JSON.stringify(current)) as T; const summary = next.effective; if (!summary) return next; if (update.policy?.strategy) summary.pool.strategy = update.policy.strategy; if (update.policy?.exhaustionPolicy) { summary.pool.exhaustionPolicy = update.policy.exhaustionPolicy; } if (update.policy?.maxNodes) summary.pool.maxNodes = update.policy.maxNodes; if (update.sourceOrder !== undefined) summary.pool.sourceOrder = update.sourceOrder; if (update.excludedSourceIds !== undefined) { summary.pool.excludedSourceIds = update.excludedSourceIds ?? []; } for (const candidateUpdate of update.candidates ?? []) { const candidate = summary.candidates.find((item) => item.id === candidateUpdate.id); if (candidate) candidate.status = candidateUpdate.status; } for (const addition of update.catalogAdditions ?? []) { const candidate = summary.candidates.find( (item) => item.capacitySourceId === addition.sourceId && item.provider === addition.provider && item.location === addition.location && item.providerInstanceType === addition.providerInstanceType && (item.providerInstanceSku ?? null) === (addition.providerInstanceSku ?? null) ); if (candidate) { candidate.status = 'active'; continue; } summary.candidates.push({ id: `mock-catalog-addition:${addition.sourceId}:${addition.provider}:${addition.location}:${addition.providerInstanceSku ?? addition.providerInstanceType}`, status: 'active', capacitySourceId: addition.sourceId, provider: addition.provider, location: addition.location, providerInstanceType: addition.providerInstanceType, providerInstanceSku: addition.providerInstanceSku ?? null, workloadRole: 'workspace', runtime: 'vm', machineClass: 'shared-vm', machineSize: null, priority: summary.candidates.length, candidateOrder: summary.candidates.length, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }); } // Like the server (default-capacity-pool-source-settings.ts): activating a machine switches its // account back on, so the mock cannot diverge from what a real save returns. const activatedSources = new Set([ ...(update.catalogAdditions ?? []).map((addition) => addition.sourceId), ...(update.candidates ?? []) .filter((candidateUpdate) => candidateUpdate.status === 'active') .flatMap((candidateUpdate) => { const candidate = summary.candidates.find((item) => item.id === candidateUpdate.id); return candidate?.capacitySourceId ? [candidate.capacitySourceId] : []; }), ]); if (summary.pool.excludedSourceIds) { summary.pool.excludedSourceIds = summary.pool.excludedSourceIds.filter( (id) => !activatedSources.has(id) ); } summary.activeCandidateCount = summary.candidates.filter( (candidate) => candidate.status === 'active' ).length; summary.pool.revision += 1; for (const item of next.defaults) { if (item.summary?.pool.id === summary.pool.id) item.summary = summary; } return next; } export async function screenshotNearHeading( page: Page, heading: string, name: string, options: { outputDir?: string } = {} ) { await page.getByRole('heading', { name: heading }).scrollIntoViewIfNeeded(); await page.waitForTimeout(600); const viewport = page.viewportSize(); const suffix = viewport ? `-${viewport.width}x${viewport.height}` : ''; const screenshotDir = resolve(process.cwd(), options.outputDir ?? DEFAULT_SCREENSHOT_DIR); mkdirSync(screenshotDir, { recursive: true }); await page.screenshot({ path: `${screenshotDir}/${name}${suffix}.png`, fullPage: false, }); } export async function screenshotSectionNearHeading( page: Page, heading: string, name: string, options: { outputDir?: string } = {} ) { const headingLocator = page.getByRole('heading', { name: heading }).first(); await headingLocator.scrollIntoViewIfNeeded(); await page.waitForTimeout(600); const viewport = page.viewportSize(); const suffix = viewport ? `-${viewport.width}x${viewport.height}` : ''; const screenshotDir = resolve(process.cwd(), options.outputDir ?? DEFAULT_SCREENSHOT_DIR); mkdirSync(screenshotDir, { recursive: true }); const section = headingLocator.locator('xpath=ancestor::section[1]').first(); const target = (await section.count()) > 0 ? section : headingLocator; await target.screenshot({ path: `${screenshotDir}/${name}${suffix}.png`, }); } export async function assertNoOverflow(page: Page) { const overflow = await page.evaluate( () => document.documentElement.scrollWidth > window.innerWidth ); expect(overflow).toBe(false); // Advisory here, blocking via `assertNoClippedOverflow` — see the rollout note // on `findClippedOverflow` below. await reportClippedOverflow(page); } /** * Detects horizontal overflow that `assertNoOverflow`'s document-level check * CANNOT see. * * AppShell puts `overflow-x-hidden` on `
` (AppShell.tsx) and `Project.tsx` * repeats it on its page wrapper. Anything wider than the viewport inside those * is therefore *clipped* — `document.documentElement.scrollWidth` never grows, * so the document-level assertion passes while the user sees content sheared off * at the right edge with no way to scroll to it. * * That false-pass shipped the Triggers mobile bug: the page root rendered 768px * wide inside a 375px viewport (`mx-auto` on a column-flex child disables * `align-items: stretch`, `min-width: auto` then floors the width at the * subtree's min-content, and Tailwind `truncate` makes a heading's min-content * its FULL untruncated string) while 25 `assertNoOverflow` assertions stayed * green. * * The signal is an element that *clips* horizontally (`overflow-x` resolved to * `hidden` or `clip`) whose content is wider than its box. Deliberate clipping * is excluded: * - `text-overflow: ellipsis` (Tailwind `truncate`) — the ellipsis IS the design * - `overflow-x: auto | scroll` — the user can scroll to the rest * - sub-4px boxes — `sr-only` clipping helpers * - `data-intentional-clip` — an explicit, self-documenting opt-out for * carousels and sliding panels (see `NavSidebar.tsx`), which are legitimately * wider than their viewport. Declaring it beats a silent blind spot. * - `` / `