Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ jobs:
- run: pnpm test
- run: pnpm --filter @gitwork/web exec playwright install --with-deps chromium
- run: pnpm test:e2e
- if: failure()
uses: actions/upload-artifact@v4
with:
name: playwright-results
path: apps/web/test-results/
retention-days: 7
# Builds and serves both runtimes; fails if libsql reaches the Worker bundle.
- run: pnpm smoke

Expand Down
432 changes: 432 additions & 0 deletions apps/web/e2e/keyboard.spec.ts

Large diffs are not rendered by default.

151 changes: 120 additions & 31 deletions apps/web/e2e/speed.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import { emailCount, signInCode } from "./outbox";

const TASKS = 2_000;
/** Script time for one view switch, measured in the page. Generous for CI machines; local runs are far lower. */
const SWITCH_BUDGET_MS = Number(process.env.SWITCH_BUDGET_MS ?? 400);
const SWITCH_BUDGET_MS = Number(process.env.SWITCH_BUDGET_MS ?? 150);
/** One J press on a 2,000-row list. Only two rows may re-render. */
const FOCUS_BUDGET_MS = Number(process.env.FOCUS_BUDGET_MS ?? 16);

async function signIn(page: Page, email: string) {
const before = emailCount(email);
Expand Down Expand Up @@ -102,15 +104,19 @@ let workspaceId = "";
test.describe.configure({ mode: "serial" });

test.beforeAll(async ({ browser }) => {
// Seeding plus sign-in can take longer than the default 30 s on a slow CI machine.
test.setTimeout(120_000);
// A clean context: test.use's storageState below does not exist yet.
const context = await browser.newContext({ storageState: { cookies: [], origins: [] } });
const page = await context.newPage();
await signIn(page, "speed-owner@example.com");
await page.getByLabel("Account name").fill("Speed Agency");
await page.getByLabel("First workspace").fill("Speed Board");
await page.getByRole("button", { name: "Create" }).click();
await expect(page.getByRole("heading", { name: "Speed Board" })).toBeVisible();
workspaceId = /\/w\/([^/?#]+)/.exec(page.url())![1]!;
// The onboarding form is covered by identity.spec.ts; here the API is enough.
const created = await page.request.post("/api/v1/accounts", {
data: { accountName: "Speed Agency", workspaceName: "Speed Board" },
headers: { origin: new URL(page.url()).origin },
});
expect(created.status(), await created.text()).toBe(200);
workspaceId = ((await created.json()) as { workspaceId: string }).workspaceId;
await seedBigBoard(workspaceId);
await context.storageState({ path: ".data/speed-owner.json" });
await context.close();
Expand All @@ -135,15 +141,15 @@ function watchRequests(page: Page) {
}

/**
* Clicks a view button and returns the time until the new view's `count` items are in the DOM.
* Clicks a view button and returns the time until the new view's first item is in the DOM.
* React commits in a microtask after the click, so the clock stops on the DOM, not on click().
*/
async function switchView(page: Page, label: string, testId: string, count: number): Promise<number> {
async function switchView(page: Page, label: string, testId: string): Promise<number> {
return page.evaluate(
({ name, testId, count }) =>
({ name, testId }) =>
new Promise<number>((resolve) => {
const button = [...document.querySelectorAll<HTMLButtonElement>('nav[aria-label="Views"] button')].find((b) => b.textContent === name)!;
const done = () => document.querySelectorAll(`[data-testid="${testId}"]`).length === count;
const done = () => document.querySelector(`[data-testid="${testId}"]`) !== null;
const t0 = performance.now();
const observer = new MutationObserver(() => {
if (!done()) return;
Expand All @@ -153,30 +159,74 @@ async function switchView(page: Page, label: string, testId: string, count: numb
observer.observe(document.body, { childList: true, subtree: true });
button.click();
}),
{ name: label, testId, count },
{ name: label, testId },
);
}

test("the /sync payload at 2,000 tasks (measured for decision 033)", async ({ page }) => {
await page.goto(`/w/${workspaceId}`);
const t0 = Date.now();
const res = await page.request.get(`/api/v1/workspaces/${workspaceId}/sync`);
const ms = Date.now() - t0;
const bytes = (await res.body()).length;
const etag = res.headers()["etag"]!;
const t1 = Date.now();
const again = await page.request.get(`/api/v1/workspaces/${workspaceId}/sync`, { headers: { "if-none-match": etag } });
const ms304 = Date.now() - t1;
console.log(`[speed] /sync 200: ${(bytes / 1024).toFixed(0)} KiB uncompressed in ${ms} ms; 304 in ${ms304} ms`);
expect(again.status()).toBe(304);
});

test("the list renders only rows near the viewport, and J reaches rows far below", async ({ page }) => {
await page.goto(`/w/${workspaceId}?view=list`);
await expect(page.getByTestId("task-row").first()).toBeVisible();
const rendered = await page.getByTestId("task-row").count();
console.log(`[speed] list rows in the DOM: ${rendered} of ${TASKS}`);
expect(rendered).toBeLessThan(150);
// The Todo group holds every third task; 100 J presses go far past the first screen.
for (let i = 0; i < 100; i++) await page.keyboard.press("j");
const focused = page.locator('[data-focused="true"]');
await expect(focused).toBeInViewport();
expect(await focused.getAttribute("data-task-id")).toBe("PVTI_big300"); // the 100th Todo task: 3, 6, …, 300
});

test("the timeline draws only rows near the viewport, and J reaches rows far below", async ({ page }) => {
await page.goto(`/w/${workspaceId}?view=timeline`);
await expect(page.getByTestId("timeline-row").first()).toBeVisible();
// One read of both counts: the timeline may re-render between two separate reads.
const { labels, bars } = await page.evaluate(() => ({
labels: document.querySelectorAll('[data-testid="timeline-row"]').length,
bars: document.querySelectorAll('[data-testid="timeline-bar"]').length,
}));
console.log(`[speed] timeline rows in the DOM: ${labels} labels, ${bars} bars of ${TASKS}`);
expect(labels).toBeLessThan(150);
expect(bars).toBe(labels);
for (let i = 0; i < 200; i++) await page.keyboard.press("j");
const focused = page.locator('[data-focused="true"]');
await expect(focused).toBeInViewport();
expect(await focused.getAttribute("data-task-id")).toBe("PVTI_big200"); // timeline order is board order
});

test("the first poll is a 304: the page and /sync agree", async ({ page }) => {
await page.goto(`/w/${workspaceId}`);
await expect(page.getByTestId("task-row")).toHaveCount(TASKS);
await expect(page.getByTestId("task-row").first()).toBeVisible();
const poll = page.waitForResponse((r) => r.url().endsWith(`/workspaces/${workspaceId}/sync`));
await page.evaluate(() => window.dispatchEvent(new Event("focus")));
expect((await poll).status()).toBe(304);
});

test("switching views sends no request and stays within budget", async ({ page }) => {
await page.goto(`/w/${workspaceId}?view=list`);
await expect(page.getByTestId("task-row")).toHaveCount(TASKS);
await expect(page.getByTestId("task-row").first()).toBeVisible();
const requests = watchRequests(page);
const times: Record<string, number> = {};
for (const [label, testId] of [
["Board", "task-card"],
["Timeline", "timeline-row"],
["List", "task-row"],
] as const) {
times[label] = await switchView(page, label, testId, TASKS);
await expect(page.getByTestId(testId)).toHaveCount(TASKS);
times[label] = await switchView(page, label, testId);
await expect(page.getByTestId(testId).first()).toBeVisible();
}
requests.stop();
console.log(`[speed] view switch script ms: ${JSON.stringify(times)}`);
Expand All @@ -187,6 +237,36 @@ test("switching views sends no request and stays within budget", async ({ page }
for (const [label, ms] of Object.entries(times)) expect(ms, `${label} switch`).toBeLessThan(SWITCH_BUDGET_MS);
});

test("J moves focus within budget on 2,000 rows", async ({ page }) => {
await page.goto(`/w/${workspaceId}?view=list`);
await expect(page.getByTestId("task-row").first()).toBeVisible();
await page.keyboard.press("j"); // focus the first row
await expect(page.locator('[data-focused="true"]')).toHaveCount(1);
const times = await page.evaluate(async () => {
const out: number[] = [];
for (let i = 0; i < 10; i++) {
const before = document.querySelector('[data-focused="true"]');
const t0 = performance.now();
await new Promise<void>((resolve) => {
const observer = new MutationObserver(() => {
const now = document.querySelector('[data-focused="true"]');
if (now && now !== before) {
observer.disconnect();
resolve();
}
});
observer.observe(document.body, { attributes: true, subtree: true, attributeFilter: ["data-focused"] });
window.dispatchEvent(new KeyboardEvent("keydown", { key: "j", bubbles: true }));
});
out.push(performance.now() - t0);
}
return out;
});
const worst = Math.max(...times);
console.log(`[speed] J focus move ms (10 presses): worst ${worst.toFixed(1)}, median ${[...times].sort((a, b) => a - b)[5]!.toFixed(1)}`);
expect(worst).toBeLessThan(FOCUS_BUDGET_MS);
});

test("a task opens in the side panel without a page load", async ({ page }) => {
await page.goto(`/w/${workspaceId}?view=list`);
const url = page.url();
Expand All @@ -195,10 +275,10 @@ test("a task opens in the side panel without a page load", async ({ page }) => {
page.on("request", (r) => {
if (r.isNavigationRequest() || (r.url().includes("_rsc") && !r.headers()["next-router-prefetch"])) loads.push(r.url());
});
await page.getByRole("link", { name: "Task number 7", exact: true }).click();
await page.getByRole("link", { name: "Task number 3", exact: true }).click();
const panel = page.getByTestId("peek-panel");
await expect(panel.getByRole("heading", { name: "Task number 7" })).toBeVisible();
await expect(panel.getByText("Body of task 7")).toBeVisible();
await expect(panel.getByRole("heading", { name: "Task number 3" })).toBeVisible();
await expect(panel.getByText("Body of task 3")).toBeVisible();
expect(page.url()).toBe(url);
expect(loads).toEqual([]);
await page.keyboard.press("Escape");
Expand All @@ -207,8 +287,10 @@ test("a task opens in the side panel without a page load", async ({ page }) => {

test("an edit shows before the server answers, and rolls back on refusal", async ({ page }) => {
await page.goto(`/w/${workspaceId}?view=list`);
const row = page.getByTestId("task-row").filter({ has: page.getByRole("link", { name: "Task number 9", exact: true }) });
await expect(row).toContainText("Todo"); // 9 % 3 = 0 → Todo
// The row moves to another status group when the status changes, so watch the store through the
// panel's Status field, and the Todo group's count in its header.
const todoHeader = page.getByRole("heading", { name: /^Todo/ });
await expect(todoHeader).toContainText("666"); // n % 3 = 0: 3, 6, …, 1998

let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
Expand All @@ -219,29 +301,36 @@ test("an edit shows before the server answers, and rolls back on refusal", async
});

await page.getByRole("link", { name: "Task number 9", exact: true }).click();
await page.getByTestId("peek-panel").getByLabel("Status").selectOption({ label: "Done" });
// Before the server answers: the row already shows the new status.
await expect(row).toContainText("Done");
const status = page.getByTestId("peek-panel").getByLabel("Status");
await status.selectOption({ label: "Done" });
// Before the server answers: the task has already left the Todo group.
await expect(status).toHaveValue("s-done");
await expect(todoHeader).toContainText("665");
release();
await expect(page.getByRole("status")).toContainText("Could not change Status");
await expect(row).toContainText("Todo");
await expect(status).toHaveValue("s-todo");
await expect(todoHeader).toContainText("666");
});

test("a successful edit keeps the server's answer", async ({ page }) => {
await page.goto(`/w/${workspaceId}?view=list`);
const row = page.getByTestId("task-row").filter({ has: page.getByRole("link", { name: "Task number 10", exact: true }) });
await expect(row).toContainText("Doing"); // 10 % 3 = 1
// The Done group is far below the first screen (virtualized), so watch the panel's Status field.
const sync = await page.request.get(`/api/v1/workspaces/${workspaceId}/sync`);
const task = ((await sync.json()) as { board: { tasks: { id: string; fields: Record<string, unknown> }[] } }).board.tasks.find(
(t) => t.id === "PVTI_big10",
(t) => t.id === "PVTI_big6",
)!;
await page.route(`**/api/v1/workspaces/${workspaceId}/tasks/PVTI_big10`, async (route) => {
await page.route(`**/api/v1/workspaces/${workspaceId}/tasks/PVTI_big6`, async (route) => {
if (route.request().method() !== "PATCH") return route.fallback();
await route.fulfill({
json: { task: { ...task, fields: { ...task.fields, F_bstatus: { type: "single_select", optionId: "s-done", name: "Done" } } } },
});
});
await page.getByRole("link", { name: "Task number 10", exact: true }).click();
await page.getByTestId("peek-panel").getByLabel("Status").selectOption({ label: "Done" });
await expect(row).toContainText("Done");
await page.getByRole("link", { name: "Task number 6", exact: true }).click();
const status = page.getByTestId("peek-panel").getByLabel("Status");
await status.selectOption({ label: "Done" });
await expect(status).toHaveValue("s-done");
// After the stubbed success the server's answer stays: no rollback, no notice.
await page.waitForTimeout(300);
await expect(status).toHaveValue("s-done");
await expect(page.getByRole("status")).not.toContainText("Could not");
});
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@opennextjs/cloudflare": "1.20.11",
"better-auth": "1.7.8",
"class-variance-authority": "0.7.1",
"cmdk": "1.1.1",
"cn": "0.4.0",
"drizzle-orm": "0.45.4",
"lucide-react": "1.57.0",
Expand Down
3 changes: 2 additions & 1 deletion apps/web/playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ export default defineConfig({
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 1 : 0,
reporter: process.env.CI ? "github" : "list",
use: { baseURL: `http://localhost:${PORT}`, trace: "on-first-retry" },
// Keep a trace and a screenshot of every failure, first attempt included: flakes are diagnosable.
use: { baseURL: `http://localhost:${PORT}`, trace: "retain-on-failure", screenshot: "only-on-failure" },
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
webServer: {
command: `rm -f .data/e2e.sqlite* ${E2E_OUTBOX} && pnpm db:migrate && pnpm build && pnpm start --port ${PORT}`,
Expand Down
8 changes: 8 additions & 0 deletions apps/web/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,20 @@ export const metadata: Metadata = {
description: "Project management on top of GitHub.",
};

// Dark mode follows the system setting, before the first paint (no flash of the light theme).
const THEME = `(function(){var m=window.matchMedia("(prefers-color-scheme: dark)");function a(){document.documentElement.classList.toggle("dark",m.matches)}a();m.addEventListener("change",a)})()`;

export default function RootLayout({ children }: LayoutProps<"/">) {
return (
<html
lang="en"
// The theme script sets the "dark" class before React hydrates.
suppressHydrationWarning
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<head>
<script dangerouslySetInnerHTML={{ __html: THEME }} />
</head>
<body className="min-h-full flex flex-col">{children}</body>
</html>
);
Expand Down
Loading
Loading