From 6ba50ba51efd0cbb0723e766d3f03d67fd8faa84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Salavisa?= Date: Fri, 22 May 2026 18:46:49 +0100 Subject: [PATCH] perf(web): render stats page shell immediately with per-panel skeletons (#1022) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * perf(web): render stats page shell immediately with per-panel skeletons The stats route previously blocked the full SSR response on the workspace stats query, leaving the user staring at a blank loading screen for the entire round-trip. Drop the server-side stats fetch (server still resolves the workspace id, which is cheap) and move the stats request to the client. The header, range toggle, and every panel render their shell on mount, with each panel showing its own skeleton until data arrives. Range changes also re-show the skeletons during the refetch instead of staling the previous data. Co-Authored-By: Claude Opus 4.7 * fix(web): address PR review feedback on stats page lazy-loading - Drop unused `loading` flag from stats reducer (Claude) - Show "Failed to load stats" subtitle on fetch error instead of stale "Loading stats…" text (Claude, cubic) - Read live `range` from useSearchParams() and validate against the RangeKey union so skeletons reset immediately on toggle and invalid ?range values fall back to "month" (Claude, CodeRabbit) - Render an error panel per section instead of perpetual skeletons when the stats fetch fails (Greptile) - Use router.replace with scroll:false on range toggle to avoid re-running the server component for a URL-only change Co-Authored-By: Claude Opus 4.7 * test(web): extract stats pure helpers into stats-utils + unit tests - Move statsReducer, isRangeKey, getRangeLabel, formatDuration, getSubtitle, toPanelState, and buildStatsSummary into apps/web/app/stats/stats-utils.ts so the testable units are reachable outside the client component - Add apps/web/app/stats/stats-utils.test.ts covering reducer transitions, range-key validation, subtitle branching, panel-state derivation, and the summary builder - Switch useStatsData from a cancellation flag to AbortController so fast range toggles actually abort the in-flight fetchStats request instead of letting stale requests run to completion Addresses Claude review blocker + suggestion on PR #1022. Co-Authored-By: Claude Opus 4.7 * refactor(web): tighten stats lazy-loading per Claude suggestions - loading.tsx now includes TopRepositoriesSkeleton, RepoLeadersSkeleton, and WorkloadSkeleton so a cold navigation to /stats shows the full page layout, not a layout that ends at Repository Activity - Reuse the existing StatsRange union for RangeKey in stats-utils.ts (one type alias, no risk of drift) - Drop the unreachable default arm in getRangeLabel so a future RangeKey addition triggers a TypeScript exhaustiveness error Co-Authored-By: Claude Opus 4.7 --------- Co-authored-by: Kandev Agent Co-authored-by: Claude Opus 4.7 --- apps/web/app/stats/loading.tsx | 145 +-------- apps/web/app/stats/page.tsx | 17 +- apps/web/app/stats/stats-page-client.tsx | 389 +++++++++++++---------- apps/web/app/stats/stats-skeletons.tsx | 216 +++++++++++++ apps/web/app/stats/stats-utils.test.ts | 198 ++++++++++++ apps/web/app/stats/stats-utils.ts | 100 ++++++ 6 files changed, 744 insertions(+), 321 deletions(-) create mode 100644 apps/web/app/stats/stats-skeletons.tsx create mode 100644 apps/web/app/stats/stats-utils.test.ts create mode 100644 apps/web/app/stats/stats-utils.ts diff --git a/apps/web/app/stats/loading.tsx b/apps/web/app/stats/loading.tsx index 1a8be70dca..5ef46c2560 100644 --- a/apps/web/app/stats/loading.tsx +++ b/apps/web/app/stats/loading.tsx @@ -1,137 +1,13 @@ -import { Card, CardContent, CardHeader } from "@kandev/ui/card"; import { Skeleton } from "@kandev/ui/skeleton"; - -function OverviewCardsSkeleton() { - return ( -
- {[...Array(4)].map((_, i) => ( - - - - - - - - - - - ))} -
- ); -} - -function ChartsSkeleton() { - return ( -
- - - - - -
-
- {[...Array(3)].map((_, i) => ( - - ))} -
- -
- - -
-
-
-
- - - - - -
- {[...Array(3)].map((_, i) => ( -
- - -
- ))} -
-
-
-
- ); -} - -function ActivitySkeleton() { - return ( -
- - - - - -
- - -
- - {[...Array(5)].map((_, i) => ( - - ))} - -
-
-
-
- - - - - -
- {[...Array(3)].map((_, i) => ( -
-
- - -
- -
- ))} -
-
-
-
- ); -} - -function RepositoriesSkeleton() { - return ( - - - - - -
- {[...Array(4)].map((_, i) => ( -
-
- - -
-
- - - -
- - -
- ))} -
-
-
- ); -} +import { + ActivitySkeleton, + ChartsSkeleton, + OverviewCardsSkeleton, + RepoLeadersSkeleton, + RepositoriesSkeleton, + TopRepositoriesSkeleton, + WorkloadSkeleton, +} from "./stats-skeletons"; export default function StatsLoading() { return ( @@ -156,6 +32,9 @@ export default function StatsLoading() { + + + diff --git a/apps/web/app/stats/page.tsx b/apps/web/app/stats/page.tsx index bfc3dd3aa0..da5c0540f6 100644 --- a/apps/web/app/stats/page.tsx +++ b/apps/web/app/stats/page.tsx @@ -1,4 +1,4 @@ -import { fetchStats, type StatsRange } from "@/lib/api/domains/stats-api"; +import type { StatsRange } from "@/lib/api/domains/stats-api"; import { fetchUserSettings } from "@/lib/api/domains/settings-api"; import { listWorkspaces } from "@/lib/api"; import { StatsPageClient } from "./stats-page-client"; @@ -10,14 +10,12 @@ type StatsPageProps = { }; export default async function StatsPage({ searchParams }: StatsPageProps) { - let stats = null; - let error = null; let workspaceId: string | undefined; + let error: string | null = null; const params = searchParams ? await searchParams : undefined; const range = params?.range; try { - // Get user settings to find active workspace const [userSettingsResponse, workspacesResponse] = await Promise.all([ fetchUserSettings({ cache: "no-store" }), listWorkspaces({ cache: "no-store" }), @@ -26,17 +24,10 @@ export default async function StatsPage({ searchParams }: StatsPageProps) { const settingsWorkspaceId = userSettingsResponse?.settings?.workspace_id; const workspaces = workspacesResponse?.workspaces ?? []; - // Find active workspace: user setting > first workspace workspaceId = workspaces.find((w) => w.id === settingsWorkspaceId)?.id ?? workspaces[0]?.id; - - if (workspaceId) { - stats = await fetchStats(workspaceId, { cache: "no-store" }, range); - } } catch (e) { - error = e instanceof Error ? e.message : "Failed to fetch stats"; + error = e instanceof Error ? e.message : "Failed to resolve workspace"; } - return ( - - ); + return ; } diff --git a/apps/web/app/stats/stats-page-client.tsx b/apps/web/app/stats/stats-page-client.tsx index fa3a994c23..61eb26c52b 100644 --- a/apps/web/app/stats/stats-page-client.tsx +++ b/apps/web/app/stats/stats-page-client.tsx @@ -5,10 +5,11 @@ import { Button } from "@kandev/ui/button"; import { PageTopbar } from "@/components/page-topbar"; import { ToggleGroup, ToggleGroupItem } from "@kandev/ui/toggle-group"; import type { StatsResponse } from "@/lib/types/http"; -import { useMemo } from "react"; +import { useCallback, useEffect, useMemo, useReducer } from "react"; import { useRouter, useSearchParams } from "next/navigation"; import { IconChartBar } from "@tabler/icons-react"; import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard"; +import { fetchStats } from "@/lib/api/domains/stats-api"; import { OverviewCards, WorkloadSection, @@ -22,61 +23,34 @@ import { CompletedTasksChart, MostProductiveSummary, } from "./stats-charts"; +import { + ActivitySkeleton, + ChartsSkeleton, + OverviewCardsSkeleton, + RepoLeadersSkeleton, + RepositoriesSkeleton, + TopRepositoriesSkeleton, + WorkloadSkeleton, +} from "./stats-skeletons"; import { PRStatsPanel } from "@/components/github/pr-stats"; +import { + buildStatsSummary, + DEFAULT_RANGE, + getRangeLabel, + getSubtitle, + isRangeKey, + type PanelState, + RANGE_KEYS, + type RangeKey, + type StatsState, + statsReducer, + toPanelState, +} from "./stats-utils"; interface StatsPageClientProps { - stats: StatsResponse | null; - error: string | null; workspaceId?: string; activeRange?: RangeKey; -} - -const EMPTY_STATS: StatsResponse = { - global: { - total_tasks: 0, - completed_tasks: 0, - in_progress_tasks: 0, - total_sessions: 0, - total_turns: 0, - total_messages: 0, - total_user_messages: 0, - total_tool_calls: 0, - total_duration_ms: 0, - avg_turns_per_task: 0, - avg_messages_per_task: 0, - avg_duration_ms_per_task: 0, - }, - task_stats: [], - daily_activity: [], - completed_activity: [], - agent_usage: [], - repository_stats: [], - git_stats: { total_commits: 0, total_files_changed: 0, total_insertions: 0, total_deletions: 0 }, -}; - -function formatDuration(ms: number): string { - if (ms === 0) return "—"; - const seconds = Math.floor(ms / 1000); - const minutes = Math.floor(seconds / 60); - const hours = Math.floor(minutes / 60); - if (hours > 0) return `${hours}h ${minutes % 60}m`; - if (minutes > 0) return `${minutes}m ${seconds % 60}s`; - return `${seconds}s`; -} - -type RangeKey = "week" | "month" | "all"; - -function getRangeLabel(range: RangeKey): string { - switch (range) { - case "week": - return "Last Week"; - case "month": - return "Last Month"; - case "all": - return "All Time"; - default: - return "Last Month"; - } + initialError?: string | null; } function StatsEmptyState({ message }: { message: string }) { @@ -91,19 +65,29 @@ function StatsEmptyState({ message }: { message: string }) { } type StatsHeaderProps = { - global: StatsResponse["global"]; + global: StatsResponse["global"] | null; range: RangeKey; copied: boolean; + copyDisabled: boolean; + hasError: boolean; onRangeChange: (r: RangeKey) => void; onCopy: () => void; }; -function StatsHeader({ global, range, copied, onRangeChange, onCopy }: StatsHeaderProps) { +function StatsHeader({ + global, + range, + copied, + copyDisabled, + hasError, + onRangeChange, + onCopy, +}: StatsHeaderProps) { return ( } - subtitle={`${global.total_tasks} tasks · ${global.total_sessions} sessions · ${formatDuration(global.total_duration_ms)}`} + subtitle={getSubtitle(global, hasError)} actions={ <> - {(["week", "month", "all"] as RangeKey[]).map((key) => ( + {RANGE_KEYS.map((key) => ( {copied ? "Copied" : "Copy Stats"} @@ -140,8 +125,6 @@ function StatsHeader({ global, range, copied, onRangeChange, onCopy }: StatsHead ); } -type StatsContentProps = { resolvedStats: StatsResponse; rangeLabel: string; workspaceId?: string }; - function SectionDivider({ id, label }: { id: string; label: string }) { return (
@@ -151,17 +134,45 @@ function SectionDivider({ id, label }: { id: string; label: string }) { ); } -function TelemetrySection({ - completedActivity, - dailyActivity, - agentUsage, - rangeLabel, -}: { - completedActivity: StatsResponse["completed_activity"]; - dailyActivity: StatsResponse["daily_activity"]; - agentUsage: StatsResponse["agent_usage"]; - rangeLabel: string; -}) { +function ErrorPanel({ title, message }: { title: string; message: string }) { + return ( + + + {title} + + +

{message}

+
+
+ ); +} + +function TelemetryPanels({ state, rangeLabel }: { state: PanelState; rangeLabel: string }) { + if (state.kind === "loading") { + return ( + <> +
+ +
+
+ +
+ + ); + } + if (state.kind === "error") { + return ( + <> +
+ +
+
+ +
+ + ); + } + const { stats } = state; return ( <>
@@ -173,7 +184,7 @@ function TelemetrySection({ - + @@ -183,7 +194,7 @@ function TelemetrySection({ - +
@@ -196,7 +207,7 @@ function TelemetrySection({ - + @@ -204,7 +215,7 @@ function TelemetrySection({ Top Agents - +
@@ -212,151 +223,179 @@ function TelemetrySection({ ); } -function StatsContent({ resolvedStats, rangeLabel, workspaceId }: StatsContentProps) { - const { - global, - task_stats, - completed_activity, - daily_activity, - agent_usage, - repository_stats, - git_stats, - } = resolvedStats; +function renderOverviewPanel(state: PanelState) { + if (state.kind === "loading") return ; + if (state.kind === "error") return ; + return ; +} + +function renderRepositoryActivityPanel(state: PanelState) { + if (state.kind === "loading") return ; + if (state.kind === "error") + return ; + return ( + + + + Repository Activity + + + + + + + ); +} + +function renderTopRepositoriesPanel(state: PanelState) { + if (state.kind === "loading") return ; + if (state.kind === "error") + return ; + return ( + + + + Top Repositories + + + + + + + ); +} + +function renderRepoLeadersPanel(state: PanelState) { + if (state.kind === "loading") return ; + if (state.kind === "error") return ; + return ( + + + Repo Leaders + + + + + + ); +} + +function renderWorkloadPanel(state: PanelState) { + if (state.kind === "loading") return ; + if (state.kind === "error") return ; + return ; +} + +function StatsContent({ + state, + rangeLabel, + workspaceId, +}: { + state: PanelState; + rangeLabel: string; + workspaceId?: string; +}) { return (
- + {renderOverviewPanel(state)} - - - - - Repository Activity - - - - - - - - - - Top Repositories - - - - - - - - - - Repo Leaders - - - - - - + + {renderRepositoryActivityPanel(state)} + {renderTopRepositoriesPanel(state)} + {renderRepoLeadersPanel(state)} - + {renderWorkloadPanel(state)}
); } -function buildStatsSummary( - resolvedStats: StatsResponse, - rangeLabel: string, - completedInRange: number, -): string { - const { global, repository_stats, git_stats } = resolvedStats; - const completion = - global.total_tasks > 0 - ? `${Math.round((global.completed_tasks / global.total_tasks) * 100)}%` - : "—"; - const topRepo = repository_stats - .filter((r) => r.total_tasks > 0) - .sort((a, b) => b.total_tasks - a.total_tasks)[0]; - const topRepoLabel = topRepo ? `${topRepo.repository_name} (${topRepo.total_tasks} tasks)` : "—"; - const hasGitStats = - git_stats && (git_stats.total_commits > 0 || git_stats.total_files_changed > 0); - const gitLine = hasGitStats - ? `${git_stats.total_commits} commits, +${git_stats.total_insertions.toLocaleString()}/-${git_stats.total_deletions.toLocaleString()}` - : "no git activity"; - return [ - `*Kandev Stats — ${rangeLabel}*`, - `- Tasks: ${global.total_tasks} total (${global.completed_tasks} done, ${global.in_progress_tasks} in progress) · ${completion} completion`, - `- Completed (${rangeLabel}): ${completedInRange}`, - `- Time: ${formatDuration(global.total_duration_ms)} total · ${formatDuration(global.avg_duration_ms_per_task)} avg/task`, - `- Repos: ${repository_stats.length} tracked · Top repo: ${topRepoLabel}`, - `- Git: ${gitLine}`, - ].join("\n"); +function useStatsData(workspaceId: string | undefined, range: RangeKey): StatsState { + const [state, dispatch] = useReducer(statsReducer, { stats: null, error: null }); + + useEffect(() => { + if (!workspaceId) return; + const controller = new AbortController(); + dispatch({ type: "fetch" }); + fetchStats(workspaceId, { cache: "no-store", init: { signal: controller.signal } }, range) + .then((data) => { + if (!controller.signal.aborted) dispatch({ type: "success", stats: data }); + }) + .catch((e: unknown) => { + if (controller.signal.aborted) return; + const message = e instanceof Error ? e.message : "Failed to fetch stats"; + dispatch({ type: "failure", error: message }); + }); + return () => { + controller.abort(); + }; + }, [workspaceId, range]); + + return state; } -export function StatsPageClient({ stats, error, workspaceId, activeRange }: StatsPageClientProps) { +export function StatsPageClient({ workspaceId, activeRange, initialError }: StatsPageClientProps) { const router = useRouter(); const searchParams = useSearchParams(); const { copied, copy } = useCopyToClipboard(); - const range = (activeRange ?? "month") as RangeKey; + + const rawRange = searchParams?.get("range") ?? activeRange; + const range: RangeKey = isRangeKey(rawRange) ? rawRange : DEFAULT_RANGE; const rangeLabel = getRangeLabel(range); - const resolvedStats = stats ?? EMPTY_STATS; + + const { stats, error: fetchError } = useStatsData(workspaceId, range); + const panelState = toPanelState(stats, fetchError); const completedInRange = useMemo( - () => - (resolvedStats.completed_activity ?? []).reduce((sum, item) => sum + item.completed_tasks, 0), - [resolvedStats.completed_activity], + () => (stats?.completed_activity ?? []).reduce((sum, item) => sum + item.completed_tasks, 0), + [stats?.completed_activity], ); const statsSummary = useMemo( - () => buildStatsSummary(resolvedStats, rangeLabel, completedInRange), - [resolvedStats, rangeLabel, completedInRange], + () => (stats ? buildStatsSummary(stats, rangeLabel, completedInRange) : ""), + [stats, rangeLabel, completedInRange], ); - if (!workspaceId) return ; - if (error) + const handleCopyStats = useCallback(() => { + if (statsSummary) void copy(statsSummary); + }, [copy, statsSummary]); + + const handleRangeChange = useCallback( + (nextRange: RangeKey) => { + const params = new URLSearchParams(searchParams?.toString() ?? ""); + params.set("range", nextRange); + router.replace(`/stats?${params.toString()}`, { scroll: false }); + }, + [router, searchParams], + ); + + if (initialError) return (
} />
-

Error loading stats: {error}

+

Error loading stats: {initialError}

); - if (!stats) return ; - - const handleCopyStats = () => { - void copy(statsSummary); - }; - - const handleRangeChange = (nextRange: RangeKey) => { - const params = new URLSearchParams(searchParams?.toString() ?? ""); - params.set("range", nextRange); - router.push(`/stats?${params.toString()}`); - }; + if (!workspaceId) return ; return (
- +
); } diff --git a/apps/web/app/stats/stats-skeletons.tsx b/apps/web/app/stats/stats-skeletons.tsx new file mode 100644 index 0000000000..f4bcc29fe6 --- /dev/null +++ b/apps/web/app/stats/stats-skeletons.tsx @@ -0,0 +1,216 @@ +import { Card, CardContent, CardHeader } from "@kandev/ui/card"; +import { Skeleton } from "@kandev/ui/skeleton"; + +export function OverviewCardsSkeleton() { + return ( +
+ {[...Array(4)].map((_, i) => ( + + + + + + + + + + + ))} +
+ ); +} + +export function ChartsSkeleton() { + return ( +
+ + + + + +
+
+ {[...Array(3)].map((_, i) => ( + + ))} +
+ +
+ + +
+
+
+
+ + + + + +
+ {[...Array(3)].map((_, i) => ( +
+ + +
+ ))} +
+
+
+
+ ); +} + +export function ActivitySkeleton() { + return ( +
+ + + + + +
+ + +
+ + {[...Array(5)].map((_, i) => ( + + ))} + +
+
+
+
+ + + + + +
+ {[...Array(3)].map((_, i) => ( +
+
+ + +
+ +
+ ))} +
+
+
+
+ ); +} + +export function RepositoriesSkeleton() { + return ( + + + + + +
+ {[...Array(4)].map((_, i) => ( +
+
+ + +
+
+ + + +
+ + +
+ ))} +
+
+
+ ); +} + +function RankedListSkeleton({ columns }: { columns: number }) { + return ( +
+ {[...Array(columns)].map((_, colIdx) => ( +
+ +
+ {[...Array(3)].map((_, i) => ( +
+ + + +
+ ))} +
+
+ ))} +
+ ); +} + +export function TopRepositoriesSkeleton() { + return ( + + + + + + + + + ); +} + +export function RepoLeadersSkeleton() { + return ( + + + + + + + + + ); +} + +export function WorkloadSkeleton() { + return ( +
+ {[...Array(2)].map((_, idx) => ( + + + + + + +
+ {[...Array(3)].map((_, i) => ( +
+ +
+ + +
+
+ + +
+
+ ))} +
+
+
+ ))} +
+ ); +} diff --git a/apps/web/app/stats/stats-utils.test.ts b/apps/web/app/stats/stats-utils.test.ts new file mode 100644 index 0000000000..78d92880f6 --- /dev/null +++ b/apps/web/app/stats/stats-utils.test.ts @@ -0,0 +1,198 @@ +import { describe, it, expect } from "vitest"; +import type { StatsResponse } from "@/lib/types/http"; +import { + buildStatsSummary, + formatDuration, + getRangeLabel, + getSubtitle, + isRangeKey, + statsReducer, + toPanelState, +} from "./stats-utils"; + +const emptyGlobal: StatsResponse["global"] = { + total_tasks: 0, + completed_tasks: 0, + in_progress_tasks: 0, + total_sessions: 0, + total_turns: 0, + total_messages: 0, + total_user_messages: 0, + total_tool_calls: 0, + total_duration_ms: 0, + avg_turns_per_task: 0, + avg_messages_per_task: 0, + avg_duration_ms_per_task: 0, +}; + +const sampleStats: StatsResponse = { + global: { + ...emptyGlobal, + total_tasks: 10, + completed_tasks: 4, + in_progress_tasks: 2, + total_sessions: 7, + total_duration_ms: 3_725_000, + avg_duration_ms_per_task: 372_500, + }, + task_stats: [], + daily_activity: [], + completed_activity: [], + agent_usage: [], + repository_stats: [ + { + repository_id: "r1", + repository_name: "kandev", + total_tasks: 6, + completed_tasks: 3, + in_progress_tasks: 1, + session_count: 5, + turn_count: 30, + message_count: 60, + user_message_count: 25, + tool_call_count: 40, + total_duration_ms: 1_000_000, + total_commits: 12, + total_files_changed: 30, + total_insertions: 1200, + total_deletions: 800, + }, + ], + git_stats: { + total_commits: 12, + total_files_changed: 30, + total_insertions: 1200, + total_deletions: 800, + }, +}; + +describe("isRangeKey", () => { + it("accepts the three valid keys", () => { + expect(isRangeKey("week")).toBe(true); + expect(isRangeKey("month")).toBe(true); + expect(isRangeKey("all")).toBe(true); + }); + + it("rejects null, undefined, and unknown strings", () => { + expect(isRangeKey(null)).toBe(false); + expect(isRangeKey(undefined)).toBe(false); + expect(isRangeKey("")).toBe(false); + expect(isRangeKey("day")).toBe(false); + expect(isRangeKey("MONTH")).toBe(false); + }); +}); + +describe("getRangeLabel", () => { + it("returns the friendly label for each range", () => { + expect(getRangeLabel("week")).toBe("Last Week"); + expect(getRangeLabel("month")).toBe("Last Month"); + expect(getRangeLabel("all")).toBe("All Time"); + }); +}); + +describe("formatDuration", () => { + it("renders an em-dash for zero", () => { + expect(formatDuration(0)).toBe("—"); + }); + + it("formats seconds, minutes, and hours", () => { + expect(formatDuration(45_000)).toBe("45s"); + expect(formatDuration(125_000)).toBe("2m 5s"); + expect(formatDuration(3_725_000)).toBe("1h 2m"); + }); +}); + +describe("getSubtitle", () => { + it("renders the summary when stats are available", () => { + expect(getSubtitle(sampleStats.global, false)).toBe("10 tasks · 7 sessions · 1h 2m"); + }); + + it("shows the loading message while the fetch is in flight", () => { + expect(getSubtitle(null, false)).toBe("Loading stats…"); + }); + + it("shows the error message when the fetch has failed", () => { + expect(getSubtitle(null, true)).toBe("Failed to load stats"); + }); + + it("prefers stats over the error flag once data arrives", () => { + expect(getSubtitle(sampleStats.global, true)).toBe("10 tasks · 7 sessions · 1h 2m"); + }); +}); + +describe("statsReducer", () => { + const initial = { stats: null, error: null }; + + it("fetch action clears stats and error", () => { + const stale = { stats: sampleStats, error: "previous" }; + expect(statsReducer(stale, { type: "fetch" })).toEqual({ stats: null, error: null }); + }); + + it("success stores stats and clears any prior error", () => { + const errored = { stats: null, error: "boom" }; + expect(statsReducer(errored, { type: "success", stats: sampleStats })).toEqual({ + stats: sampleStats, + error: null, + }); + }); + + it("failure stores the error and clears stats", () => { + const loaded = { stats: sampleStats, error: null }; + expect(statsReducer(loaded, { type: "failure", error: "nope" })).toEqual({ + stats: null, + error: "nope", + }); + }); + + it("does not return the same reference as the input", () => { + const next = statsReducer(initial, { type: "fetch" }); + expect(next).not.toBe(initial); + }); +}); + +describe("toPanelState", () => { + it("returns loading when neither stats nor error is set", () => { + expect(toPanelState(null, null)).toEqual({ kind: "loading" }); + }); + + it("returns ready when stats are available", () => { + expect(toPanelState(sampleStats, null)).toEqual({ kind: "ready", stats: sampleStats }); + }); + + it("returns error when an error is present", () => { + expect(toPanelState(null, "boom")).toEqual({ kind: "error", message: "boom" }); + }); + + it("prefers error over stale stats so panels never linger in a ready+error mix", () => { + expect(toPanelState(sampleStats, "boom")).toEqual({ kind: "error", message: "boom" }); + }); +}); + +describe("buildStatsSummary", () => { + it("includes completion %, top repo, and git line", () => { + const summary = buildStatsSummary(sampleStats, "Last Month", 4); + expect(summary).toContain("*Kandev Stats — Last Month*"); + expect(summary).toContain("10 total (4 done, 2 in progress) · 40% completion"); + expect(summary).toContain("Completed (Last Month): 4"); + expect(summary).toContain("Top repo: kandev (6 tasks)"); + expect(summary).toContain("12 commits, +1,200/-800"); + }); + + it("falls back to em-dash and no-git when there is no activity", () => { + const empty: StatsResponse = { + ...sampleStats, + global: emptyGlobal, + repository_stats: [], + git_stats: { + total_commits: 0, + total_files_changed: 0, + total_insertions: 0, + total_deletions: 0, + }, + }; + const summary = buildStatsSummary(empty, "All Time", 0); + expect(summary).toContain("Top repo: —"); + expect(summary).toContain("Git: no git activity"); + expect(summary).toContain("0 total (0 done, 0 in progress) · — completion"); + }); +}); diff --git a/apps/web/app/stats/stats-utils.ts b/apps/web/app/stats/stats-utils.ts new file mode 100644 index 0000000000..cb5e6b26f9 --- /dev/null +++ b/apps/web/app/stats/stats-utils.ts @@ -0,0 +1,100 @@ +import type { StatsRange } from "@/lib/api/domains/stats-api"; +import type { StatsResponse } from "@/lib/types/http"; + +export type RangeKey = StatsRange; + +export const RANGE_KEYS = ["week", "month", "all"] as const satisfies readonly RangeKey[]; +export const DEFAULT_RANGE: RangeKey = "month"; + +export function isRangeKey(value: string | null | undefined): value is RangeKey { + return value === "week" || value === "month" || value === "all"; +} + +export function getRangeLabel(range: RangeKey): string { + switch (range) { + case "week": + return "Last Week"; + case "month": + return "Last Month"; + case "all": + return "All Time"; + } +} + +export function formatDuration(ms: number): string { + if (ms === 0) return "—"; + const seconds = Math.floor(ms / 1000); + const minutes = Math.floor(seconds / 60); + const hours = Math.floor(minutes / 60); + if (hours > 0) return `${hours}h ${minutes % 60}m`; + if (minutes > 0) return `${minutes}m ${seconds % 60}s`; + return `${seconds}s`; +} + +export function getSubtitle(global: StatsResponse["global"] | null, hasError: boolean): string { + if (global) { + return `${global.total_tasks} tasks · ${global.total_sessions} sessions · ${formatDuration(global.total_duration_ms)}`; + } + return hasError ? "Failed to load stats" : "Loading stats…"; +} + +export type StatsState = { + stats: StatsResponse | null; + error: string | null; +}; + +export type StatsAction = + | { type: "fetch" } + | { type: "success"; stats: StatsResponse } + | { type: "failure"; error: string }; + +export function statsReducer(state: StatsState, action: StatsAction): StatsState { + switch (action.type) { + case "fetch": + return { stats: null, error: null }; + case "success": + return { stats: action.stats, error: null }; + case "failure": + return { stats: null, error: action.error }; + } +} + +export type PanelState = + | { kind: "loading" } + | { kind: "error"; message: string } + | { kind: "ready"; stats: StatsResponse }; + +export function toPanelState(stats: StatsResponse | null, error: string | null): PanelState { + if (error) return { kind: "error", message: error }; + if (stats) return { kind: "ready", stats }; + return { kind: "loading" }; +} + +export function buildStatsSummary( + resolvedStats: StatsResponse, + rangeLabel: string, + completedInRange: number, +): string { + const { global, repository_stats, git_stats } = resolvedStats; + const completion = + global.total_tasks > 0 + ? `${Math.round((global.completed_tasks / global.total_tasks) * 100)}%` + : "—"; + const topRepo = repository_stats + .filter((r) => r.total_tasks > 0) + .sort((a, b) => b.total_tasks - a.total_tasks)[0]; + const topRepoLabel = topRepo ? `${topRepo.repository_name} (${topRepo.total_tasks} tasks)` : "—"; + const hasGitStats = + git_stats && (git_stats.total_commits > 0 || git_stats.total_files_changed > 0); + const gitLine = hasGitStats + ? `${git_stats.total_commits} commits, +${git_stats.total_insertions.toLocaleString()}/-${git_stats.total_deletions.toLocaleString()}` + : "no git activity"; + return [ + `*Kandev Stats — ${rangeLabel}*`, + `- Tasks: ${global.total_tasks} total (${global.completed_tasks} done, ${global.in_progress_tasks} in progress) · ${completion} completion`, + `- Completed (${rangeLabel}): ${completedInRange}`, + `- Time: ${formatDuration(global.total_duration_ms)} total · ${formatDuration(global.avg_duration_ms_per_task)} avg/task`, + `- Repos: ${repository_stats.length} tracked · Top repo: ${topRepoLabel}`, + `- Git: ${gitLine}`, + ].join("\n"); +}