perf(web): render stats page shell immediately with per-panel skeletons (#1022)

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
João Salavisa
2026-05-22 18:46:49 +01:00
committed by GitHub
parent b4a696a5e9
commit 6ba50ba51e
6 changed files with 744 additions and 321 deletions
+12 -133
View File
@@ -1,137 +1,13 @@
import { Card, CardContent, CardHeader } from "@kandev/ui/card";
import { Skeleton } from "@kandev/ui/skeleton";
function OverviewCardsSkeleton() {
return (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
{[...Array(4)].map((_, i) => (
<Card key={i} className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-24" />
</CardHeader>
<CardContent>
<Skeleton className="h-9 w-16 mb-2" />
<Skeleton className="h-4 w-32 mb-3" />
<Skeleton className="h-1.5 w-full" />
</CardContent>
</Card>
))}
</div>
);
}
function ChartsSkeleton() {
return (
<div className="grid gap-4 lg:grid-cols-3">
<Card className="rounded-sm lg:col-span-2">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-48" />
</CardHeader>
<CardContent>
<div className="space-y-3">
<div className="flex gap-2">
{[...Array(3)].map((_, i) => (
<Skeleton key={i} className="h-7 w-16" />
))}
</div>
<Skeleton className="h-32 w-full" />
<div className="flex justify-between">
<Skeleton className="h-3 w-16" />
<Skeleton className="h-3 w-16" />
</div>
</div>
</CardContent>
</Card>
<Card className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-32" />
</CardHeader>
<CardContent>
<div className="space-y-3">
{[...Array(3)].map((_, i) => (
<div key={i} className="flex justify-between">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-16" />
</div>
))}
</div>
</CardContent>
</Card>
</div>
);
}
function ActivitySkeleton() {
return (
<div className="grid gap-4 lg:grid-cols-2">
<Card className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-32" />
</CardHeader>
<CardContent>
<div className="space-y-2">
<Skeleton className="h-4 w-48 mb-2" />
<Skeleton className="h-24 w-full" />
<div className="flex items-center gap-2 mt-2">
<Skeleton className="h-3 w-8" />
{[...Array(5)].map((_, i) => (
<Skeleton key={i} className="h-2 w-2" />
))}
<Skeleton className="h-3 w-8" />
</div>
</div>
</CardContent>
</Card>
<Card className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-24" />
</CardHeader>
<CardContent>
<div className="space-y-3">
{[...Array(3)].map((_, i) => (
<div key={i}>
<div className="flex justify-between mb-1">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-8" />
</div>
<Skeleton className="h-1.5 w-full" />
</div>
))}
</div>
</CardContent>
</Card>
</div>
);
}
function RepositoriesSkeleton() {
return (
<Card className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-40" />
</CardHeader>
<CardContent>
<div className="grid gap-3 md:grid-cols-2">
{[...Array(4)].map((_, i) => (
<div key={i} className="rounded-sm border bg-muted/20 p-3">
<div className="flex justify-between mb-2">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-16" />
</div>
<div className="flex gap-3 mb-3">
<Skeleton className="h-3 w-16" />
<Skeleton className="h-3 w-20" />
<Skeleton className="h-3 w-16" />
</div>
<Skeleton className="h-3 w-full mb-2" />
<Skeleton className="h-3 w-full" />
</div>
))}
</div>
</CardContent>
</Card>
);
}
import {
ActivitySkeleton,
ChartsSkeleton,
OverviewCardsSkeleton,
RepoLeadersSkeleton,
RepositoriesSkeleton,
TopRepositoriesSkeleton,
WorkloadSkeleton,
} from "./stats-skeletons";
export default function StatsLoading() {
return (
@@ -156,6 +32,9 @@ export default function StatsLoading() {
<ChartsSkeleton />
<ActivitySkeleton />
<RepositoriesSkeleton />
<TopRepositoriesSkeleton />
<RepoLeadersSkeleton />
<WorkloadSkeleton />
</div>
</div>
</div>
+4 -13
View File
@@ -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 (
<StatsPageClient stats={stats} error={error} workspaceId={workspaceId} activeRange={range} />
);
return <StatsPageClient workspaceId={workspaceId} activeRange={range} initialError={error} />;
}
+214 -175
View File
@@ -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 (
<PageTopbar
title="Statistics"
icon={<IconChartBar className="h-4 w-4" />}
subtitle={`${global.total_tasks} tasks · ${global.total_sessions} sessions · ${formatDuration(global.total_duration_ms)}`}
subtitle={getSubtitle(global, hasError)}
actions={
<>
<ToggleGroup
@@ -115,7 +99,7 @@ function StatsHeader({ global, range, copied, onRangeChange, onCopy }: StatsHead
variant="outline"
className="h-7"
>
{(["week", "month", "all"] as RangeKey[]).map((key) => (
{RANGE_KEYS.map((key) => (
<ToggleGroupItem
key={key}
value={key}
@@ -131,6 +115,7 @@ function StatsHeader({ global, range, copied, onRangeChange, onCopy }: StatsHead
size="sm"
className="h-7 px-2 text-xs cursor-pointer"
onClick={onCopy}
disabled={copyDisabled}
>
{copied ? "Copied" : "Copy Stats"}
</Button>
@@ -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 (
<div id={id} className="flex items-center gap-3 pt-2 scroll-mt-24">
@@ -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 (
<Card className="rounded-sm">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">{title}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">{message}</p>
</CardContent>
</Card>
);
}
function TelemetryPanels({ state, rangeLabel }: { state: PanelState; rangeLabel: string }) {
if (state.kind === "loading") {
return (
<>
<div id="completed" className="scroll-mt-24">
<ChartsSkeleton />
</div>
<div id="activity" className="scroll-mt-24">
<ActivitySkeleton />
</div>
</>
);
}
if (state.kind === "error") {
return (
<>
<div id="completed" className="scroll-mt-24">
<ErrorPanel title="Completed Tasks Over Time" message={state.message} />
</div>
<div id="activity" className="scroll-mt-24">
<ErrorPanel title="Activity" message={state.message} />
</div>
</>
);
}
const { stats } = state;
return (
<>
<div id="completed" className="scroll-mt-24">
@@ -173,7 +184,7 @@ function TelemetrySection({
</CardTitle>
</CardHeader>
<CardContent>
<CompletedTasksChart completedActivity={completedActivity} />
<CompletedTasksChart completedActivity={stats.completed_activity} />
</CardContent>
</Card>
<Card className="rounded-sm">
@@ -183,7 +194,7 @@ function TelemetrySection({
</CardTitle>
</CardHeader>
<CardContent>
<MostProductiveSummary completedActivity={completedActivity} />
<MostProductiveSummary completedActivity={stats.completed_activity} />
</CardContent>
</Card>
</div>
@@ -196,7 +207,7 @@ function TelemetrySection({
</CardTitle>
</CardHeader>
<CardContent>
<ActivityHeatmap dailyActivity={dailyActivity} />
<ActivityHeatmap dailyActivity={stats.daily_activity} />
</CardContent>
</Card>
<Card className="rounded-sm">
@@ -204,7 +215,7 @@ function TelemetrySection({
<CardTitle className="text-sm font-medium text-muted-foreground">Top Agents</CardTitle>
</CardHeader>
<CardContent>
<AgentUsageList agentUsage={agentUsage} />
<AgentUsageList agentUsage={stats.agent_usage} />
</CardContent>
</Card>
</div>
@@ -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 <OverviewCardsSkeleton />;
if (state.kind === "error") return <ErrorPanel title="Overview" message={state.message} />;
return <OverviewCards global={state.stats.global} git_stats={state.stats.git_stats} />;
}
function renderRepositoryActivityPanel(state: PanelState) {
if (state.kind === "loading") return <RepositoriesSkeleton />;
if (state.kind === "error")
return <ErrorPanel title="Repository Activity" message={state.message} />;
return (
<Card id="repositories" className="rounded-sm scroll-mt-24">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Repository Activity
</CardTitle>
</CardHeader>
<CardContent>
<RepositoryStatsGrid repositoryStats={state.stats.repository_stats} />
</CardContent>
</Card>
);
}
function renderTopRepositoriesPanel(state: PanelState) {
if (state.kind === "loading") return <TopRepositoriesSkeleton />;
if (state.kind === "error")
return <ErrorPanel title="Top Repositories" message={state.message} />;
return (
<Card className="rounded-sm">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Top Repositories
</CardTitle>
</CardHeader>
<CardContent>
<TopRepositories repositoryStats={state.stats.repository_stats} />
</CardContent>
</Card>
);
}
function renderRepoLeadersPanel(state: PanelState) {
if (state.kind === "loading") return <RepoLeadersSkeleton />;
if (state.kind === "error") return <ErrorPanel title="Repo Leaders" message={state.message} />;
return (
<Card className="rounded-sm">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Repo Leaders</CardTitle>
</CardHeader>
<CardContent>
<RepoLeaders repositoryStats={state.stats.repository_stats} />
</CardContent>
</Card>
);
}
function renderWorkloadPanel(state: PanelState) {
if (state.kind === "loading") return <WorkloadSkeleton />;
if (state.kind === "error") return <ErrorPanel title="Workload" message={state.message} />;
return <WorkloadSection task_stats={state.stats.task_stats} />;
}
function StatsContent({
state,
rangeLabel,
workspaceId,
}: {
state: PanelState;
rangeLabel: string;
workspaceId?: string;
}) {
return (
<div className="flex-1 overflow-auto">
<div className="max-w-7xl mx-auto p-6">
<div className="space-y-5">
<OverviewCards global={global} git_stats={git_stats} />
{renderOverviewPanel(state)}
<SectionDivider id="telemetry" label="Telemetry" />
<TelemetrySection
completedActivity={completed_activity}
dailyActivity={daily_activity}
agentUsage={agent_usage}
rangeLabel={rangeLabel}
/>
<Card id="repositories" className="rounded-sm scroll-mt-24">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Repository Activity
</CardTitle>
</CardHeader>
<CardContent>
<RepositoryStatsGrid repositoryStats={repository_stats} />
</CardContent>
</Card>
<Card className="rounded-sm">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Top Repositories
</CardTitle>
</CardHeader>
<CardContent>
<TopRepositories repositoryStats={repository_stats} />
</CardContent>
</Card>
<Card className="rounded-sm">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Repo Leaders
</CardTitle>
</CardHeader>
<CardContent>
<RepoLeaders repositoryStats={repository_stats} />
</CardContent>
</Card>
<TelemetryPanels state={state} rangeLabel={rangeLabel} />
{renderRepositoryActivityPanel(state)}
{renderTopRepositoriesPanel(state)}
{renderRepoLeadersPanel(state)}
<SectionDivider id="github" label="GitHub" />
<PRStatsPanel workspaceId={workspaceId ?? null} />
<SectionDivider id="workload" label="Workload" />
<WorkloadSection task_stats={task_stats} />
{renderWorkloadPanel(state)}
</div>
</div>
</div>
);
}
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 <StatsEmptyState message="Select a workspace to view statistics." />;
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 (
<div className="h-screen w-full flex flex-col bg-background">
<PageTopbar title="Statistics" icon={<IconChartBar className="h-4 w-4" />} />
<div className="flex-1 flex items-center justify-center">
<p className="text-destructive">Error loading stats: {error}</p>
<p className="text-destructive">Error loading stats: {initialError}</p>
</div>
</div>
);
if (!stats) return <StatsEmptyState message="No stats available." />;
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 <StatsEmptyState message="Select a workspace to view statistics." />;
return (
<div className="h-screen w-full flex flex-col bg-background">
<StatsHeader
global={resolvedStats.global}
global={stats?.global ?? null}
range={range}
copied={copied}
copyDisabled={!stats}
hasError={Boolean(fetchError)}
onRangeChange={handleRangeChange}
onCopy={handleCopyStats}
/>
<StatsContent
resolvedStats={resolvedStats}
rangeLabel={rangeLabel}
workspaceId={workspaceId}
/>
<StatsContent state={panelState} rangeLabel={rangeLabel} workspaceId={workspaceId} />
</div>
);
}
+216
View File
@@ -0,0 +1,216 @@
import { Card, CardContent, CardHeader } from "@kandev/ui/card";
import { Skeleton } from "@kandev/ui/skeleton";
export function OverviewCardsSkeleton() {
return (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
{[...Array(4)].map((_, i) => (
<Card key={i} className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-24" />
</CardHeader>
<CardContent>
<Skeleton className="h-9 w-16 mb-2" />
<Skeleton className="h-4 w-32 mb-3" />
<Skeleton className="h-1.5 w-full" />
</CardContent>
</Card>
))}
</div>
);
}
export function ChartsSkeleton() {
return (
<div className="grid gap-4 lg:grid-cols-3">
<Card className="rounded-sm lg:col-span-2">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-48" />
</CardHeader>
<CardContent>
<div className="space-y-3">
<div className="flex gap-2">
{[...Array(3)].map((_, i) => (
<Skeleton key={i} className="h-7 w-16" />
))}
</div>
<Skeleton className="h-32 w-full" />
<div className="flex justify-between">
<Skeleton className="h-3 w-16" />
<Skeleton className="h-3 w-16" />
</div>
</div>
</CardContent>
</Card>
<Card className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-32" />
</CardHeader>
<CardContent>
<div className="space-y-3">
{[...Array(3)].map((_, i) => (
<div key={i} className="flex justify-between">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-16" />
</div>
))}
</div>
</CardContent>
</Card>
</div>
);
}
export function ActivitySkeleton() {
return (
<div className="grid gap-4 lg:grid-cols-2">
<Card className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-32" />
</CardHeader>
<CardContent>
<div className="space-y-2">
<Skeleton className="h-4 w-48 mb-2" />
<Skeleton className="h-24 w-full" />
<div className="flex items-center gap-2 mt-2">
<Skeleton className="h-3 w-8" />
{[...Array(5)].map((_, i) => (
<Skeleton key={i} className="h-2 w-2" />
))}
<Skeleton className="h-3 w-8" />
</div>
</div>
</CardContent>
</Card>
<Card className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-24" />
</CardHeader>
<CardContent>
<div className="space-y-3">
{[...Array(3)].map((_, i) => (
<div key={i}>
<div className="flex justify-between mb-1">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-8" />
</div>
<Skeleton className="h-1.5 w-full" />
</div>
))}
</div>
</CardContent>
</Card>
</div>
);
}
export function RepositoriesSkeleton() {
return (
<Card className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-40" />
</CardHeader>
<CardContent>
<div className="grid gap-3 md:grid-cols-2">
{[...Array(4)].map((_, i) => (
<div key={i} className="rounded-sm border bg-muted/20 p-3">
<div className="flex justify-between mb-2">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-16" />
</div>
<div className="flex gap-3 mb-3">
<Skeleton className="h-3 w-16" />
<Skeleton className="h-3 w-20" />
<Skeleton className="h-3 w-16" />
</div>
<Skeleton className="h-3 w-full mb-2" />
<Skeleton className="h-3 w-full" />
</div>
))}
</div>
</CardContent>
</Card>
);
}
function RankedListSkeleton({ columns }: { columns: number }) {
return (
<div
className="grid gap-4"
style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
>
{[...Array(columns)].map((_, colIdx) => (
<div key={colIdx}>
<Skeleton className="h-3 w-24 mb-3" />
<div className="space-y-2">
{[...Array(3)].map((_, i) => (
<div key={i} className="flex items-center gap-3">
<Skeleton className="h-3 w-3" />
<Skeleton className="h-4 flex-1" />
<Skeleton className="h-4 w-12" />
</div>
))}
</div>
</div>
))}
</div>
);
}
export function TopRepositoriesSkeleton() {
return (
<Card className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-32" />
</CardHeader>
<CardContent>
<RankedListSkeleton columns={2} />
</CardContent>
</Card>
);
}
export function RepoLeadersSkeleton() {
return (
<Card className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-32" />
</CardHeader>
<CardContent>
<RankedListSkeleton columns={3} />
</CardContent>
</Card>
);
}
export function WorkloadSkeleton() {
return (
<div className="grid gap-4 lg:grid-cols-2">
{[...Array(2)].map((_, idx) => (
<Card key={idx} className="rounded-sm">
<CardHeader className="pb-2">
<Skeleton className="h-4 w-32 mb-1" />
<Skeleton className="h-3 w-40" />
</CardHeader>
<CardContent>
<div className="space-y-3">
{[...Array(3)].map((_, i) => (
<div key={i} className="flex items-center gap-3">
<Skeleton className="h-3 w-3" />
<div className="flex-1 space-y-1">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-3 w-32" />
</div>
<div className="space-y-1 text-right">
<Skeleton className="h-4 w-16" />
<Skeleton className="h-3 w-20" />
</div>
</div>
))}
</div>
</CardContent>
</Card>
))}
</div>
);
}
+198
View File
@@ -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");
});
});
+100
View File
@@ -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");
}