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
130 changes: 130 additions & 0 deletions dashboard/e2e/codegen-env.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { expect, test, type Page, type Route } from "@playwright/test";
import fs from "node:fs";
import path from "node:path";

// A run that stopped before its pull request because a code generator needed
// public values the repository doesn't set: the run page names them and links
// to the repository's codegen environment, where an admin sets public values
// (secrets are refused). Every API call is answered here.

const SHOTS_DIR = process.env.E2E_SHOTS_DIR || path.join("test-results", "shots");
const now = Date.now();
const iso = (minsAgo: number) => new Date(now - minsAgo * 60_000).toISOString();

const RUN = {
run_id: "01RUNG",
status: "failed",
ticket_source: "jira",
ticket_id: "ABC-8",
title: "Add the hero block",
repo: "your-team/web",
branch: "abc-8-hero-block",
cost_usd: 1,
tokens_in: 10,
tokens_out: 10,
duration_s: 600,
current_pass: "review",
created_at: iso(30),
updated_at: iso(2),
error:
"Stopped before opening a pull request: regenerating the generated files failed because `pnpm run typegen` needs public values the sandbox doesn't have.",
pass_history: [],
progress_notes: [],
codegen_env_missing: {
repo: "your-team/web",
command: "pnpm run typegen",
vars: ["SANITY_STUDIO_DATASET", "SANITY_STUDIO_PROJECT_ID"],
},
};

async function mockApi(page: Page, role = "admin") {
const puts: unknown[] = [];
const json = (route: Route, body: unknown, status = 200) =>
route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
await page.route((url) => url.hostname !== "localhost", (route) => route.abort());
await page.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (route) => {
const req = route.request();
const p = new URL(req.url()).pathname;
if (p === "/api/me") return json(route, { user_id: "u_1", team_id: "t_1", github_login: "sam", email: "sam@example.com", avatar_url: "", role });
if (p === "/api/usage") return json(route, { month: "2026-01", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 });
if (p === "/api/banners") return json(route, { banners: [] });
if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "your-team", status: "active", current: true }] });
if (p === "/api/repos") return json(route, { repos: [{ name: "your-team/web", enabled: true, onboard_status: "ready" }] });
if (p === "/api/plugins/catalog") return json(route, { plugins: [] });
if (p === "/api/runs/01RUNG") return json(route, RUN);
if (/^\/api\/runs\/01RUNG\//.test(p)) return json(route, p.endsWith("traces") ? { traces: [] } : p.endsWith("agent-log") ? { passes: [], live_events: [] } : p.endsWith("asks") ? { asks: [] } : {});
if (p === "/api/repos/your-team/web/codegen-env" && req.method() === "GET") return json(route, { repo: "your-team/web", vars: [{ name: "SANITY_STUDIO_DATASET", value: "production" }] });
if (p === "/api/repos/your-team/web/codegen-env" && req.method() === "PUT") {
const body = JSON.parse(req.postData() ?? "{}");
puts.push(body);
const bad = (body.vars as { name: string }[]).find((v) => /TOKEN|SECRET|PASSWORD/.test(v.name));
if (bad) return json(route, { error: `\`${bad.name}\` looks like a secret. Only public values (ones that already ship to the browser) belong here.` }, 400);
return json(route, { repo: "your-team/web", count: body.vars.length });
}
return json(route, { error: `Not mocked: ${p}` }, 404);
});
return puts;
}

async function shot(page: Page, name: string) {
fs.mkdirSync(SHOTS_DIR, { recursive: true });
await page.screenshot({ path: path.join(SHOTS_DIR, `${name}.png`), fullPage: true });
}

for (const [label, width, height] of [
["desktop", 1440, 900],
["phone", 390, 844],
] as const) {
test(`a run stopped for missing codegen values names them and links to where they're set (${label})`, async ({ page }) => {
await page.setViewportSize({ width, height });
const puts = await mockApi(page);
await page.goto("/runs/detail?id=01RUNG");
const box = page.getByTestId("codegen-env-missing");
await expect(box).toContainText("SANITY_STUDIO_PROJECT_ID");
await expect(box).toContainText("SANITY_STUDIO_DATASET");
await expect(box).toContainText("Codegen environment");
const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
expect(overflow).toBeLessThanOrEqual(0);
await shot(page, `codegen-env-run-${width}`);

await page.getByTestId("codegen-env-link").click();
await expect(page).toHaveURL(/\/settings\/repos\/codegen\/?\?repo=your-team%2Fweb&need=/);
await expect(page.getByTestId("codegen-env-warning")).toContainText("Never put tokens");
// The one already set is kept; the one the run asked for is pre-filled.
const names = page.getByRole("textbox", { name: "Name" });
await expect(names).toHaveCount(2);
await expect(names.nth(1)).toHaveValue("SANITY_STUDIO_PROJECT_ID");
await page.getByRole("textbox", { name: "Value" }).nth(1).fill("abc123xy");
await shot(page, `codegen-env-settings-${width}`);
await page.getByRole("button", { name: "Save" }).click();
await expect(page.getByText("Saved. The next run uses these values.")).toBeVisible();
expect(puts.at(-1)).toEqual({
vars: [
{ name: "SANITY_STUDIO_DATASET", value: "production" },
{ name: "SANITY_STUDIO_PROJECT_ID", value: "abc123xy" },
],
});
});
}

test("a secret is refused with the reason", async ({ page }) => {
await mockApi(page);
await page.goto("/settings/repos/codegen?repo=your-team%2Fweb");
await page.getByRole("button", { name: "Add a variable" }).click();
await page.getByRole("textbox", { name: "Name" }).last().fill("sanity_auth_token");
await page.getByRole("textbox", { name: "Value" }).last().fill("x");
await page.getByRole("button", { name: "Save" }).click();
await expect(page.getByTestId("codegen-env-error")).toContainText("looks like a secret");
});

test("the repositories list links each repo to its codegen environment", async ({ page }) => {
await mockApi(page);
await page.goto("/settings/repos");
await expect(page.getByRole("link", { name: "Codegen environment" })).toHaveAttribute("href", "/settings/repos/codegen?repo=your-team%2Fweb");
});

test("members don't get the settings page", async ({ page }) => {
await mockApi(page, "member");
await page.goto("/settings/repos/codegen?repo=your-team%2Fweb");
await expect(page.getByTestId("codegen-env-form")).toHaveCount(0);
});
111 changes: 111 additions & 0 deletions dashboard/e2e/round-incomplete.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { expect, test, type Page, type Route } from "@playwright/test";
import fs from "node:fs";
import path from "node:path";

// A run whose pull request is open while its last fix round didn't finish:
// the run page says so plainly (never "failed") and offers Resume, which calls
// the run's retry path. Every API call is answered here.

const SHOTS_DIR = process.env.E2E_SHOTS_DIR || path.join("test-results", "shots");

const now = Date.now();
const iso = (minsAgo: number) => new Date(now - minsAgo * 60_000).toISOString();

const RUN = {
run_id: "01RUNR",
status: "completed",
ticket_source: "jira",
ticket_id: "ABC-7",
title: "Add the gallery block",
repo: "your-team/web",
branch: "abc-7-gallery-block",
pr_url: "https://github.com/your-team/web/pull/41",
pr_number: 41,
cost_usd: 4.2,
tokens_in: 1000,
tokens_out: 1000,
duration_s: 2400,
current_pass: "done",
created_at: iso(120),
updated_at: iso(5),
pass_history: [],
progress_notes: [],
round_incomplete: {
kind: "review_fix",
number: 3,
reason: "the review fix round ran out of its time budget 3 times in a row",
summary: "Pull request open; the last fix round didn't finish: the review fix round ran out of its time budget 3 times in a row.",
pushed: [
{ sha: "4f2a9c1e7b3d", message: "ABC-7: Add the gallery tabs" },
{ sha: "9b0c4d2a1e6f", message: "ABC-7: Add the tab tests" },
],
files: ["src/blocks/gallery/tabs.tsx", "src/blocks/gallery/tabs.test.tsx"],
wip_branch: "coderhelm-wip/abc-7-gallery-block",
at: iso(5),
can_resume: true,
},
};

async function mockApi(page: Page, role = "member") {
const calls: string[] = [];
const json = (route: Route, body: unknown, status = 200) =>
route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
await page.route((url) => url.hostname !== "localhost", (route) => route.abort());
await page.route((url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), async (route) => {
const req = route.request();
const p = new URL(req.url()).pathname;
calls.push(`${req.method()} ${p}`);
if (p === "/api/me") return json(route, { user_id: "u_1", team_id: "t_1", github_login: "sam", email: "sam@example.com", avatar_url: "", role });
if (p === "/api/usage") return json(route, { month: "2026-01", total_tokens: 0, tokens_in: 0, tokens_out: 0, total_runs: 0, max_tokens: 0 });
if (p === "/api/banners") return json(route, { banners: [] });
if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "your-team", status: "active", current: true }] });
if (p === "/api/repos") return json(route, { repos: [{ name: "your-team/web", enabled: true, ticket_source: "jira" }] });
if (p === "/api/plugins/catalog") return json(route, { plugins: [] });
if (p === "/api/runs/01RUNR") return json(route, RUN);
if (p === "/api/runs/01RUNR/retry" && req.method() === "POST") return json(route, { status: "resuming" });
if (p === "/api/runs/01RUNR/openspec") return json(route, {});
if (p === "/api/runs/01RUNR/traces") return json(route, { traces: [] });
if (p === "/api/runs/01RUNR/agent-log") return json(route, { passes: [], live_events: [] });
if (p === "/api/runs/01RUNR/asks") return json(route, { asks: [] });
return json(route, { error: `Not mocked: ${p}` }, 404);
});
return calls;
}

async function shot(page: Page, name: string) {
fs.mkdirSync(SHOTS_DIR, { recursive: true });
await page.screenshot({ path: path.join(SHOTS_DIR, `${name}.png`), fullPage: true });
}

for (const [label, width, height] of [
["desktop", 1440, 900],
["phone", 390, 844],
] as const) {
test(`an open PR whose last fix round stopped reads plainly and resumes (${label})`, async ({ page }) => {
await page.setViewportSize({ width, height });
const calls = await mockApi(page);
await page.goto("/runs/detail?id=01RUNR");
const outcome = page.getByTestId("run-outcome");
await expect(outcome).toContainText("Pull request open; the last fix round didn't finish");
await expect(outcome).toContainText("The review fix round ran out of its time budget 3 times in a row.");
await expect(page.getByTestId("round-incomplete")).toContainText("The pull request is unchanged. Its work so far (2 checkpoint commits) is saved on branch coderhelm-wip/abc-7-gallery-block.");
await expect(outcome).not.toContainText(/failed/i);
await expect(page.getByText("PR open, fix unfinished")).toBeVisible();
await expect(outcome.getByRole("link", { name: /Open pull request #41/ })).toBeVisible();
const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
expect(overflow).toBeLessThanOrEqual(0);
await shot(page, `round-incomplete-${width}`);

await page.getByTestId("resume-round").click();
await expect(page.getByText("Resuming the fix round on the same pull request")).toBeVisible();
expect(calls).toContain("POST /api/runs/01RUNR/retry");
await expect(page.getByTestId("round-incomplete")).toHaveCount(0);
});
}

test("a viewer sees the state but no Resume", async ({ page }) => {
await mockApi(page, "viewer");
await page.goto("/runs/detail?id=01RUNR");
await expect(page.getByTestId("round-incomplete")).toContainText("Ask someone with member access to resume it.");
await expect(page.getByTestId("resume-round")).toHaveCount(0);
});
89 changes: 87 additions & 2 deletions dashboard/src/app/runs/detail/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@
if (idx > max) max = idx;
});
return max;
}, [run?.current_pass, run?.pass_history]);

Check warning on line 448 in dashboard/src/app/runs/detail/page.tsx

View workflow job for this annotation

GitHub Actions / Lint & Build

React Hook useMemo has a missing dependency: 'run'. Either include it or remove the dependency array

if (!runId) {
return (
Expand Down Expand Up @@ -520,6 +520,22 @@
const openPrs = run.pr_number && run.status !== "merged" ? [...new Set([run.pr_number, ...(run.pr_numbers ?? [])])] : [];
const limitTitle = limitHit ? `The monthly ${limitName(limitHit.kind)} limit is reached` : undefined;

// The pull request is open but its last fix round didn't finish: Retry
// resumes that round on the same run (the gateway's retry path).
const unfinished = run.round_incomplete ?? null;
const canResume = !!unfinished?.can_resume;
const resumeRound = async () => {
setBusy("retry");
try {
await api.retryRun(runId);
setRun((r) => (r ? { ...r, status: "awaiting_ci", round_incomplete: null } : r));
toast("Resuming the fix round on the same pull request");
} catch (e) {
toast(actionError(e, "resume this fix round"), "error");
} finally {
setBusy(null);
}
};
const retry = async () => {
setBusy("retry");
try {
Expand Down Expand Up @@ -654,7 +670,76 @@
);

let outcome: React.ReactNode;
if (run.status === "failed") {
if (done && unfinished) {
outcome = (
<OutcomeCard
tone="attention"
title="Pull request open; the last fix round didn't finish"
testId="run-outcome"
actions={
<>
{canAct && canResume && (
<button type="button" onClick={resumeRound} disabled={busy !== null || tokensExceeded} title={limitTitle} className={primaryButton} data-testid="resume-round">
{busy === "retry" ? "Resuming…" : "Resume"}
</button>
)}
{openPrButtons("secondary")}
</>
}
>
<div className="space-y-1" data-testid="round-incomplete">
<p className="[overflow-wrap:anywhere]">{unfinished.reason ? `${unfinished.reason.charAt(0).toUpperCase()}${unfinished.reason.slice(1)}.` : "It stopped before it finished."}</p>
<p className="text-zinc-400">
{unfinished.pushed.length && unfinished.wip_branch
? `The pull request is unchanged. Its work so far (${unfinished.pushed.length} checkpoint commit${unfinished.pushed.length === 1 ? "" : "s"}) is saved on branch ${unfinished.wip_branch}.`
: "The pull request is unchanged; the round saved no work before it stopped."}{" "}
{canAct && canResume ? "Resume continues the round from there with a fresh time budget and pushes it to the pull request as one commit when it's done." : "Ask someone with member access to resume it."}
</p>
</div>
</OutcomeCard>
);
} else if (run.status === "failed" && run.codegen_env_missing?.vars.length) {
// A generator needed public values the repository doesn't set: say which,
// and where to set them; Retry once they're in.
const missing = run.codegen_env_missing;
outcome = (
<OutcomeCard
tone="attention"
title="Generated files couldn't be regenerated"
testId="run-outcome"
actions={
<>
{canAct && (
<a
href={`/settings/repos/codegen?repo=${encodeURIComponent(missing.repo)}&need=${encodeURIComponent(missing.vars.join(","))}`}
className={primaryButton}
data-testid="codegen-env-link"
>
Set the values
</a>
)}
{retryButton}
</>
}
>
<div className="space-y-2" data-testid="codegen-env-missing">
<p className="[overflow-wrap:anywhere]">
The pull request didn&apos;t open: <Code>{missing.command}</Code> needs public values {missing.repo} doesn&apos;t set for Coderhelm&apos;s sandbox:
</p>
<ul className="list-disc space-y-1 pl-5 text-sm">
{missing.vars.map((v) => (
<li key={v}>
<Code>{v}</Code>
</li>
))}
</ul>
<p className="text-zinc-400">
Set them in Settings, Repositories, {missing.repo}, Codegen environment (public values only, never secrets), then retry.
</p>
</div>
</OutcomeCard>
);
} else if (run.status === "failed") {
outcome = (
<Problem
testId="run-outcome"
Expand Down Expand Up @@ -792,7 +877,7 @@
<PageHeader
detail
title={run.title || "Untitled run"}
status={<RunStatusBadge status={run.status} />}
status={<RunStatusBadge status={run.status} unfinishedRound={!!run.round_incomplete && ["completed", "success"].includes(run.status)} />}
lead={
<span className="[overflow-wrap:anywhere]">
{run.repo || "Choosing a repository…"}
Expand Down
Loading
Loading