ST-1216: Insights sprint-widget — token KPI-kaartjes & per-job tabel (#114)
* feat(ST-vmc7vpps): lib/insights/token-stats.ts — sprint KPI + per-job query SQL-queries voor totale tokens/kosten (KPI) en per-job tabel met ModelPrice JOIN. Guard op lege sprintId. Tests voor empty guard, KPI-mapping en null token-data. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(ST-vmc7vpps): TokenUsageCard — KPI-kaartjes + sorteerbare per-job tabel Client-component met drie KPI-strips (totaal tokens, kosten USD, gem. per job) en sorteerbare tabel op kosten of duur. Nulls als '—', MD3-tokens, geen hardcoded kleuren. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(ST-vmc7vpps): insights page — TokenUsageCard integreren Voeg getTokenStats + TokenUsageCard imports toe aan insights/page.tsx. tokenStats apart awaiten na activeSprints (kan niet in dezelfde Promise.all). TokenUsageCard-sectie toegevoegd na AgentThroughputCard. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
b147f813d4
commit
a2c8bd41af
4 changed files with 318 additions and 0 deletions
67
__tests__/lib/insights/token-stats.test.ts
Normal file
67
__tests__/lib/insights/token-stats.test.ts
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const { mockQueryRaw } = vi.hoisted(() => ({ mockQueryRaw: vi.fn() }))
|
||||
|
||||
vi.mock('@/lib/prisma', () => ({
|
||||
prisma: { $queryRaw: mockQueryRaw },
|
||||
}))
|
||||
|
||||
import { getTokenStats } from '@/lib/insights/token-stats'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('getTokenStats', () => {
|
||||
it('returns empty result for empty sprintId', async () => {
|
||||
const result = await getTokenStats('user-1', '')
|
||||
|
||||
expect(result.kpi.totalTokens).toBe(0)
|
||||
expect(result.kpi.totalCostUsd).toBe(0)
|
||||
expect(result.kpi.avgCostPerJob).toBe(0)
|
||||
expect(result.kpi.jobCount).toBe(0)
|
||||
expect(result.jobs).toHaveLength(0)
|
||||
expect(mockQueryRaw).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('maps kpi rows correctly', async () => {
|
||||
const kpiRows = [{ total_tokens: BigInt(10000), total_cost: 0.15, avg_cost: 0.05, job_count: BigInt(3) }]
|
||||
const jobRows: unknown[] = []
|
||||
mockQueryRaw.mockResolvedValueOnce(kpiRows).mockResolvedValueOnce(jobRows)
|
||||
|
||||
const result = await getTokenStats('user-1', 'sprint-1')
|
||||
|
||||
expect(result.kpi.totalTokens).toBe(10000)
|
||||
expect(result.kpi.totalCostUsd).toBe(0.15)
|
||||
expect(result.kpi.avgCostPerJob).toBe(0.05)
|
||||
expect(result.kpi.jobCount).toBe(3)
|
||||
})
|
||||
|
||||
it('maps job rows and handles null token data', async () => {
|
||||
const kpiRows = [{ total_tokens: BigInt(0), total_cost: null, avg_cost: null, job_count: BigInt(0) }]
|
||||
const jobRows = [
|
||||
{
|
||||
job_id: 'job-1',
|
||||
task_title: 'My Task',
|
||||
idea_code: null,
|
||||
model_id: 'claude-sonnet-4-6',
|
||||
input_tokens: null,
|
||||
output_tokens: null,
|
||||
cache_read_tokens: null,
|
||||
cache_write_tokens: null,
|
||||
cost_usd: null,
|
||||
duration_seconds: 42,
|
||||
},
|
||||
]
|
||||
mockQueryRaw.mockResolvedValueOnce(kpiRows).mockResolvedValueOnce(jobRows)
|
||||
|
||||
const result = await getTokenStats('user-1', 'sprint-1')
|
||||
|
||||
expect(result.jobs).toHaveLength(1)
|
||||
const job = result.jobs[0]
|
||||
expect(job.jobId).toBe('job-1')
|
||||
expect(job.taskTitle).toBe('My Task')
|
||||
expect(job.costUsd).toBeNull()
|
||||
expect(job.durationSeconds).toBe(42)
|
||||
})
|
||||
})
|
||||
109
app/(app)/insights/components/token-usage.tsx
Normal file
109
app/(app)/insights/components/token-usage.tsx
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
'use client'
|
||||
|
||||
import { useState, useMemo } from 'react'
|
||||
import type { TokenKpi, TokenJobRow } from '@/lib/insights/token-stats'
|
||||
|
||||
export interface TokenUsageCardProps {
|
||||
kpi: TokenKpi
|
||||
jobs: TokenJobRow[]
|
||||
}
|
||||
|
||||
type SortKey = 'cost' | 'duration'
|
||||
|
||||
function fmt(n: number | null, decimals = 0): string {
|
||||
if (n === null) return '—'
|
||||
return n.toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals })
|
||||
}
|
||||
|
||||
function fmtCost(n: number | null): string {
|
||||
if (n === null) return '—'
|
||||
return '$' + n.toFixed(4)
|
||||
}
|
||||
|
||||
function jobLabel(job: TokenJobRow): string {
|
||||
const label = job.taskTitle ?? job.ideaCode ?? job.jobId
|
||||
return label.length > 40 ? label.slice(0, 37) + '…' : label
|
||||
}
|
||||
|
||||
export function TokenUsageCard({ kpi, jobs }: TokenUsageCardProps) {
|
||||
const [sortKey, setSortKey] = useState<SortKey>('cost')
|
||||
|
||||
const sorted = useMemo(() => {
|
||||
return [...jobs].sort((a, b) => {
|
||||
if (sortKey === 'cost') return (b.costUsd ?? -Infinity) - (a.costUsd ?? -Infinity)
|
||||
return (b.durationSeconds ?? -Infinity) - (a.durationSeconds ?? -Infinity)
|
||||
})
|
||||
}, [jobs, sortKey])
|
||||
|
||||
if (kpi.jobCount === 0) {
|
||||
return <p className="text-muted-foreground">Geen token-data</p>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* KPI strip */}
|
||||
<div className="flex gap-6">
|
||||
<div>
|
||||
<div className="text-2xl font-semibold text-foreground">
|
||||
{kpi.totalTokens.toLocaleString()}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">Totaal tokens</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-semibold text-foreground">
|
||||
${kpi.totalCostUsd.toFixed(4)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">Kosten (USD)</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-semibold text-foreground">
|
||||
{kpi.avgCostPerJob ? '$' + kpi.avgCostPerJob.toFixed(4) : '—'}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">Gem. per job</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sortable table */}
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-muted text-muted-foreground text-xs uppercase tracking-wide">
|
||||
<th className="py-2 pr-3 text-left font-medium">Taak</th>
|
||||
<th className="py-2 pr-3 text-left font-medium">Model</th>
|
||||
<th className="py-2 pr-3 text-right font-medium">Input</th>
|
||||
<th className="py-2 pr-3 text-right font-medium">Output</th>
|
||||
<th className="py-2 pr-3 text-right font-medium">Cache-R</th>
|
||||
<th className="py-2 pr-3 text-right font-medium">Cache-W</th>
|
||||
<th
|
||||
className={`py-2 pr-3 text-right font-medium cursor-pointer select-none ${sortKey === 'cost' ? 'text-primary' : ''}`}
|
||||
onClick={() => setSortKey('cost')}
|
||||
>
|
||||
Kosten (USD) {sortKey === 'cost' ? '▾' : ''}
|
||||
</th>
|
||||
<th
|
||||
className={`py-2 text-right font-medium cursor-pointer select-none ${sortKey === 'duration' ? 'text-primary' : ''}`}
|
||||
onClick={() => setSortKey('duration')}
|
||||
>
|
||||
Duur (s) {sortKey === 'duration' ? '▾' : ''}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sorted.map(job => (
|
||||
<tr key={job.jobId} className="border-b border-border last:border-0">
|
||||
<td className="py-2 pr-3 text-foreground max-w-48 truncate">{jobLabel(job)}</td>
|
||||
<td className="py-2 pr-3 text-muted-foreground whitespace-nowrap">{job.modelId ?? '—'}</td>
|
||||
<td className="py-2 pr-3 text-right tabular-nums">{fmt(job.inputTokens)}</td>
|
||||
<td className="py-2 pr-3 text-right tabular-nums">{fmt(job.outputTokens)}</td>
|
||||
<td className="py-2 pr-3 text-right tabular-nums">{fmt(job.cacheReadTokens)}</td>
|
||||
<td className="py-2 pr-3 text-right tabular-nums">{fmt(job.cacheWriteTokens)}</td>
|
||||
<td className="py-2 pr-3 text-right tabular-nums">{fmtCost(job.costUsd)}</td>
|
||||
<td className="py-2 text-right tabular-nums">{fmt(job.durationSeconds, 1)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import { getBurndownData } from '@/lib/insights/burndown'
|
|||
import { getSprintStatusBreakdown } from '@/lib/insights/sprint-status'
|
||||
import { getVerifyResultStats, getAlignmentTrend } from '@/lib/insights/verify-stats'
|
||||
import { getJobsPerDay } from '@/lib/insights/agent-throughput'
|
||||
import { getTokenStats } from '@/lib/insights/token-stats'
|
||||
import { getVelocity } from '@/lib/insights/velocity'
|
||||
import { getBacklogHealth } from '@/lib/insights/backlog-health'
|
||||
import { SprintInfoStrip } from './components/sprint-info-strip'
|
||||
|
|
@ -15,6 +16,7 @@ import { SprintStatusDonut } from './components/sprint-status-donut'
|
|||
import { PlanQualityCard } from './components/plan-quality'
|
||||
import { AlignmentTrend } from './components/alignment-trend'
|
||||
import { AgentThroughputCard } from './components/agent-throughput'
|
||||
import { TokenUsageCard } from './components/token-usage'
|
||||
import { VelocityChart } from './components/velocity-chart'
|
||||
import { BacklogHealthCard } from './components/backlog-health'
|
||||
|
||||
|
|
@ -76,6 +78,11 @@ export default async function InsightsPage({ searchParams }: InsightsPageProps)
|
|||
getBacklogHealth(userId),
|
||||
])
|
||||
|
||||
const activeSprintId = activeSprints.find(s => s.product.id === filterProductId)?.id ?? ''
|
||||
const tokenStats = await (activeSprints.length > 0 && filterProductId
|
||||
? getTokenStats(userId, activeSprintId)
|
||||
: Promise.resolve({ kpi: { totalTokens: 0, totalCostUsd: 0, avgCostPerJob: 0, jobCount: 0 }, jobs: [] }))
|
||||
|
||||
// Date.now is an impure call but used once per request — safe in a Server Component.
|
||||
// eslint-disable-next-line react-hooks/purity
|
||||
const nowMs = Date.now()
|
||||
|
|
@ -142,6 +149,12 @@ export default async function InsightsPage({ searchParams }: InsightsPageProps)
|
|||
/>
|
||||
</section>
|
||||
|
||||
{/* Token usage */}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-lg font-medium text-foreground">Token gebruik</h2>
|
||||
<TokenUsageCard kpi={tokenStats.kpi} jobs={tokenStats.jobs} />
|
||||
</section>
|
||||
|
||||
{/* Velocity */}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-lg font-medium text-foreground">Velocity</h2>
|
||||
|
|
|
|||
129
lib/insights/token-stats.ts
Normal file
129
lib/insights/token-stats.ts
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
export interface TokenKpi {
|
||||
totalTokens: number
|
||||
totalCostUsd: number
|
||||
avgCostPerJob: number
|
||||
jobCount: number
|
||||
}
|
||||
|
||||
export interface TokenJobRow {
|
||||
jobId: string
|
||||
taskTitle: string | null
|
||||
ideaCode: string | null
|
||||
modelId: string | null
|
||||
inputTokens: number | null
|
||||
outputTokens: number | null
|
||||
cacheReadTokens: number | null
|
||||
cacheWriteTokens: number | null
|
||||
costUsd: number | null
|
||||
durationSeconds: number | null
|
||||
}
|
||||
|
||||
export interface TokenStatsResult {
|
||||
kpi: TokenKpi
|
||||
jobs: TokenJobRow[]
|
||||
}
|
||||
|
||||
type RawKpiRow = {
|
||||
total_tokens: bigint
|
||||
total_cost: number | null
|
||||
avg_cost: number | null
|
||||
job_count: bigint
|
||||
}
|
||||
|
||||
type RawJobRow = {
|
||||
job_id: string
|
||||
task_title: string | null
|
||||
idea_code: string | null
|
||||
model_id: string | null
|
||||
input_tokens: number | null
|
||||
output_tokens: number | null
|
||||
cache_read_tokens: number | null
|
||||
cache_write_tokens: number | null
|
||||
cost_usd: number | null
|
||||
duration_seconds: number | null
|
||||
}
|
||||
|
||||
const EMPTY_KPI: TokenKpi = { totalTokens: 0, totalCostUsd: 0, avgCostPerJob: 0, jobCount: 0 }
|
||||
|
||||
export async function getTokenStats(userId: string, sprintId: string): Promise<TokenStatsResult> {
|
||||
if (!sprintId) return { kpi: EMPTY_KPI, jobs: [] }
|
||||
|
||||
const [kpiRows, jobRows] = await Promise.all([
|
||||
prisma.$queryRaw<RawKpiRow[]>`
|
||||
SELECT
|
||||
COALESCE(SUM(cj.input_tokens + cj.output_tokens + cj.cache_read_tokens + cj.cache_write_tokens), 0) AS total_tokens,
|
||||
SUM(
|
||||
cj.input_tokens * mp.input_price_per_1m / 1000000.0
|
||||
+ cj.output_tokens * mp.output_price_per_1m / 1000000.0
|
||||
+ cj.cache_read_tokens * mp.cache_read_price_per_1m / 1000000.0
|
||||
+ cj.cache_write_tokens * mp.cache_write_price_per_1m / 1000000.0
|
||||
) FILTER (WHERE cj.input_tokens IS NOT NULL) AS total_cost,
|
||||
AVG(
|
||||
cj.input_tokens * mp.input_price_per_1m / 1000000.0
|
||||
+ cj.output_tokens * mp.output_price_per_1m / 1000000.0
|
||||
+ cj.cache_read_tokens * mp.cache_read_price_per_1m / 1000000.0
|
||||
+ cj.cache_write_tokens * mp.cache_write_price_per_1m / 1000000.0
|
||||
) FILTER (WHERE cj.input_tokens IS NOT NULL) AS avg_cost,
|
||||
COUNT(*) FILTER (WHERE cj.input_tokens IS NOT NULL) AS job_count
|
||||
FROM claude_jobs cj
|
||||
JOIN tasks t ON cj.task_id = t.id
|
||||
JOIN stories s ON t.story_id = s.id
|
||||
LEFT JOIN model_prices mp ON mp.model_id = cj.model_id
|
||||
WHERE cj.user_id = ${userId}
|
||||
AND s.sprint_id = ${sprintId}
|
||||
AND cj.status = 'DONE'
|
||||
`,
|
||||
prisma.$queryRaw<RawJobRow[]>`
|
||||
SELECT
|
||||
cj.id AS job_id,
|
||||
t.title AS task_title,
|
||||
i.code AS idea_code,
|
||||
cj.model_id,
|
||||
cj.input_tokens,
|
||||
cj.output_tokens,
|
||||
cj.cache_read_tokens,
|
||||
cj.cache_write_tokens,
|
||||
CASE WHEN cj.input_tokens IS NOT NULL THEN
|
||||
cj.input_tokens * mp.input_price_per_1m / 1000000.0
|
||||
+ cj.output_tokens * mp.output_price_per_1m / 1000000.0
|
||||
+ cj.cache_read_tokens * mp.cache_read_price_per_1m / 1000000.0
|
||||
+ cj.cache_write_tokens * mp.cache_write_price_per_1m / 1000000.0
|
||||
END AS cost_usd,
|
||||
EXTRACT(EPOCH FROM (cj.finished_at - cj.claimed_at)) AS duration_seconds
|
||||
FROM claude_jobs cj
|
||||
LEFT JOIN tasks t ON cj.task_id = t.id
|
||||
LEFT JOIN ideas i ON cj.idea_id = i.id
|
||||
LEFT JOIN stories s ON t.story_id = s.id
|
||||
LEFT JOIN model_prices mp ON mp.model_id = cj.model_id
|
||||
WHERE cj.user_id = ${userId}
|
||||
AND (s.sprint_id = ${sprintId} OR cj.idea_id IS NOT NULL)
|
||||
AND cj.status = 'DONE'
|
||||
ORDER BY cj.finished_at DESC
|
||||
`,
|
||||
])
|
||||
|
||||
const kpi = kpiRows[0]
|
||||
|
||||
return {
|
||||
kpi: {
|
||||
totalTokens: Number(kpi?.total_tokens ?? 0),
|
||||
totalCostUsd: Number(kpi?.total_cost ?? 0),
|
||||
avgCostPerJob: Number(kpi?.avg_cost ?? 0),
|
||||
jobCount: Number(kpi?.job_count ?? 0),
|
||||
},
|
||||
jobs: jobRows.map(r => ({
|
||||
jobId: r.job_id,
|
||||
taskTitle: r.task_title,
|
||||
ideaCode: r.idea_code,
|
||||
modelId: r.model_id,
|
||||
inputTokens: r.input_tokens,
|
||||
outputTokens: r.output_tokens,
|
||||
cacheReadTokens: r.cache_read_tokens,
|
||||
cacheWriteTokens: r.cache_write_tokens,
|
||||
costUsd: r.cost_usd != null ? Number(r.cost_usd) : null,
|
||||
durationSeconds: r.duration_seconds != null ? Number(r.duration_seconds) : null,
|
||||
})),
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue