From 8113432e9c1d6021a5ea47f57bbb02cf19e74162 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 30 Nov 2026 22:52:55 -0500 Subject: [PATCH] A run held by the token limit reads as paused, and admins hear before the limit runs out A run waiting on the monthly token limit (waiting_on.pause) shows one line with when it resumes, in the viewer's own time zone, a link to the limit setting and no Retry; its badge reads Paused or Waiting for token room, never Needs a person. Admins and owners get a banner at 80% and at 95% of a limit with the projected run-out date, once each per month and limit. The reached-limit banner says paused runs resume by themselves. --- dashboard/e2e/token-limit-pauses.spec.ts | 254 ++++++++++++++++++++++ dashboard/src/app/runs/detail/page.tsx | 40 +++- dashboard/src/components/client-shell.tsx | 42 +++- dashboard/src/components/run-status.tsx | 23 +- dashboard/src/lib/api.ts | 34 +++ dashboard/src/lib/run-timeline.ts | 3 + dashboard/src/lib/usage.ts | 56 ++++- 7 files changed, 439 insertions(+), 13 deletions(-) create mode 100644 dashboard/e2e/token-limit-pauses.spec.ts diff --git a/dashboard/e2e/token-limit-pauses.spec.ts b/dashboard/e2e/token-limit-pauses.spec.ts new file mode 100644 index 00000000..40d84721 --- /dev/null +++ b/dashboard/e2e/token-limit-pauses.spec.ts @@ -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 & { run_id: string; status: string }; + +function run(over: Partial = {}): 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 = { + "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; +} + +async function mockApi(page: Page, init: Partial = {}): Promise { + 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); + }); + } +}); diff --git a/dashboard/src/app/runs/detail/page.tsx b/dashboard/src/app/runs/detail/page.tsx index 2bca0f0e..e9b095bd 100644 --- a/dashboard/src/app/runs/detail/page.tsx +++ b/dashboard/src/app/runs/detail/page.tsx @@ -6,7 +6,7 @@ import { useSearchParams, useRouter } from "next/navigation"; 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"; @@ -561,6 +561,8 @@ function RunDetailInner() { // 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, @@ -572,7 +574,9 @@ function RunDetailInner() { 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 }); @@ -926,7 +930,7 @@ function RunDetailInner() { } 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. @@ -1068,6 +1072,19 @@ function RunDetailInner() { ), 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: {pauseLine(pause)}, + actions: ( + + Token limit settings + + ), + } : run.status === "needs_input" && run.waiting_on?.action ? { // A named wait: what to do, why, and where. @@ -1170,6 +1187,7 @@ function RunDetailInner() { 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)} /> @@ -1256,7 +1274,9 @@ function RunDetailInner() { ? "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" } @@ -1617,7 +1637,7 @@ function standingLink(standing: RunMergeStanding) { return null; } -type OutcomeTone = "success" | "waiting" | "attention" | "live" | "neutral"; +type OutcomeTone = "success" | "waiting" | "attention" | "live" | "neutral" | "info"; const OUTCOME_LOOK: Record = { success: { box: "border-emerald-500/30 bg-emerald-500/5", dot: "bg-emerald-400" }, @@ -1625,6 +1645,7 @@ const OUTCOME_LOOK: Record = { 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" }, }; /** @@ -1647,8 +1668,8 @@ function OutcomeCard({ 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 ( @@ -1663,6 +1684,11 @@ function OutcomeCard({ Needs a person )} + {who === "self" && ( + + Resumes by itself + + )} {who === "none" && ( Nothing needed from you diff --git a/dashboard/src/components/client-shell.tsx b/dashboard/src/components/client-shell.tsx index b41660ca..2f67d898 100644 --- a/dashboard/src/components/client-shell.tsx +++ b/dashboard/src/components/client-shell.tsx @@ -6,7 +6,7 @@ import { usePathname, useRouter } from "next/navigation"; import { type ReactNode, useEffect, useRef, useState } from "react"; import { api, ApiError, TEAM_MOVED, TWO_FACTOR_REQUIRED, movedUrl, type SignInSenders, type UsageInfo, type Banner, type TeamInfo } from "@/lib/api"; import { pushToDataLayer } from "@/lib/gtm"; -import { formatTokens, limitName, reachedLimit, USAGE_CHANGED, usageBreakdown, usageLimits } from "@/lib/usage"; +import { formatTokens, formatWhenLocal, limitName, reachedLimit, USAGE_CHANGED, usageBreakdown, usageLimits, warnBannerId, warnedLimit } from "@/lib/usage"; import { TokenMeters } from "@/components/token-meters"; import { usePluginsFlag } from "@/hooks/use-plugins-flag"; import { ToastProvider } from "./toast"; @@ -502,6 +502,11 @@ export function ClientShell({ children }: { children: React.ReactNode }) { !dismissedBanners.has(b.id))} limit={usage && !dismissedBanners.has("token-limit-banner") ? reachedLimit(usage) : undefined} + warn={(() => { + // Admins and owners hear at 80% and again at 95%, once each per month and limit. + const w = usage && can(user, "budget") && !reachedLimit(usage) ? warnedLimit(usage) : undefined; + return w && !dismissedBanners.has(warnBannerId(usage?.month, w)) ? w : undefined; + })()} month={usage?.month} canRaise={can(user, "budget")} onLimitPage={pathname.replace(/\/+$/, "") === "/settings/budget"} @@ -1827,6 +1832,8 @@ function HelpMenu({ issueHref, waiting, current }: { issueHref: string; waiting: const BANNER_LOOK: Record = { error: { box: "border-red-500/30 bg-red-950/60", icon: , iconClass: "text-red-400" }, + // A token limit at 95%: louder than a warning, short of a reached limit. + urgent: { box: "border-orange-500/40 bg-orange-950/60", icon: , iconClass: "text-orange-400" }, warning: { box: "border-amber-500/30 bg-amber-950/50", icon: , iconClass: "text-amber-400" }, info: { box: "border-blue-500/25 bg-blue-950/40", icon: , iconClass: "text-blue-300" }, }; @@ -1845,19 +1852,22 @@ function ShellBanners({ banners, limit, month, + warn, canRaise, onLimitPage, onDismiss, }: { banners: Banner[]; limit: ReturnType; + /** A limit at 80% or 95% (never a reached one), for admins and owners. */ + warn?: ReturnType; month?: string; canRaise: boolean; onLimitPage: boolean; onDismiss: (id: string) => void; }) { const [open, setOpen] = useState(false); - type Item = { id: string; type: "error" | "warning" | "info"; title: ReactNode; detail?: ReactNode; action?: ReactNode; dismissible: boolean; testId: string }; + type Item = { id: string; type: "error" | "urgent" | "warning" | "info"; title: ReactNode; detail?: ReactNode; action?: ReactNode; dismissible: boolean; testId: string }; const items: Item[] = []; if (limit) { const name = limitName(limit.kind); @@ -1872,7 +1882,7 @@ function ShellBanners({ detail: ( <> You've used {formatTokens(limit.used)} of your {formatTokens(limit.max)} {name} limit this month.{" "} - {canRaise ? `Raise the limit to keep going, or runs resume ${reset}.` : `Ask an admin or the owner to raise the limit, or runs resume ${reset}.`} + {canRaise ? "Raise the limit to keep going." : "Ask an admin or the owner to raise the limit."} Paused runs resume by themselves as soon as it is raised, or {reset}. ), action: onLimitPage ? null : ( @@ -1882,6 +1892,32 @@ function ShellBanners({ ), }); } + if (warn && !limit) { + const name = limitName(warn.kind); + const Name = warn.kind === "all_tokens" ? "Token" : `${name.charAt(0).toUpperCase()}${name.slice(1)}`; + const reset = month ? resetLabel(month).replace("Resets", "on") : "next month"; + const strong = warn.warn_level === 95; + items.push({ + id: warnBannerId(month, warn), + type: strong ? "urgent" : "warning", + testId: "token-limit-warn-banner", + dismissible: true, + title: strong + ? `${Name} limit is almost used up: ${formatTokens(warn.used)} of ${formatTokens(warn.max)} this month` + : `${Name} limit is ${warn.warn_level}% used: ${formatTokens(warn.used)} of ${formatTokens(warn.max)} this month`, + detail: ( + <> + {warn.projected_at ? At this pace it runs out on {formatWhenLocal(warn.projected_at)}. : null} + Runs that reach it pause and resume by themselves {reset}, or as soon as the limit is raised. + + ), + action: onLimitPage ? null : ( + + Token limit settings + + ), + }); + } const rank = { error: 0, warning: 1, info: 2 } as const; for (const b of [...banners].sort((x, y) => (rank[x.type as keyof typeof rank] ?? 2) - (rank[y.type as keyof typeof rank] ?? 2))) { const type = b.type === "error" || b.type === "warning" ? b.type : "info"; diff --git a/dashboard/src/components/run-status.tsx b/dashboard/src/components/run-status.tsx index 04c908c6..eac200ab 100644 --- a/dashboard/src/components/run-status.tsx +++ b/dashboard/src/components/run-status.tsx @@ -89,6 +89,22 @@ const STOPPED_UNFINISHED: RunLook = { label: "Finished, work deferred", tone: "a /** Waiting on a person for something that isn't a question (`waiting_on`): reviewing the pull request, say. */ const WAITING_ON_YOU: RunLook = { label: "Waiting on you", tone: "waiting", group: "waiting" }; +/** + * Held by the team's monthly token limit (`waiting_on.pause`): it starts again + * by itself when the month turns or the limit is raised, so it never reads as + * waiting on a person. + */ +const PAUSED: Record<"token_limit" | "token_room", RunLook> = { + token_limit: { label: "Paused", tone: "info", group: "waiting" }, + token_room: { label: "Waiting for token room", tone: "info", group: "waiting" }, +}; + +/** The look of a run held by the token limit, or null when it isn't. */ +export function runPauseLook(status: string | null | undefined, pauseKind: string | null | undefined): RunLook | null { + if (status !== "needs_input") return null; + return pauseKind === "token_limit" || pauseKind === "token_room" ? PAUSED[pauseKind] : null; +} + /** What a run that needs a person is held on, from its hold reasons and its wait: CI failing, or work left unfinished. */ export function runHeldOn(whats: (string | null | undefined)[]): "ci_failing" | "unfinished" | null { const w = whats.map((s) => (s ?? "").trim()); @@ -103,6 +119,7 @@ export function RunStatusBadge({ draftHold, waitingOn, heldOn, + pause, }: { status: string | null | undefined; unfinishedRound?: boolean; @@ -112,8 +129,10 @@ export function RunStatusBadge({ waitingOn?: boolean; /** What holds it, when that is CI failing or unfinished work (`runHeldOn`). */ heldOn?: "ci_failing" | "unfinished" | null; + /** `waiting_on.pause.kind`, when the token limit holds the run. */ + pause?: string | null; }) { - const look = heldOn === "ci_failing" + const look = runPauseLook(status, pause) ?? (heldOn === "ci_failing" ? CI_FAILING : heldOn === "unfinished" ? STOPPED_UNFINISHED @@ -125,7 +144,7 @@ export function RunStatusBadge({ ? UNFINISHED_ROUND : waitingOn && status === "needs_input" ? WAITING_ON_YOU - : runStatusLook(status); + : runStatusLook(status)); return ( diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index 4f13eab3..67604ab8 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -2514,6 +2514,36 @@ export interface RunWaitingOn { url?: string | null; /** When the wait started. */ since?: string | null; + /** + * Set when the run waits on the team's monthly token limit rather than on a + * person: it starts again by itself. Older backends leave it out. + */ + pause?: RunPause | null; +} + +/** + * A run held by the monthly token limit. `token_limit`: it stopped mid-run at + * the limit. `token_room`: a new run waits because the room left is less than + * a run like it takes. + */ +export interface RunPause { + kind: "token_limit" | "token_room" | (string & {}); + /** The limit's label ("new tokens"). */ + limit: string; + /** Tokens used this month. */ + used: number; + /** The limit. */ + max: number; + /** `token_room` only: tokens left this month. */ + room?: number | null; + /** `token_room` only: about what a run like this takes. */ + need?: number | null; + /** When it starts again by itself: 00:00 UTC on the 1st of next month. */ + resumes_at: string; + /** The gateway's own sentence, with the time in UTC. */ + line: string; + /** Where the limit is set ("/settings/budget"). */ + settings_path: string; } /** Why a finished run's pull request is still a draft. */ @@ -3153,6 +3183,10 @@ export interface TokenLimitUse { max: number; /** What it counts so far this month. */ used: number; + /** The warning level reached: 0, 80, 95 or 100 (percent). Older backends leave it out. */ + warn_level?: number; + /** When the limit runs out at this month's pace, if that is before the month turns. */ + projected_at?: string | null; } /** The three monthly limits; null (or 0) means no limit of that kind. */ diff --git a/dashboard/src/lib/run-timeline.ts b/dashboard/src/lib/run-timeline.ts index c3c471c8..64387d8b 100644 --- a/dashboard/src/lib/run-timeline.ts +++ b/dashboard/src/lib/run-timeline.ts @@ -38,6 +38,8 @@ export interface TimelineInput { hold?: string | null; questions?: number; waitingOn?: string | null; + /** The token limit holds the run (`waiting_on.pause`): it starts again by itself, so nobody is asked to act. */ + paused?: boolean; closedBy?: string | null; } @@ -104,6 +106,7 @@ function endStep(i: TimelineInput): Omit | null { case "awaiting_ci": return { pass: "end", title: i.hasPr ? `Waiting for the checks on ${pr}` : "Waiting for the checks", state: "waiting", started_at: at }; case "needs_input": + if (i.paused) return { pass: "end", title: i.waitingOn || "Paused by the monthly token limit; starts again by itself", state: "waiting", started_at: at }; return { pass: "end", title: i.questions ? (i.questions === 1 ? "Waiting for your answer" : `Waiting for your answers to ${i.questions} questions`) : i.waitingOn || "Waiting for more detail", diff --git a/dashboard/src/lib/usage.ts b/dashboard/src/lib/usage.ts index 7ea76f8c..1046a460 100644 --- a/dashboard/src/lib/usage.ts +++ b/dashboard/src/lib/usage.ts @@ -1,7 +1,7 @@ // Token counts and how close a team is to its monthly limits, shared by the // sidebar meters, the Settings hub and the Token limit page so all three agree. -import type { TokenLimitKind, TokenLimitUse, UsageInfo } from "./api"; +import type { RunPause, TokenLimitKind, TokenLimitUse, UsageInfo } from "./api"; /** Fired after the limit changes so the sidebar meter and banner re-read usage. */ export const USAGE_CHANGED = "coderhelm:usage-changed"; @@ -153,3 +153,57 @@ export function limitBarClass(l: TokenLimitUse): string { const tone = usageTone(l.used, l.max); return tone === "error" ? "bg-red-500" : tone === "warning" ? "bg-amber-500" : "bg-emerald-500"; } + +/** A date and time in the viewer's own time zone: "Tue, Dec 1, 7:00 PM EST". */ +export function formatWhenLocal(iso: string): string { + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return iso; + return d.toLocaleString(undefined, { + weekday: "short", + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", + timeZoneName: "short", + }); +} + +/** What a paused run's status reads as: never "needs a person", since it starts again by itself. */ +export function pauseLabel(kind: string | null | undefined): string | null { + if (kind === "token_limit") return "Paused"; + if (kind === "token_room") return "Waiting for token room"; + return null; +} + +/** + * The run page's one line for a run held by the monthly token limit, with the + * time it starts again in the viewer's zone. An unknown kind gets the + * gateway's own line. + */ +export function pauseLine(p: RunPause): string { + const when = formatWhenLocal(p.resumes_at); + if (p.kind === "token_limit") { + return `Paused: this month's token limit is used up (${formatTokens(p.used)} of ${formatTokens(p.max)}). Resumes by itself on ${when} when the month turns, or as soon as an admin raises the limit.`; + } + if (p.kind === "token_room" && p.room != null && p.need != null) { + return `Waiting for token room: this month's limit has ${formatTokens(p.room)} left and a run like this takes about ${formatTokens(p.need)}. Starts by itself on ${when} when the month turns, or as soon as an admin raises the limit.`; + } + return p.line; +} + +/** + * The limit closest to running out that is at a warning level (80 or 95 + * percent) but not yet reached, as the gateway grades it. A reached limit has + * its own banner. + */ +export function warnedLimit(u: UsageInfo): (TokenLimitUse & { warn_level: 80 | 95 }) | undefined { + const warned = (u.limits ?? []) + .filter((l) => l.max > 0 && l.used < l.max && (l.warn_level === 80 || l.warn_level === 95)) + .sort((a, b) => (b.warn_level ?? 0) - (a.warn_level ?? 0) || b.used / b.max - a.used / a.max); + return warned[0] as (TokenLimitUse & { warn_level: 80 | 95 }) | undefined; +} + +/** The dismissal key for a warning: shown once per month, limit and level. */ +export function warnBannerId(month: string | undefined, l: TokenLimitUse): string { + return `token-limit-warn:${month ?? ""}:${l.kind}:${l.warn_level ?? 0}`; +}