diff --git a/dashboard/e2e/delivery-overview.spec.ts b/dashboard/e2e/delivery-overview.spec.ts new file mode 100644 index 00000000..fdef7e8f --- /dev/null +++ b/dashboard/e2e/delivery-overview.spec.ts @@ -0,0 +1,278 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; +import fs from "node:fs"; +import path from "node:path"; + +// Settings, then Deliveries, then Overview: how deliveries went over a +// period, against the one before. Every API call is answered here; nothing +// reaches a real backend. Names are made up. + +const SHOTS_DIR = process.env.E2E_SHOTS_DIR || path.join("test-results", "shots"); + +const ME = { user_id: "u_1", team_id: "t_1", github_login: "dana", email: "dana@example.org", avatar_url: "", role: "admin", mfa_enabled: false }; + +const DAY = 86_400_000; +const HOUR = 3_600_000; + +function startOfDay(t: number) { + const d = new Date(t); + return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()); +} + +function series(period: string) { + const hourly = period === "24h"; + const n = period === "24h" ? 24 : period === "30d" ? 30 : 7; + const step = hourly ? HOUR : DAY; + const last = hourly ? Math.floor(Date.now() / HOUR) * HOUR : startOfDay(Date.now()); + return Array.from({ length: n }, (_, i) => { + const start = last - (n - 1 - i) * step; + const failed = i % 3 === 0 ? 2 + (i % 5) : i === n - 2 ? 9 : 0; + const ok = 120 + ((i * 37) % 60); + return { + start: new Date(start).toISOString().replace(/\.\d{3}Z$/, "Z"), + end: new Date(start + step).toISOString().replace(/\.\d{3}Z$/, "Z"), + deliveries: ok + failed, + ok, + failed, + success_rate: ok / (ok + failed), + p95_ms: 600 + ((i * 113) % 900), + previous_deliveries: 110 + ((i * 29) % 70), + }; + }); +} + +function full(period: string) { + const s = series(period); + return { + period, + granularity: period === "24h" ? "hour" : "day", + from: s[0].start, + to: s[s.length - 1].end, + previous_from: s[0].start, + previous_to: s[0].start, + summary: { deliveries: 1284, handled: 1190, ignored: 61, failed: 33, success_rate: 0.9743, retried: 41, retried_ok: 37, retries: 58, p50_ms: 180, p95_ms: 1240, p99_ms: 4800 }, + previous: { deliveries: 1120, handled: 1040, ignored: 52, failed: 28, success_rate: 0.975, retried: 30, retried_ok: 26, retries: 44, p50_ms: 170, p95_ms: 1100, p99_ms: 4100 }, + series: s, + sources: [ + { source: "github", direction: "inbound", deliveries: 912, ok: 905, failed: 7, success_rate: 0.9923, p95_ms: 640, previous_deliveries: 870, previous_success_rate: 0.9897 }, + { source: "webhook", direction: "outbound", deliveries: 214, ok: 202, failed: 12, success_rate: 0.9439, p95_ms: 2900, previous_deliveries: 150, previous_success_rate: 0.98 }, + { source: "slack", direction: "outbound", deliveries: 101, ok: 99, failed: 2, success_rate: 0.9802, p95_ms: 420, previous_deliveries: 60, previous_success_rate: 1 }, + { source: "email", direction: "outbound", deliveries: 57, ok: 45, failed: 12, success_rate: 0.7895, p95_ms: 300, previous_deliveries: 40, previous_success_rate: 0.95 }, + ], + reasons: [ + { code: "webhook_server_error", message: "Your webhook endpoint answered with a server error (5xx).", fix: "Check your endpoint's logs for this event id. CoderHelm retries for about a day.", count: 12, previous_count: 3, sources: ["webhook"] }, + { code: "email_sandbox", message: "Amazon SES only sends to confirmed addresses on this account (the SES sandbox).", fix: "Request production access in Amazon SES, or confirm the recipient.", count: 12, previous_count: 0, sources: ["email"] }, + { code: "handler_error", message: "The event was understood but handling it failed.", fix: "Press Redeliver. If it keeps failing, contact support with the delivery id.", count: 7, previous_count: 9, sources: ["github"] }, + { code: "chat_rejected", message: "Slack or Teams refused the message.", fix: "Check the webhook in Settings, Notifications and send a test.", count: 2, previous_count: 1, sources: ["slack"] }, + ], + events: [ + { event: "run.failed", source: "webhook", failed: 9 }, + { event: "invite", source: "email", failed: 8 }, + { event: "pull_request.synchronize", source: "github", failed: 5 }, + ], + endpoints: [ + { id: "ep_off", url: "https://hooks.example.com/old-bot", description: "Old incident bot", deleted: false, enabled: false, disabled_reason: "failing", deliveries: 0, ok: 0, failed: 0, success_rate: null, p50_ms: null, p95_ms: null, streak: 41, last_failure_at: new Date(Date.now() - 3 * DAY).toISOString(), last_failure_reason: "webhook_unreachable", last_failure_message: "Your webhook endpoint couldn't be reached (the connection failed or its name didn't resolve).", failing_since: new Date(Date.now() - 6 * DAY).toISOString(), last_success_at: null }, + { id: "ep_ops", url: "https://ops.example.com/coderhelm/events", description: "", deleted: false, enabled: true, disabled_reason: "", deliveries: 214, ok: 202, failed: 12, success_rate: 0.9439, p50_ms: 320, p95_ms: 2900, streak: 0, last_failure_at: new Date(Date.now() - 2 * HOUR).toISOString(), last_failure_reason: "webhook_server_error", last_failure_message: "Your webhook endpoint answered with a server error (5xx).", failing_since: null, last_success_at: new Date(Date.now() - 5 * 60_000).toISOString() }, + ], + seen_sources: ["email", "github", "slack", "webhook"], + backfill: { complete: true }, + kept_days: 120, + records_kept_days: 14, + }; +} + +function empty(period: string) { + const zero = { deliveries: 0, handled: 0, ignored: 0, failed: 0, success_rate: null, retried: 0, retried_ok: 0, retries: 0, p50_ms: null, p95_ms: null, p99_ms: null }; + const s = series(period).map((p) => ({ ...p, deliveries: 0, ok: 0, failed: 0, success_rate: null, p95_ms: null, previous_deliveries: 0 })); + return { ...full(period), summary: zero, previous: zero, series: s, sources: [], reasons: [], events: [], endpoints: [], seen_sources: [], backfill: { complete: false } }; +} + +function few(period: string) { + const f = full(period); + const s = f.series.map((p, i) => (i === f.series.length - 1 ? { ...p, deliveries: 6, ok: 5, failed: 1, success_rate: 5 / 6, previous_deliveries: 0 } : { ...p, deliveries: 0, ok: 0, failed: 0, success_rate: null, p95_ms: null, previous_deliveries: 0 })); + return { + ...f, + summary: { deliveries: 6, handled: 5, ignored: 0, failed: 1, success_rate: 0.8333, retried: 1, retried_ok: 0, retries: 2, p50_ms: 210, p95_ms: 900, p99_ms: 980 }, + previous: { deliveries: 0, handled: 0, ignored: 0, failed: 0, success_rate: null, retried: 0, retried_ok: 0, retries: 0, p50_ms: null, p95_ms: null, p99_ms: null }, + series: s, + sources: [{ source: "slack", direction: "outbound", deliveries: 6, ok: 5, failed: 1, success_rate: 0.8333, p95_ms: 900, previous_deliveries: 0, previous_success_rate: null }], + reasons: [{ ...f.reasons[3], count: 1, previous_count: 0 }], + events: [{ event: "run.finished", source: "slack", failed: 1 }], + endpoints: [], + seen_sources: ["slack"], + }; +} + +interface Backend { + asks: URLSearchParams[]; + lists: URLSearchParams[]; +} + +async function setup(page: Page, mode: "full" | "empty" | "few" = "full"): Promise { + const db: Backend = { asks: [], lists: [] }; + const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + await page.route((url) => url.pathname === "/runtime-config.js", (route) => route.fulfill({ contentType: "text/javascript", body: "window.__CODERHELM_CONFIG__ = {};" })); + 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 u = new URL(route.request().url()); + const p = decodeURIComponent(u.pathname); + if (p === "/api/me") return json(route, ME); + if (p === "/api/usage") return json(route, { month: "2026-10", 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: "example-org", status: "active", current: true }] }); + if (p === "/api/deliveries/analytics") { + db.asks.push(u.searchParams); + const period = u.searchParams.get("period") || "7d"; + return json(route, mode === "empty" ? empty(period) : mode === "few" ? few(period) : full(period)); + } + if (p === "/api/deliveries") { + db.lists.push(u.searchParams); + return json(route, { + deliveries: [], + summary: { total: 0, ok: 0, failed: 0, pending: 0, success_rate: null, oldest_pending_at: null, last_failure_at: null }, + sources: [], + retention_days: 14, + sharing: { available: false, enabled: false, payloads: false }, + hybrid: false, + }); + } + return json(route, {}); + }); + return db; +} + +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 vp of [ + { name: "1440", width: 1440, height: 900 }, + { name: "390", width: 390, height: 844 }, +]) { + test(`overview at ${vp.name}: tiles, charts, reasons, endpoints, sources and no sideways scroll`, async ({ page }) => { + await page.setViewportSize({ width: vp.width, height: vp.height }); + const db = await setup(page); + await page.goto("/settings/deliveries/?view=overview"); + await expect(page.getByRole("heading", { name: "Deliveries", level: 1 })).toBeVisible(); + await expect(page.getByTestId("deliveries-page").getByRole("link", { name: "Overview" })).toHaveAttribute("aria-current", "page"); + await expect(page.getByTestId("tile-success")).toContainText("97.4%"); + await expect(page.getByTestId("tile-success")).toContainText("0.1 pts lower than the previous 7 days"); + await expect(page.getByTestId("tile-deliveries")).toContainText("1,284"); + await expect(page.getByTestId("tile-deliveries")).toContainText("15% more than the previous 7 days"); + await expect(page.getByTestId("tile-deliveries")).toContainText("41 needed a retry, 37 then went fine"); + await expect(page.getByTestId("tile-failures")).toContainText("33"); + await expect(page.getByTestId("tile-failures")).toContainText("18% more than the previous 7 days"); + await expect(page.getByTestId("tile-latency")).toContainText("13% slower than the previous 7 days"); + await expect(page.getByTestId("chart-volume").locator(".recharts-bar-rectangle").first()).toBeVisible(); + await expect(page.getByTestId("chart-rate").locator(".recharts-line-curve")).toBeVisible(); + await expect(page.getByTestId("reason-row")).toHaveCount(4); + await expect(page.getByTestId("reason-row").first()).toContainText("server error (5xx)"); + await expect(page.getByTestId("reason-row").first()).toContainText("3 in the previous 7 days"); + await expect(page.getByTestId("endpoint-row").filter({ visible: true })).toHaveCount(2); + await expect(page.getByText("Off: kept failing").filter({ visible: true }).first()).toBeVisible(); + expect(db.asks.at(-1)?.get("period")).toBe("7d"); + // Nothing is wider than the screen. + const wide = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + expect(wide).toBeLessThanOrEqual(1); + await page.waitForTimeout(400); + await shot(page, `delivery-overview-${vp.name}`); + }); +} + +test("filters: period, status, source and endpoint go to the server and the address", async ({ page }) => { + const db = await setup(page); + await page.goto("/settings/deliveries/?view=overview"); + await expect(page.getByTestId("tile-success")).toBeVisible(); + + await page.getByRole("group", { name: "Period" }).getByRole("button", { name: "24 hours" }).click(); + await expect.poll(() => db.asks.at(-1)?.get("period")).toBe("24h"); + await expect(page).toHaveURL(/period=24h/); + await expect(page.getByTestId("tile-success")).toContainText("the previous 24 hours"); + + await page.getByRole("group", { name: "Show" }).getByRole("button", { name: "Failed" }).click(); + await expect.poll(() => db.asks.at(-1)?.get("status")).toBe("failed"); + + await page.getByRole("combobox", { name: "Source" }).selectOption("webhook"); + await expect.poll(() => db.asks.at(-1)?.get("source")).toBe("webhook"); + + await page.getByRole("combobox", { name: "Endpoint" }).selectOption("ep_ops"); + await expect.poll(() => db.asks.at(-1)?.get("endpoint")).toBe("ep_ops"); + await expect(page).toHaveURL(/endpoint=ep_ops/); + + // The list tab keeps the source and status. + await expect(page.getByTestId("deliveries-page").getByRole("link", { name: "Deliveries", exact: true })).toHaveAttribute("href", /source=webhook/); + await page.getByTestId("overview-clear").click(); + await expect.poll(() => db.asks.at(-1)?.get("source")).toBeNull(); + await expect(page).not.toHaveURL(/source=|status=|endpoint=/); +}); + +test("drill in: tiles, a bar, a reason, an endpoint and an event open the filtered list", async ({ page }) => { + const db = await setup(page); + await page.goto("/settings/deliveries/?view=overview"); + await expect(page.getByTestId("tile-success")).toBeVisible(); + + // A failure reason opens failed deliveries with that reason, for the period. + const reason = page.getByTestId("reason-row").filter({ hasText: "SES sandbox" }); + await expect(reason).toHaveAttribute("href", /status=failed/); + await reason.click(); + await expect(page).toHaveURL(/reason=email_sandbox/); + await expect(page.getByTestId("narrow-reason")).toContainText("Email sandbox"); + await expect(page.getByTestId("narrow-time")).toBeVisible(); + await expect.poll(() => db.lists.at(-1)?.get("reason")).toBe("email_sandbox"); + expect(db.lists.at(-1)?.get("status")).toBe("failed"); + expect(db.lists.at(-1)?.get("since")).toMatch(/^\d{4}-\d\d-\d\dT00:00:00Z$/); + expect(db.lists.at(-1)?.get("until")).toMatch(/^\d{4}-\d\d-\d\dT00:00:00Z$/); + await page.getByTestId("narrow-reason").getByRole("button").click(); + await expect.poll(() => db.lists.at(-1)?.get("reason")).toBeNull(); + await page.goBack(); + await page.goBack(); + + // A bar opens its own day. + await expect(page.getByTestId("chart-volume")).toBeVisible(); + const bars = page.getByTestId("chart-volume").locator(".recharts-bar-rectangle"); + await bars.last().click(); + await expect(page).toHaveURL(/from=.*until=/); + const since = db.lists.at(-1)?.get("since") ?? ""; + const until = db.lists.at(-1)?.get("until") ?? ""; + expect(Date.parse(until) - Date.parse(since)).toBe(DAY); + await page.goBack(); + + // The table view of the chart has the same days as links. + await page.getByRole("button", { name: "Show table: Deliveries per day" }).click(); + await expect(page.getByRole("table", { name: "Deliveries over time" }).getByRole("link").first()).toHaveAttribute("href", /from=.*until=/); + + // Endpoints: the name opens its settings, the count lists its deliveries. + const ops = page.locator('[data-testid="endpoint-row"][data-id="ep_ops"]').filter({ visible: true }).first(); + await expect(ops.getByTestId("endpoint-link")).toHaveAttribute("href", "/settings/webhooks/?endpoint=ep_ops"); + await expect(page.getByTestId("endpoint-deliveries").filter({ visible: true }).last()).toHaveAttribute("href", /endpoint=ep_ops/); + await expect(page.getByTestId("tile-failures")).toHaveAttribute("href", /status=failed/); + await expect(page.getByTestId("event-link").filter({ visible: true }).first()).toHaveAttribute("href", /q=run\.failed/); + await page.getByTestId("source-link").filter({ visible: true }).first().click(); + await expect(page).toHaveURL(/source=github/); + await expect.poll(() => db.lists.at(-1)?.get("source")).toBe("github"); +}); + +for (const vp of [ + { name: "1440", width: 1440, height: 900 }, + { name: "390", width: 390, height: 844 }, +]) { + test(`empty and low-data states read plainly at ${vp.name}`, async ({ page }) => { + await page.setViewportSize({ width: vp.width, height: vp.height }); + await setup(page, "empty"); + await page.goto("/settings/deliveries/?view=overview"); + await expect(page.getByTestId("overview-empty")).toContainText("No deliveries in the last 7 days"); + await expect(page.getByTestId("overview-backfill")).toBeVisible(); + await shot(page, `delivery-overview-empty-${vp.name}`); + + await page.unrouteAll({ behavior: "ignoreErrors" }); + await setup(page, "few"); + await page.goto("/settings/deliveries/?view=overview"); + await expect(page.getByTestId("overview-low-data")).toContainText("Only 6 deliveries"); + await expect(page.getByTestId("tile-deliveries")).toContainText("None in the previous 7 days"); + await expect(page.getByTestId("tile-success")).toContainText("Nothing to compare with"); + const wide = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + expect(wide).toBeLessThanOrEqual(1); + await page.waitForTimeout(400); + await shot(page, `delivery-overview-few-${vp.name}`); + }); +} diff --git a/dashboard/src/app/analytics/page.tsx b/dashboard/src/app/analytics/page.tsx index 0069820e..1c37e103 100644 --- a/dashboard/src/app/analytics/page.tsx +++ b/dashboard/src/app/analytics/page.tsx @@ -6,19 +6,15 @@ import { Bar, BarChart, CartesianGrid, Legend, Line, LineChart, ResponsiveContai import { api, type Analytics, type Stats, type AnalyticsCiOutcomes, type AnalyticsComparison, type AnalyticsCounts, type AnalyticsPeriod } from "@/lib/api"; import { CardSkeleton, ChartSkeleton } from "@/components/skeleton"; import { StatGrid, StatTile } from "@/components/stat-tile"; -import { DataTable, type Column } from "@/components/data-table"; import { Problem } from "@/components/problem"; import { Tabs } from "@/components/tabs"; import { useSearchParams } from "next/navigation"; import { Segmented } from "@/components/segmented"; import { Callout } from "@/components/callout"; -import { focusRing, inputClass } from "@/components/ui"; +import { inputClass } from "@/components/ui"; import { Page, PageHeader, Section } from "@/components/page"; import { RepoFilter, formatDuration } from "@/components/list"; - -// Categorical slots for the dark chart surface, checked for color-vision -// separation and contrast (blue, orange). Text never takes a series color. -const SERIES = { first: "#3987e5", second: "#d95926" }; +import { ChartCard, ChartTip, SERIES, Table, axis, delta, shortDay } from "@/components/charts"; const PERIODS: { value: `${AnalyticsPeriod}`; label: string }[] = [ { value: "7", label: "7 days" }, @@ -51,24 +47,6 @@ const totalTokens = (s: { tokens?: number; tokens_in: number; tokens_out: number const perPr = (s: { tokens?: number; tokens_in: number; tokens_out: number; prs_merged: number; tokens_per_merged_pr?: number | null }) => s.tokens_per_merged_pr ?? (s.prs_merged ? Math.round(totalTokens(s) / s.prs_merged) : null); -/** "+12% vs previous 30 days", or points for rates. Neutral ink: the reader judges. */ -function delta(cur: number | null, prev: number | null, kind: "count" | "rate" | "hours", vs: string): string { - if (cur == null || prev == null) return `— ${vs}`; - if (kind === "rate") { - const pts = Math.round((cur - prev) * 100); - return `${pts > 0 ? "▲ " : pts < 0 ? "▼ " : ""}${pts === 0 ? "No change" : `${Math.abs(pts)} pts`} ${vs}`; - } - if (prev === 0) return cur === 0 ? `No change ${vs}` : `New ${vs}`; - const change = Math.round(((cur - prev) / prev) * 100); - if (change === 0) return `No change ${vs}`; - return `${change > 0 ? "▲" : "▼"} ${Math.abs(change)}% ${vs}`; -} - -const shortDay = (day: string) => { - const d = new Date(`${day}T00:00:00Z`); - return d.toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" }); -}; - // ── Pieces ───────────────────────────────────────────────────────────────── /** One number: the shared stat tile, with the change in neutral ink (the reader judges). */ @@ -89,74 +67,6 @@ function RatingsTile({ up, down }: { up: number; down: number }) { ); } -function ChartCard({ title, children, table, actions }: { title: string; children: ReactNode; table: ReactNode; actions?: ReactNode }) { - const [showTable, setShowTable] = useState(false); - return ( -
-
-

{title}

- {actions &&
{actions}
} - -
- {showTable ?
{table}
: children} -
- ); -} - -function ChartTip({ active, payload, label, format }: { active?: boolean; payload?: { name: string; value: number; color: string }[]; label?: string; format?: (v: number) => string }) { - if (!active || !payload?.length) return null; - return ( -
-

{label ? shortDay(label) : ""}

- {payload.map((p) => ( -
-
- ))} -
- ); -} - -const axis = { stroke: "transparent", tick: { fill: "#71717a", fontSize: 11 }, tickLine: false, axisLine: false }; - -/** - * A table on the shared DataTable: the first column takes the spare width and - * wraps, numbers stay narrow, and a phone gets one card per row, so no column - * is ever pushed out of its card. `grow` marks other text columns that wrap. - */ -function Table({ head, rows, empty, label, grow = [] }: { head: string[]; rows: ReactNode[][]; empty: string; label: string; grow?: number[] }) { - const columns: Column[] = head.map((h, i) => ({ - key: `${i}-${h}`, - header: h, - cell: (r) => {r[i]}, - width: i === 0 || grow.includes(i) ? "grow" : "fit", - align: i === 0 || grow.includes(i) ? "left" : "right", - clamp: grow.includes(i), - })); - const table = ( - String(i)} - empty={

{empty}

} - /> - ); - // A wide table keeps a minimum width from sm: up and scrolls inside its own - // box, so no column squeezes a word in half; a phone gets one card per row. - if (head.length < 4) return table; - const min = head.length >= 7 ? "sm:min-w-[960px]" : head.length >= 5 ? "sm:min-w-[860px]" : "sm:min-w-[600px]"; - return ( -
-
{table}
-
- ); -} - function actorLabel(a: string) { return ({ reviewer: "Reviewer", planner: "Planner", coder: "Coding agent", people: "People in the dashboard" } as Record)[a] ?? a; } diff --git a/dashboard/src/app/settings/deliveries/page.tsx b/dashboard/src/app/settings/deliveries/page.tsx index 868d7e4c..f803fd98 100644 --- a/dashboard/src/app/settings/deliveries/page.tsx +++ b/dashboard/src/app/settings/deliveries/page.tsx @@ -5,6 +5,8 @@ import { RoleGuard } from "@/components/role-guard"; import { Page, PageHeader } from "@/components/page"; import { ListSkeleton, useListParams } from "@/components/list"; import { DEFAULT_RANGE, Deliveries } from "@/components/deliveries"; +import { DeliveryOverview } from "@/components/delivery-overview"; +import { Tabs } from "@/components/tabs"; const HEADER = ( -
{HEADER}
- set(patch, opts)} - openId={params.id} - onOpen={(id) => set({ id }, { replace: !id })} +
{HEADER}
+ + {overview ? ( + set(patch)} + /> + ) : ( + set(patch, opts)} + openId={params.id} + onOpen={(id) => set({ id }, { replace: !id })} + /> + )} ); } diff --git a/dashboard/src/components/charts.tsx b/dashboard/src/components/charts.tsx new file mode 100644 index 00000000..c6cb6429 --- /dev/null +++ b/dashboard/src/components/charts.tsx @@ -0,0 +1,100 @@ +"use client"; + +/** + * The chart pieces Insights, Analytics and Settings, Deliveries share: a card + * with a chart and its table, the tooltip, axis styling, the series colors, + * a table that turns into cards on a phone, and the change against the + * period before. + */ + +import { useState, type ReactNode } from "react"; +import { DataTable, type Column } from "./data-table"; +import { focusRing } from "./ui"; + +// Categorical slots for the dark chart surface, checked for color-vision +// separation and contrast (blue, orange). Text never takes a series color. +export const SERIES = { first: "#3987e5", second: "#d95926" }; + +/** "+12% vs previous 30 days", or points for rates. Neutral ink: the reader judges. */ +export function delta(cur: number | null, prev: number | null, kind: "count" | "rate" | "hours", vs: string): string { + if (cur == null || prev == null) return `— ${vs}`; + if (kind === "rate") { + const pts = Math.round((cur - prev) * 100); + return `${pts > 0 ? "▲ " : pts < 0 ? "▼ " : ""}${pts === 0 ? "No change" : `${Math.abs(pts)} pts`} ${vs}`; + } + if (prev === 0) return cur === 0 ? `No change ${vs}` : `New ${vs}`; + const change = Math.round(((cur - prev) / prev) * 100); + if (change === 0) return `No change ${vs}`; + return `${change > 0 ? "▲" : "▼"} ${Math.abs(change)}% ${vs}`; +} +export const shortDay = (day: string) => { + const d = new Date(`${day}T00:00:00Z`); + return d.toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" }); +}; +export function ChartCard({ title, children, table, actions }: { title: string; children: ReactNode; table: ReactNode; actions?: ReactNode }) { + const [showTable, setShowTable] = useState(false); + return ( +
+
+

{title}

+ {actions &&
{actions}
} + +
+ {showTable ?
{table}
: children} +
+ ); +} + +export function ChartTip({ active, payload, label, format, labelFormat = shortDay }: { active?: boolean; payload?: { name: string; value: number; color: string }[]; label?: string; format?: (v: number) => string; labelFormat?: (label: string) => string }) { + if (!active || !payload?.length) return null; + return ( +
+

{label ? labelFormat(label) : ""}

+ {payload.map((p) => ( +
+
+ ))} +
+ ); +} + +export const axis = { stroke: "transparent", tick: { fill: "#71717a", fontSize: 11 }, tickLine: false, axisLine: false }; + +/** + * A table on the shared DataTable: the first column takes the spare width and + * wraps, numbers stay narrow, and a phone gets one card per row, so no column + * is ever pushed out of its card. `grow` marks other text columns that wrap. + */ +export function Table({ head, rows, empty, label, grow = [] }: { head: string[]; rows: ReactNode[][]; empty: string; label: string; grow?: number[] }) { + const columns: Column[] = head.map((h, i) => ({ + key: `${i}-${h}`, + header: h, + cell: (r) => {r[i]}, + width: i === 0 || grow.includes(i) ? "grow" : "fit", + align: i === 0 || grow.includes(i) ? "left" : "right", + clamp: grow.includes(i), + })); + const table = ( + String(i)} + empty={

{empty}

} + /> + ); + // A wide table keeps a minimum width from sm: up and scrolls inside its own + // box, so no column squeezes a word in half; a phone gets one card per row. + if (head.length < 4) return table; + const min = head.length >= 7 ? "sm:min-w-[960px]" : head.length >= 5 ? "sm:min-w-[860px]" : "sm:min-w-[600px]"; + return ( +
+
{table}
+
+ ); +} diff --git a/dashboard/src/components/deliveries.tsx b/dashboard/src/components/deliveries.tsx index a2c2c048..8b41fa22 100644 --- a/dashboard/src/components/deliveries.tsx +++ b/dashboard/src/components/deliveries.tsx @@ -127,6 +127,24 @@ export interface DeliveryFilters { status: string; range: string; q: string; + /** One hour or day from the overview (RFC 3339, `until` exclusive); replaces `range`. */ + from?: string; + until?: string; + /** One webhook endpoint, or one failure reason, from the overview. */ + endpoint?: string; + reason?: string; +} + +/** "Oct 24, 10:00 to 11:00", or "Oct 24" for a whole day. */ +export function windowWords(from: string, until: string): string { + const a = new Date(from); + const b = new Date(until); + if (Number.isNaN(a.getTime()) || Number.isNaN(b.getTime())) return "the chosen time"; + const day = (d: Date) => d.toLocaleDateString(undefined, { month: "short", day: "numeric" }); + const time = (d: Date) => d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" }); + const hours = (b.getTime() - a.getTime()) / 3_600_000; + if (hours >= 23.5 && hours <= 24.5 && a.getHours() === 0) return day(a); + return `${day(a)}, ${time(a)} to ${time(b)}`; } // ── The list ──────────────────────────────────────────────────────── @@ -149,6 +167,10 @@ export function Deliveries({ const [error, setError] = useState(""); const [loading, setLoading] = useState(true); const { source, status, range, q } = filters; + const from = filters.from ?? ""; + const until = filters.until ?? ""; + const endpoint = filters.endpoint ?? ""; + const reason = filters.reason ?? ""; const load = useCallback(async () => { setLoading(true); @@ -156,8 +178,11 @@ export function Deliveries({ const r = await api.listDeliveries({ source: source === "all" ? undefined : source, status: status === "all" ? undefined : (status as DeliveryStatusFilter), - since: sinceFor(range), + since: from || sinceFor(range), + until: from ? until || undefined : undefined, q: q.trim() || undefined, + endpoint: endpoint || undefined, + reason: reason || undefined, limit: 200, }); setData(r); @@ -167,7 +192,7 @@ export function Deliveries({ } finally { setLoading(false); } - }, [source, status, range, q]); + }, [source, status, range, q, from, until, endpoint, reason]); useEffect(() => { void load(); @@ -187,8 +212,9 @@ export function Deliveries({ if (source !== "all") all.add(source); return [...all].sort((a, b) => sourceName(a).localeCompare(sourceName(b))); }, [data?.sources, source]); - const filtering = source !== "all" || status !== "all" || range !== DEFAULT_RANGE || !!q; - const clear = () => onFilters({ source: "all", status: "all", range: DEFAULT_RANGE, q: "" }); + const narrowed = !!from || !!endpoint || !!reason; + const filtering = source !== "all" || status !== "all" || range !== DEFAULT_RANGE || !!q || narrowed; + const clear = () => onFilters({ source: "all", status: "all", range: DEFAULT_RANGE, q: "", from: "", until: "", endpoint: "", reason: "" }); const retention = data?.retention_days ?? 14; return ( @@ -228,12 +254,23 @@ export function Deliveries({ ))} - onFilters({ range: v })}> - {RANGES.map((r) => ( - - ))} - + {!from && ( + onFilters({ range: v })}> + {RANGES.map((r) => ( + + ))} + + )} + {narrowed && ( +
+ {from && ( + onFilters({ from: "", until: "" })} testId="narrow-time" /> + )} + {endpoint && onFilters({ endpoint: "" })} testId="narrow-endpoint" />} + {reason && onFilters({ reason: "" })} testId="narrow-reason" />} +
+ )} )} @@ -275,6 +312,18 @@ export function Deliveries({ ); } +/** One narrowing from the overview, with a button that takes it off. */ +function NarrowChip({ label, onClear, testId }: { label: string; onClear: () => void; testId: string }) { + return ( + + {label} + + + ); +} + // ── Health ────────────────────────────────────────────────────────── function rateText(rate: number | null): string { diff --git a/dashboard/src/components/delivery-overview.tsx b/dashboard/src/components/delivery-overview.tsx new file mode 100644 index 00000000..75c82913 --- /dev/null +++ b/dashboard/src/components/delivery-overview.tsx @@ -0,0 +1,488 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useState } from "react"; +import { Bar, BarChart, CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts"; +import { endpointHref } from "@/lib/webhooks"; +import { api, type DeliveryAnalytics, type DeliveryEndpointRow, type DeliveryPeriod, type DeliveryPoint } from "@/lib/api"; +import { ChartCard, ChartTip, SERIES, Table, axis } from "./charts"; +import { Callout } from "./callout"; +import { FilterSelect } from "./data-source-activity"; +import { EmptyState } from "./empty-state"; +import { RepeatIcon } from "./icons"; +import { Chip, formatDate, formatMs, timeAgo, type Tone } from "./list"; +import { Section } from "./page"; +import { Problem } from "./problem"; +import { Segmented } from "./segmented"; +import { CardSkeleton, ChartSkeleton } from "./skeleton"; +import { StatGrid, StatTile } from "./stat-tile"; +import { buttonClass, focusRing } from "./ui"; +import { sourceName } from "./deliveries"; + +// ── Words ─────────────────────────────────────────────────────────── + +export const PERIODS: { value: DeliveryPeriod; label: string; vs: string }[] = [ + { value: "24h", label: "24 hours", vs: "the previous 24 hours" }, + { value: "7d", label: "7 days", vs: "the previous 7 days" }, + { value: "30d", label: "30 days", vs: "the previous 30 days" }, +]; + +/** The status choices the overview offers: the list's, less Retrying (a retry counts once it finishes). */ +const STATUSES = [ + { value: "all", label: "All" }, + { value: "failed", label: "Failed" }, + { value: "handled", label: "Handled" }, + { value: "ignored", label: "Ignored" }, +] as const; + +const count = (v: number) => v.toLocaleString(); + +export function rateText(rate: number | null | undefined): string { + if (rate == null) return "None yet"; + const pct = rate * 100; + return `${pct >= 99.95 || pct === 0 ? pct.toFixed(0) : pct.toFixed(1)}%`; +} + +const msText = (ms: number | null | undefined) => (ms == null ? "Not timed" : formatMs(ms)); + +/** The change against the period before, in words: "12% more than the previous 7 days". */ +export function changeWords(cur: number | null, prev: number | null, kind: "count" | "rate" | "latency", vs: string): string { + if (cur == null || prev == null) return `Nothing to compare with ${vs}`; + if (kind === "rate") { + const pts = Math.round((cur - prev) * 1000) / 10; + if (pts === 0) return `Same as ${vs}`; + return `${Math.abs(pts)} pts ${pts > 0 ? "higher" : "lower"} than ${vs}`; + } + if (prev === 0) return cur === 0 ? `Same as ${vs}` : `None in ${vs}`; + const change = Math.round(((cur - prev) / prev) * 100); + if (change === 0) return `Same as ${vs}`; + if (kind === "latency") return `${Math.abs(change)}% ${change > 0 ? "slower" : "faster"} than ${vs}`; + return `${Math.abs(change)}% ${change > 0 ? "more" : "fewer"} than ${vs}`; +} + +/** A bucket's label on the axis: "14:00" by hour, "Oct 24" by day. */ +function bucketLabel(iso: string, hourly: boolean): string { + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return iso; + return hourly + ? d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" }) + : d.toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" }); +} + +export interface OverviewFilters { + period: string; + source: string; + status: string; + endpoint: string; +} + +/** The Deliveries list, narrowed: every chart element links to one of these. */ +export function listHref(f: { source?: string; status?: string; from?: string; until?: string; endpoint?: string; reason?: string; q?: string }): string { + const q = new URLSearchParams(); + for (const [k, v] of Object.entries(f)) if (v && v !== "all") q.set(k, v); + const s = q.toString(); + return `/settings/deliveries/${s ? `?${s}` : ""}`; +} + +function endpointName(e: DeliveryEndpointRow): string { + if (e.description) return e.description; + if (e.url) { + try { + return new URL(e.url).host; + } catch { + return e.url; + } + } + return e.deleted ? "Deleted endpoint" : e.id; +} + +function endpointState(e: DeliveryEndpointRow): { label: string; tone: Tone } { + if (e.deleted) return { label: "Deleted", tone: "muted" }; + if (!e.enabled) return e.disabled_reason === "failing" ? { label: "Off: kept failing", tone: "danger" } : { label: "Off", tone: "muted" }; + if (e.streak > 0) return { label: `Failing (${e.streak} in a row)`, tone: "danger" }; + return { label: "On", tone: "success" }; +} + +const textLink = `rounded text-zinc-100 underline-offset-2 hover:underline ${focusRing}`; + +// ── The overview ──────────────────────────────────────────────────── + +/** Settings, then Deliveries, then Overview: how deliveries went over a period, against the one before. */ +export function DeliveryOverview({ filters, onFilters }: { filters: OverviewFilters; onFilters: (patch: Partial) => void }) { + const period = (PERIODS.find((p) => p.value === filters.period)?.value ?? "7d") as DeliveryPeriod; + const status = (STATUSES.find((s) => s.value === filters.status)?.value ?? "all") as (typeof STATUSES)[number]["value"]; + const { source, endpoint } = filters; + const [data, setData] = useState(null); + const [error, setError] = useState(""); + const [loading, setLoading] = useState(true); + + const load = useCallback(async () => { + setLoading(true); + try { + const r = await api.getDeliveryAnalytics({ + period, + source: source === "all" ? undefined : source, + status: status === "all" ? undefined : status, + endpoint: endpoint || undefined, + }); + setData(r); + setError(""); + } catch (e) { + setError(e instanceof Error ? e.message : "The request failed."); + } finally { + setLoading(false); + } + }, [period, source, status, endpoint]); + + useEffect(() => { + void load(); + }, [load]); + + const filtering = source !== "all" || status !== "all" || !!endpoint; + const clear = () => onFilters({ source: "all", status: "all", endpoint: "" }); + const sources = [...new Set([...(data?.seen_sources ?? []), ...(source !== "all" ? [source] : [])])].sort((a, b) => sourceName(a).localeCompare(sourceName(b))); + + return ( +
+
+ ({ value: p.value, label: p.label }))} value={period} onChange={(v) => onFilters({ period: v })} /> + ({ value: s.value, label: s.label }))} value={status} onChange={(v) => onFilters({ status: v })} /> + onFilters({ source: v, endpoint: v === "all" || v === "webhook" ? endpoint : "" })}> + + {sources.map((s) => ( + + ))} + + {(data?.endpoints.length ?? 0) > 0 || endpoint ? ( + onFilters({ endpoint: v })}> + + {(data?.endpoints ?? []).map((e) => ( + + ))} + {endpoint && !data?.endpoints.some((e) => e.id === endpoint) && } + + ) : null} + {filtering && ( + + )} +
+ + {error ? ( +
+ void load()} details={error}> + Nothing was changed. Check your connection and try again. + +
+ ) : !data ? ( +
+
+ {[0, 1, 2, 3].map((i) => )} +
+ +
+ ) : ( +
+ +
+ )} +
+ ); +} + +function Body({ data, filters, filtering, onClear }: { data: DeliveryAnalytics; filters: OverviewFilters; filtering: boolean; onClear: () => void }) { + const router = useRouter(); + const s = data.summary; + const p = data.previous; + const vs = PERIODS.find((x) => x.value === data.period)?.vs ?? "the period before"; + const hourly = data.granularity === "hour"; + const base = { + source: filters.source, + status: filters.status, + endpoint: filters.endpoint, + }; + const whole = { ...base, from: data.from, until: data.to }; + const bucketHref = (pt: DeliveryPoint, extra: { status?: string } = {}) => listHref({ ...base, ...extra, from: pt.start, until: pt.end }); + const nothing = s.deliveries === 0 && p.deliveries === 0; + const span = `the last ${PERIODS.find((x) => x.value === data.period)?.label ?? data.period}`; + const olderThanRecords = data.period === "30d"; + + const notes = ( + <> + {!data.backfill.complete && ( +
+ + Deliveries from before this overview existed are still being added up, so these numbers grow for a few minutes. Reload to see the rest. + +
+ )} + + ); + + if (nothing) { + return ( + <> + {notes} +
+ {filtering ? ( + } title="No deliveries match these filters" onClear={onClear}> + Nothing with these filters finished in {span} or the period before. Try another source or status, or a longer period. + + ) : ( + } + title={`No deliveries in ${span}`} + action={Check your integrations} + > + This overview counts every webhook GitHub, Jira and your alerts send to Coderhelm, every event it relays, and every message it sends to your webhook endpoints, Slack, Teams or email. Counts appear as deliveries finish, and are kept for {data.kept_days} days. + + )} +
+ + ); + } + + const failedTone = s.failed > 0 ? "danger" : "neutral"; + const rateTone = s.success_rate == null ? "neutral" : s.success_rate >= 0.95 ? "success" : s.success_rate >= 0.8 ? "warning" : "danger"; + const series = data.series.map((pt) => ({ ...pt, label: pt.start, rate: pt.success_rate == null ? null : Math.round(pt.success_rate * 1000) / 10 })); + const maxReason = Math.max(1, ...data.reasons.map((r) => r.count)); + const tipLabel = (iso: string) => (hourly ? `${formatDate(iso, { time: true })}` : bucketLabel(iso, false)); + const open = (pt: DeliveryPoint | undefined, extra: { status?: string } = {}) => { + if (pt && (pt.deliveries > 0 || pt.previous_deliveries > 0)) router.push(bucketHref(pt, extra)); + }; + type Click = { activePayload?: { payload?: DeliveryPoint }[]; activeIndex?: number | string | null; activeTooltipIndex?: number | string | null }; + const clicked = (e: unknown): DeliveryPoint | undefined => { + const c = e as Click | null; + const i = Number(c?.activeTooltipIndex ?? c?.activeIndex); + return c?.activePayload?.[0]?.payload ?? (Number.isFinite(i) ? data.series[i] : undefined); + }; + + return ( + <> + {notes} +
+ + + + + + + {s.deliveries > 0 && s.deliveries < 20 && ( +

+ Only {count(s.deliveries)} {s.deliveries === 1 ? "delivery" : "deliveries"} in this period, so a single failure moves the success rate a lot. +

+ )} +
+ +
+ [ + {tipLabel(pt.start)}, + count(pt.ok), + pt.failed ? {count(pt.failed)} : "0", + count(pt.previous_deliveries), + ])} + empty="No deliveries." + /> + } + > +
+ + open(clicked(e))}> + + bucketLabel(v, hourly)} {...axis} minTickGap={24} /> + + } /> + + + + + +
+
+ [ + {tipLabel(pt.start)}, + rateText(pt.success_rate), + msText(pt.p95_ms), + ])} + empty="No deliveries." + /> + } + > + {series.every((x) => x.rate == null) ? ( +
Nothing finished in this period, so there is no rate to show.
+ ) : ( +
+ + open(clicked(e))}> + + bucketLabel(v, hourly)} {...axis} minTickGap={24} /> + Math.max(0, Math.floor(Math.min(min, 90) / 10) * 10), 100]} tickFormatter={(v: number) => `${v}%`} {...axis} /> + `${v}%`} />} /> + + + +
+ )} +
+
+ {olderThanRecords && ( +

+ Counts are kept {data.kept_days} days; each delivery's own record is kept {data.records_kept_days}, so a day older than that opens an empty list. +

+ )} + +
+ {data.reasons.length === 0 ? ( +

+ No failures in {span}. +

+ ) : ( +
    + {data.reasons.map((r) => ( +
  • + +
    +

    {r.message}

    + {count(r.count)} +
    +
  • + ))} +
+ )} +
+ + {data.endpoints.length > 0 && ( +
+ { + const st = endpointState(e); + return [ + + + {e.deleted ? ( + {endpointName(e)} + ) : ( + {endpointName(e)} + )} + {st.label} + + {e.url && e.description && {e.url}} + , + + {rateText(e.success_rate)} + + {e.deliveries ? `of ${count(e.deliveries)}` : "No deliveries"} + + , + msText(e.p95_ms), + e.last_failure_at ? ( + + {timeAgo(e.last_failure_at)} + {e.last_failure_message ? `: ${e.last_failure_message}` : ""} + + ) : ( + "None" + ), + ]; + })} + empty="No endpoints." + /> + + )} + +
+
+
[ + + {sourceName(r.source)} + + {r.direction === "inbound" ? "Received" : "Sent"} · slowest 5% {msText(r.p95_ms)} · {changeWords(r.deliveries, r.previous_deliveries, "count", vs)} + + , + count(r.deliveries), + rateText(r.success_rate), + ])} + empty={`No deliveries in ${span}.`} + /> + +
+
[ + + {e.event} + {sourceName(e.source)} + , + count(e.failed), + ])} + empty={`No failures in ${span}.`} + /> + + + + ); +} diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index a0d02f39..1d44e07b 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -1209,6 +1209,13 @@ export const api = { return request(`/api/deliveries${s ? `?${s}` : ""}`); }, getDelivery: (id: string) => request(`/api/deliveries/${encodeURIComponent(id)}`), + /** The Deliveries overview: counts per hour or day for a period, against the period before. */ + getDeliveryAnalytics: (f: DeliveryAnalyticsFilter = {}) => { + const q = new URLSearchParams(); + for (const [k, v] of Object.entries(f)) if (v !== undefined && v !== "" && v !== "all") q.set(k, String(v)); + const s = q.toString(); + return request(`/api/deliveries/analytics${s ? `?${s}` : ""}`); + }, redeliver: (id: string) => requestWithBody<{ message?: string }, { code?: string }>(`/api/deliveries/${encodeURIComponent(id)}/redeliver`, { method: "POST", body: "{}" }), @@ -3807,7 +3814,13 @@ export interface DeliveryFilter { status?: DeliveryStatusFilter; /** RFC 3339. */ since?: string; + /** RFC 3339, exclusive: with `since`, one hour or day of the overview. */ + until?: string; q?: string; + /** Only deliveries to this webhook endpoint. */ + endpoint?: string; + /** Only failures with this reason code. */ + reason?: string; limit?: number; } @@ -3877,6 +3890,112 @@ export interface DeliveryDetailReply { can_redeliver: boolean; } +export type DeliveryPeriod = "24h" | "7d" | "30d"; + +export interface DeliveryAnalyticsFilter { + period?: DeliveryPeriod; + source?: string; + /** Retrying deliveries count once they finish, so there is no `pending`. */ + status?: Exclude; + endpoint?: string; +} + +export interface DeliveryTotals { + deliveries: number; + handled: number; + ignored: number; + failed: number; + /** 0..1, or null with nothing finished. */ + success_rate: number | null; + retried: number; + retried_ok: number; + /** Null while a status filter is on. */ + retries: number | null; + p50_ms: number | null; + p95_ms: number | null; + p99_ms: number | null; +} + +export interface DeliveryPoint { + start: string; + end: string; + deliveries: number; + ok: number; + failed: number; + success_rate: number | null; + p95_ms: number | null; + previous_deliveries: number; +} + +export interface DeliverySourceRow { + source: string; + direction: "inbound" | "outbound"; + deliveries: number; + ok: number; + failed: number; + success_rate: number | null; + p95_ms: number | null; + previous_deliveries: number; + previous_success_rate: number | null; +} + +export interface DeliveryReasonRow { + code: string; + message: string; + fix: string; + count: number; + previous_count: number; + sources: string[]; +} + +export interface DeliveryEventRow { + event: string; + source: string; + failed: number; +} + +export interface DeliveryEndpointRow { + id: string; + url: string; + description: string; + deleted: boolean; + enabled: boolean; + /** "manual" or "failing"; empty while on. */ + disabled_reason: string; + deliveries: number; + ok: number; + failed: number; + success_rate: number | null; + p50_ms: number | null; + p95_ms: number | null; + streak: number; + last_failure_at: string | null; + last_failure_reason: string | null; + last_failure_message: string | null; + failing_since: string | null; + last_success_at: string | null; +} + +export interface DeliveryAnalytics { + period: DeliveryPeriod; + granularity: "hour" | "day"; + from: string; + to: string; + previous_from: string; + previous_to: string; + summary: DeliveryTotals; + previous: DeliveryTotals; + series: DeliveryPoint[]; + sources: DeliverySourceRow[]; + reasons: DeliveryReasonRow[]; + events: DeliveryEventRow[]; + endpoints: DeliveryEndpointRow[]; + seen_sources: string[]; + backfill: { complete: boolean }; + kept_days: number; + records_kept_days: number; +} + // ── Hybrid (self-hosted) ──────────────────────────────────────────────── export type HybridCheckStatus = "pass" | "fail" | "wait" | "todo";