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

// A run held by the team's monthly token limit starts again by itself: the run
// page says so in one line, with the time in the viewer's own zone and a link
// to the limit, and never asks a person to act. Admins hear about a limit
// before it runs out, at 80% and again at 95%, once each per month. Every API
// call is answered here.

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

// The viewer is in New York: 00:00 UTC on Dec 1 is 7:00 PM on Nov 30 there.
test.use({ timezoneId: "America/New_York", locale: "en-US", colorScheme: "dark" });

const MONTH = "2026-11";
const RESUMES = "2026-12-01T00:00:00Z";
const RESUMES_LOCAL = "Mon, Nov 30, 7:00 PM EST";
const PROJECTED = "2026-11-27T19:00:00Z";
const PROJECTED_LOCAL = "Fri, Nov 27, 2:00 PM EST";

type Run = Record<string, unknown> & { run_id: string; status: string };

function run(over: Partial<Run> = {}): Run {
return {
run_id: "01RUNPAUSE",
status: "needs_input",
ticket_source: "github",
ticket_id: "acme/bookstore-web#12",
title: "Show the gift card balance at checkout",
repo: "acme/bookstore-web",
current_pass: "implement",
tokens_in: 1200,
tokens_out: 300,
cost_usd: 0.4,
duration_s: 95,
created_at: "2026-11-27T15:00:00Z",
updated_at: "2026-11-27T15:20:00Z",
pass_history: [
{ pass: "triage", started_at: "2026-11-27T15:00:00Z" },
{ pass: "plan", started_at: "2026-11-27T15:02:00Z" },
{ pass: "implement", started_at: "2026-11-27T15:08:00Z" },
],
progress_notes: [],
questions: [],
answers: [],
...over,
};
}

const LIMIT_LINE = "Paused: this month's token limit is used up (40.3M of 40M). Resumes by itself on Tue, Dec 1, 00:00 UTC when the month turns, or as soon as an admin raises the limit.";
const ROOM_LINE = "Waiting for token room: this month's limit has 1.5M left and a run like this takes about 4M. Starts by itself on Tue, Dec 1, 00:00 UTC when the month turns, or as soon as an admin raises the limit.";

const RUNS: Record<string, Run> = {
"01RUNPAUSE": run({
waiting_on: {
action: LIMIT_LINE,
detail: "",
pause: { kind: "token_limit", limit: "new tokens", used: 40_300_000, max: 40_000_000, resumes_at: RESUMES, line: LIMIT_LINE, settings_path: "/settings/budget" },
},
}),
"01RUNROOM": run({
run_id: "01RUNROOM",
title: "Add a reading list export",
ticket_id: "acme/bookstore-web#14",
current_pass: "triage",
pass_history: [{ pass: "triage", started_at: "2026-11-27T15:00:00Z" }],
waiting_on: {
action: ROOM_LINE,
detail: "",
pause: { kind: "token_room", limit: "new tokens", used: 38_500_000, max: 40_000_000, room: 1_500_000, need: 4_000_000, resumes_at: RESUMES, line: ROOM_LINE, settings_path: "/settings/budget" },
},
}),
"01RUNPERSON": run({
run_id: "01RUNPERSON",
title: "Fix the shelf sort order",
ticket_id: "acme/bookstore-web#15",
waiting_on: { action: "Review pull request #31", detail: "The reviewer asked for a second look at the sort key.", url: "https://github.com/acme/bookstore-web/pull/31" },
}),
};

type Limit = { kind: string; max: number; used: number; warn_level?: number; projected_at?: string | null };

function usage(limits: Limit[], month = MONTH) {
const used = limits[0]?.used ?? 0;
return { month, total_tokens: used, tokens_in: used, tokens_out: 0, cache_read_tokens: 0, cache_write_tokens: 0, total_runs: 3, max_tokens: 0, limits };
}

const AT_80: Limit = { kind: "new_tokens", max: 40_000_000, used: 33_000_000, warn_level: 80, projected_at: PROJECTED };
const AT_95: Limit = { kind: "new_tokens", max: 40_000_000, used: 38_500_000, warn_level: 95, projected_at: PROJECTED };
const REACHED: Limit = { kind: "new_tokens", max: 40_000_000, used: 40_300_000, warn_level: 100 };
const UNDER: Limit = { kind: "new_tokens", max: 40_000_000, used: 9_000_000, warn_level: 0 };

interface Backend {
role: string;
usage: ReturnType<typeof usage>;
}

async function mockApi(page: Page, init: Partial<Backend> = {}): Promise<Backend> {
const db: Backend = { role: "admin", usage: usage([UNDER]), ...init };
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 url = new URL(req.url());
const p = url.pathname;
if (p === "/api/me") return json(route, { user_id: "u_1", team_id: "t_1", github_login: "pat", email: "pat@example.com", avatar_url: "", role: db.role });
if (p === "/api/usage") return json(route, db.usage);
if (p === "/api/banners") return json(route, { banners: [] });
if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "acme", status: "active", current: true }] });
if (p === "/api/repos") return json(route, { repos: [{ name: "acme/bookstore-web", enabled: true, ticket_source: "github" }] });
if (p === "/api/plugins/catalog") return json(route, { plugins: [] });
if (p === "/api/search") return json(route, { q: url.searchParams.get("q"), runs: [], reviews: [], releases: [], plans: [] });
if (p === "/api/runs" && req.method() === "GET") return json(route, { runs: Object.values(RUNS), next: null });
const m = p.match(/^\/api\/runs\/([^/]+)(?:\/(.+))?$/);
if (m) {
const r = RUNS[decodeURIComponent(m[1])];
if (!r) return json(route, { error: "No run with this id in the team.", code: "not_found" }, 404);
const action = m[2];
if (!action) return json(route, r);
if (action === "openspec") return json(route, {});
if (action === "traces") return json(route, { traces: [] });
if (action === "agent-log") return json(route, { passes: [], live_events: [] });
if (action === "asks") return json(route, { asks: [] });
}
return json(route, { error: `Not mocked: ${p}` }, 404);
});
return db;
}

const openRun = (page: Page, id: string) => page.goto(`/runs/detail?id=${id}`);

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

test.describe("a run held by the token limit", () => {
test("a paused run says when it resumes, in the viewer's zone, and needs no person", async ({ page }) => {
await mockApi(page, { usage: usage([REACHED]) });
await openRun(page, "01RUNPAUSE");
const outcome = page.getByTestId("run-outcome");
await expect(outcome).toHaveAttribute("data-tone", "info");
await expect(page.getByTestId("run-pause-line")).toHaveText(
`Paused: this month's token limit is used up (40.3M of 40M). Resumes by itself on ${RESUMES_LOCAL} when the month turns, or as soon as an admin raises the limit.`,
);
await expect(outcome.getByTestId("run-who")).toHaveText("Resumes by itself");
await expect(page.getByText("Needs a person")).toHaveCount(0);
await expect(page.getByText("Needs your answer")).toHaveCount(0);
await expect(page.getByText("Waiting on you")).toHaveCount(0);
await expect(page.getByText("Waiting on a person")).toHaveCount(0);
// The gateway's UTC wording is the fallback only; the page shows the viewer's zone.
await expect(page.getByText(/00:00 UTC/)).toHaveCount(0);
// The status badge in the header.
await expect(page.getByText("Paused", { exact: true }).first()).toBeVisible();
// No Retry: it starts again by itself.
await expect(outcome.getByRole("button", { name: "Retry" })).toHaveCount(0);
const link = page.getByTestId("run-pause-settings");
await expect(link).toHaveText("Token limit settings");
await expect(link).toHaveAttribute("href", /\/settings\/budget\/?$/);
});

test("a run waiting for token room says how much is left and what it needs", async ({ page }) => {
await mockApi(page, { usage: usage([AT_95]) });
await openRun(page, "01RUNROOM");
await expect(page.getByTestId("run-pause-line")).toHaveText(
`Waiting for token room: this month's limit has 1.5M left and a run like this takes about 4M. Starts by itself on ${RESUMES_LOCAL} when the month turns, or as soon as an admin raises the limit.`,
);
await expect(page.getByTestId("run-outcome").getByTestId("run-who")).toHaveText("Resumes by itself");
await expect(page.getByText("Waiting for token room", { exact: true }).first()).toBeVisible();
await expect(page.getByText("Needs a person")).toHaveCount(0);
await expect(page.getByTestId("run-pause-settings")).toBeVisible();
});

test("a run waiting on a person still says so", async ({ page }) => {
await mockApi(page);
await openRun(page, "01RUNPERSON");
const outcome = page.getByTestId("run-outcome");
await expect(outcome).toContainText("Review pull request #31");
await expect(outcome.getByTestId("run-who")).toHaveText("Needs a person");
await expect(page.getByTestId("run-pause-line")).toHaveCount(0);
});
});

test.describe("warning admins before the limit runs out", () => {
test("80%, then 95%: each shows the projected date, dismisses, and stays dismissed that month", async ({ page }) => {
const db = await mockApi(page, { usage: usage([AT_80]) });
await openRun(page, "01RUNPERSON");
const warn = page.getByTestId("token-limit-warn-banner");
await expect(warn).toContainText("New tokens limit is 80% used: 33M of 40M this month");
await expect(warn.getByTestId("token-limit-projected")).toHaveText(`At this pace it runs out on ${PROJECTED_LOCAL}. `);
await expect(warn.getByRole("link", { name: "Token limit settings" })).toHaveAttribute("href", /\/settings\/budget\/?$/);
await warn.getByRole("button", { name: "Dismiss this message" }).click();
await expect(warn).toHaveCount(0);
await page.reload();
await expect(page.getByTestId("run-outcome")).toBeVisible();
await expect(page.getByTestId("token-limit-warn-banner")).toHaveCount(0);

// 95% is a new level: it shows again, louder.
db.usage = usage([AT_95]);
await page.reload();
await expect(warn).toContainText("New tokens limit is almost used up: 38.5M of 40M this month");
await expect(warn).toContainText(`At this pace it runs out on ${PROJECTED_LOCAL}.`);
await warn.getByRole("button", { name: "Dismiss this message" }).click();
await page.reload();
await expect(page.getByTestId("run-outcome")).toBeVisible();
await expect(page.getByTestId("token-limit-warn-banner")).toHaveCount(0);

// A new month: the 80% warning is news again.
db.usage = usage([{ ...AT_80, projected_at: null }], "2026-12");
await page.reload();
await expect(warn).toContainText("New tokens limit is 80% used");
await expect(warn.getByTestId("token-limit-projected")).toHaveCount(0);
});

test("members don't get the warning", async ({ page }) => {
await mockApi(page, { role: "member", usage: usage([AT_95]) });
await openRun(page, "01RUNPERSON");
await expect(page.getByTestId("run-outcome")).toBeVisible();
await expect(page.getByTestId("token-limit-warn-banner")).toHaveCount(0);
});

test("a reached limit keeps its own banner, which says paused runs resume by themselves", async ({ page }) => {
await mockApi(page, { usage: usage([REACHED]) });
await openRun(page, "01RUNPAUSE");
const reached = page.getByTestId("token-limit-banner");
await expect(reached).toContainText("New tokens limit reached, so new runs are paused");
await expect(reached).toContainText("Paused runs resume by themselves as soon as it is raised, or on Dec 1.");
await expect(page.getByTestId("token-limit-warn-banner")).toHaveCount(0);
});
});

// The screenshots for review: the paused run and the 95% banner, at desktop
// and phone widths. Only pictures, so the same test runs on main for a before.
test.describe("screens", () => {
for (const width of [1440, 390]) {
test(`paused run and warning banner at ${width}`, async ({ page }) => {
await page.setViewportSize({ width, height: width > 600 ? 900 : 844 });
const db = await mockApi(page, { usage: usage([REACHED]) });
await openRun(page, "01RUNPAUSE");
await expect(page.getByTestId("run-outcome")).toBeVisible();
await page.waitForTimeout(500);
await shot(page, `run-${width}-dark`);
// A run waiting for room while the limit is at 95%.
db.usage = usage([AT_95]);
await openRun(page, "01RUNROOM");
await expect(page.getByTestId("run-outcome")).toBeVisible();
await page.waitForTimeout(500);
await shot(page, `banner-${width}-dark`, false);
});
}
});
40 changes: 33 additions & 7 deletions dashboard/src/app/runs/detail/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import Link from "next/link";
import { api, type JiraAppUpdate, type RunDetail, type RunMergeStanding, type Openspec, type UsageInfo, type PluginDef, type PassTrace, type AgentLog, errorStatus } from "@/lib/api";
import { Skeleton } from "@/components/skeleton";
import { limitName, reachedLimit, usageBreakdown, usageTotal } from "@/lib/usage";
import { limitName, pauseLabel, pauseLine, reachedLimit, usageBreakdown, usageTotal } from "@/lib/usage";
import { useToast } from "@/components/toast";
import { useConfirm } from "@/components/confirm-dialog";
import { Callout } from "@/components/callout";
Expand Down Expand Up @@ -326,7 +326,7 @@
if (idx > max) max = idx;
});
return max;
}, [run?.current_pass, run?.pass_history]);

Check warning on line 329 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 @@ -561,6 +561,8 @@
// The timeline, the run's time, and what is still to come.
const prNumber = run.pr_number ?? runPrs[0]?.pr_number ?? null;
const prWords = prNumber ? `Pull request #${prNumber}` : "The pull request";
// Held by the monthly token limit: it starts again by itself, so it never reads as needing a person.
const pause = run.status === "needs_input" && run.waiting_on?.pause ? run.waiting_on.pause : null;
const steps = runTimeline({
status: run.status,
current_pass: run.current_pass,
Expand All @@ -572,7 +574,9 @@
hasPr,
hold: hold?.kind ?? null,
questions: run.status === "needs_input" ? run.questions?.length ?? 0 : 0,
waitingOn: run.status === "needs_input" ? run.waiting_on?.action ?? null : null,
// A paused run's line carries the time in the viewer's zone, not the gateway's UTC.
waitingOn: pause ? pauseLine(pause) : run.status === "needs_input" ? run.waiting_on?.action ?? null : null,
paused: !!pause,
closedBy: run.closed_by,
});
const upcoming = stillToCome({ status: run.status, current_pass: run.current_pass, pass_history: run.pass_history, hasPr });
Expand Down Expand Up @@ -926,7 +930,7 @@
} else {
// `body` is one sentence; `content` is a block of its own (a form, a list).
// `who`: whether a person must act now ("you") or nothing is needed ("none").
const look: { tone: OutcomeTone; title: string; body: React.ReactNode; content?: React.ReactNode; actions?: React.ReactNode; next?: React.ReactNode; who?: "you" | "none" } =
const look: { tone: OutcomeTone; title: string; body: React.ReactNode; content?: React.ReactNode; actions?: React.ReactNode; next?: React.ReactNode; who?: "you" | "none" | "self" } =
hold
? {
// Finished, and the pull request stays a draft: why, and what to do about each reason.
Expand Down Expand Up @@ -1068,6 +1072,19 @@
),
actions: undefined,
}
: pause
? {
// The token limit holds it: no person, no Retry. It starts again by itself.
tone: "info",
title: pauseLabel(pause.kind) ?? "Paused",
who: "self",
body: <span className="[overflow-wrap:anywhere]" data-testid="run-pause-line">{pauseLine(pause)}</span>,
actions: (
<Link href={pause.settings_path?.startsWith("/") && !pause.settings_path.startsWith("//") ? pause.settings_path : "/settings/budget"} className={secondaryButton} data-testid="run-pause-settings">
Token limit settings
</Link>
),
}
: run.status === "needs_input" && run.waiting_on?.action
? {
// A named wait: what to do, why, and where.
Expand Down Expand Up @@ -1170,6 +1187,7 @@
status={run.status}
draftHold={hold?.kind}
waitingOn={!run.questions?.length && !!run.waiting_on?.action}
pause={pause?.kind}
heldOn={run.status === "needs_input" || hold ? runHeldOn([...(hold?.reasons ?? []).map((r) => r.what), run.status === "needs_input" ? run.waiting_on?.detail : null]) : null}
unfinishedRound={!!run.round_incomplete && ["completed", "success"].includes(run.status)}
/>
Expand Down Expand Up @@ -1256,7 +1274,9 @@
? "Working on it"
: run.status === "awaiting_ci"
? "Waiting for the checks"
: run.status === "needs_input"
: pause
? pause.kind === "token_room" ? "Waiting for token room" : "Paused by the token limit"
: run.status === "needs_input"
? "Waiting on a person"
: "What CoderHelm did"
}
Expand Down Expand Up @@ -1617,14 +1637,15 @@
return null;
}

type OutcomeTone = "success" | "waiting" | "attention" | "live" | "neutral";
type OutcomeTone = "success" | "waiting" | "attention" | "live" | "neutral" | "info";

const OUTCOME_LOOK: Record<OutcomeTone, { box: string; dot: string }> = {
success: { box: "border-emerald-500/30 bg-emerald-500/5", dot: "bg-emerald-400" },
waiting: { box: "border-amber-500/30 bg-amber-500/5", dot: "bg-amber-400" },
attention: { box: "border-orange-500/30 bg-orange-500/5", dot: "bg-orange-400" },
live: { box: "border-sky-500/30 bg-sky-500/5", dot: "bg-sky-400 animate-pulse motion-reduce:animate-none" },
neutral: { box: "border-zinc-800 bg-zinc-900/50", dot: "bg-zinc-400" },
info: { box: "border-blue-500/25 bg-blue-500/5", dot: "bg-blue-400" },
};

/**
Expand All @@ -1647,8 +1668,8 @@
testId?: string;
/** What happens next, in one sentence. */
next?: React.ReactNode;
/** A person must act now ("you"), or nothing is needed ("none"). */
who?: "you" | "none";
/** A person must act now ("you"), nothing is needed ("none"), or it starts again by itself ("self"). */
who?: "you" | "none" | "self";
}) {
const look = OUTCOME_LOOK[tone];
return (
Expand All @@ -1663,6 +1684,11 @@
Needs a person
</span>
)}
{who === "self" && (
<span className="whitespace-nowrap rounded-full border border-blue-500/30 bg-blue-500/10 px-2 text-xs font-medium leading-5 text-blue-200" data-testid="run-who">
Resumes by itself
</span>
)}
{who === "none" && (
<span className="whitespace-nowrap text-xs text-zinc-400" data-testid="run-who">
Nothing needed from you
Expand Down
Loading
Loading