Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ node_modules/
.DS_Store
test-results/
playwright-report/
docs/superpowers
2 changes: 2 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
bun run check
bun x tsc --noEmit
1 change: 1 addition & 0 deletions .husky/pre-push
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
bun test tests/unit
3 changes: 3 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"typecheck": "bun x tsc --noEmit",
"test": "bun test tests/unit",
"test:unit": "bun test tests/unit",
"test:e2e": "playwright test"
"test:e2e": "playwright test",
"prepare": "husky"
},
"dependencies": {
"@opencode-ai/plugin": "^1.4.7"
Expand All @@ -37,6 +38,7 @@
"@biomejs/biome": "^2.4.15",
"@playwright/test": "^1.59.1",
"@types/bun": "^1.3.13",
"husky": "^9.1.7",
"playwright": "^1.59.1"
}
}
4 changes: 4 additions & 0 deletions src/dashboard/routes/page-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export function createPageRoute(
const costSummary = dailyTokens.getCostSummary();
const daily = dailyTokens.getDailyTokens();
const dailyModel = dailyTokens.getDailyTokensByModel();
const dailyCost = dailyTokens.getDailyCost();
const dailyModelCost = dailyTokens.getDailyModelCost();
const toolGroups = repos.toolCalls.getToolUsageSummary();
return new Response(
renderHTML(
Expand All @@ -34,6 +36,8 @@ export function createPageRoute(
toolGroups,
directories,
dirFilter,
dailyCost,
dailyModelCost,
),
{
headers: { "Content-Type": "text/html; charset=utf-8" },
Expand Down
4 changes: 4 additions & 0 deletions src/dashboard/routes/stats-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ export function createStatsRoute(
const costSummary = dailyTokens.getCostSummary();
const daily = dailyTokens.getDailyTokens();
const dailyModel = dailyTokens.getDailyTokensByModel();
const dailyCost = dailyTokens.getDailyCost();
const dailyModelCost = dailyTokens.getDailyModelCost();
const toolGroups = repos.toolCalls.getToolUsageSummary();
const html = renderSessionsFragment(
sessions,
Expand All @@ -56,6 +58,8 @@ export function createStatsRoute(
toolGroups,
directories,
dirFilter,
dailyCost,
dailyModelCost,
);

cache.set(cacheKey, { html, expiry: now + CACHE_TTL_MS });
Expand Down
25 changes: 25 additions & 0 deletions src/dashboard/services/daily-tokens-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import type { DailyTokens } from "../../db/shared-types";
export interface DailyTokensService {
getDailyTokens(): DailyTokens[];
getDailyTokensByModel(): DailyModelTokens[];
getDailyCost(): DailyTokens[];
getDailyModelCost(): DailyModelTokens[];
getTokenSummary(): TokenSummary;
getCostSummary(): CostSummary;
}
Expand Down Expand Up @@ -38,6 +40,29 @@ export function createDailyTokensService(repos: Repos): DailyTokensService {
return repos.messages.getDailyTokensByModel();
},

getDailyCost(): DailyTokens[] {
const today = new Date().toISOString().slice(0, 10);
const todayRow = repos.messages.getTodayCost(today);
const historyRows = repos.dailyUsage.getHistoryUntilCost(today, 60);

const dataMap = new Map<string, number>();
for (const row of historyRows) dataMap.set(row.date, row.total);
dataMap.set(todayRow.date, todayRow.total);

const result: DailyTokens[] = [];
for (let i = 59; i >= 0; i--) {
const d = new Date();
d.setDate(d.getDate() - i);
const key = d.toISOString().slice(0, 10);
result.push({ date: key, total: dataMap.get(key) ?? 0 });
}
return result;
},

getDailyModelCost(): DailyModelTokens[] {
return repos.messages.getDailyModelCost();
},

getTokenSummary(): TokenSummary {
return repos.messages.getTokenSummary();
},
Expand Down
62 changes: 61 additions & 1 deletion src/dashboard/templates/daily-chart.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { DailyTokens } from "../../db/shared-types";
import { fmt } from "./formatters";
import { fmt, fmtCost } from "./formatters";

export function renderDailyChart(daily: DailyTokens[]): string {
const dataMap = new Map<string, number>();
Expand Down Expand Up @@ -61,3 +61,63 @@ export function renderDailyChart(daily: DailyTokens[]): string {
</div>
</div>`;
}

export function renderDailyCostChart(daily: DailyTokens[]): string {
const dataMap = new Map<string, number>();
for (const d of daily) dataMap.set(d.date, d.total);

const days: { date: string; total: number }[] = [];
for (let i = 59; i >= 0; i--) {
const d = new Date();
d.setDate(d.getDate() - i);
const key = d.toISOString().slice(0, 10);
days.push({ date: key, total: dataMap.get(key) ?? 0 });
}

const max = Math.max(...days.map((d) => d.total));

const bars = days
.map((d) => {
const pct =
max > 0 && d.total > 0
? Math.max(1, Math.round((d.total / max) * 100))
: 0;
const dateObj = new Date(`${d.date}T00:00:00`);
const weekday = dateObj.toLocaleDateString("en-US", { weekday: "short" });
const day = String(dateObj.getDate()).padStart(2, "0");
const month = dateObj.toLocaleDateString("en-US", { month: "short" });
const tooltipDate = `${weekday}, ${day} ${month}`;
return `
<div class="chart-col">
${d.total > 0 ? `<div class="chart-value">${fmtCost(d.total)}</div>` : ""}
<div class="chart-bar" style="height: ${pct}%"></div>
<div class="chart-tooltip">${tooltipDate}<br>${fmtCost(d.total)}</div>
</div>`;
})
.join("");

const avgPoints: { x: number; y: number }[] = [];
for (let i = 0; i < days.length; i++) {
const window = days.slice(Math.max(0, i - 4), i + 1);
const avg = window.reduce((s, d) => s + d.total, 0) / window.length;
const xPct = ((i + 0.5) / days.length) * 100;
const yPct = max > 0 ? 100 - (avg / max) * 100 : 100;
avgPoints.push({ x: xPct, y: yPct });
}
const polyline = avgPoints.map((p) => `${p.x},${p.y}`).join(" ");

return `
<div class="daily-chart">
<div class="chart-title">Daily Cost (last 60 days)</div>
<div class="chart-container">
${bars}
<svg class="chart-avg-line" viewBox="0 0 100 100" preserveAspectRatio="none">
<polyline points="${polyline}" fill="none" stroke="#f0883e" stroke-width="1.5" vector-effect="non-scaling-stroke"/>
</svg>
</div>
<div class="chart-legend">
<span class="legend-item"><span class="legend-bar"></span>Daily cost</span>
<span class="legend-item"><span class="legend-line"></span>5-day avg</span>
</div>
</div>`;
}
92 changes: 91 additions & 1 deletion src/dashboard/templates/model-chart.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { DailyModelTokens } from "../../db/message/message-repo";
import { esc, fmt } from "./formatters";
import { esc, fmt, fmtCost } from "./formatters";

export const MODEL_COLORS = [
"#58a6ff",
Expand Down Expand Up @@ -101,3 +101,93 @@ export function renderDailyModelChart(modelData: DailyModelTokens[]): string {
</div>
</div>`;
}

export function renderDailyModelCostChart(
modelData: DailyModelTokens[],
): string {
const modelTotals = new Map<string, number>();
for (const d of modelData) {
modelTotals.set(d.model, (modelTotals.get(d.model) ?? 0) + d.total);
}
const models = [...modelTotals.entries()]
.sort((a, b) => b[1] - a[1])
.map(([m]) => m);

const colorMap = new Map<string, string>();
for (const [i, m] of models.entries()) {
colorMap.set(m, MODEL_COLORS[i % MODEL_COLORS.length]!);
}

const dataMap = new Map<string, Map<string, number>>();
for (const d of modelData) {
if (!dataMap.has(d.date)) dataMap.set(d.date, new Map());
dataMap.get(d.date)?.set(d.model, d.total);
}

const days: { date: string; byModel: Map<string, number>; total: number }[] =
[];
for (let i = 59; i >= 0; i--) {
const dt = new Date();
dt.setDate(dt.getDate() - i);
const key = dt.toISOString().slice(0, 10);
const byModel = dataMap.get(key) ?? new Map();
const total = [...byModel.values()].reduce((s, v) => s + v, 0);
days.push({ date: key, byModel, total });
}

const max = Math.max(...days.map((d) => d.total), 1);

const bars = days
.map((d) => {
const dateObj = new Date(`${d.date}T00:00:00`);
const weekday = dateObj.toLocaleDateString("en-US", { weekday: "short" });
const day = String(dateObj.getDate()).padStart(2, "0");
const month = dateObj.toLocaleDateString("en-US", { month: "short" });
const tooltipDate = `${weekday}, ${day} ${month}`;

const segments = models
.map((m) => {
const val = d.byModel.get(m) ?? 0;
if (val === 0) return "";
const pct = (val / max) * 100;
const color = colorMap.get(m)!;
return `<div class="model-bar-seg" style="height:${pct}%;background:${color}"></div>`;
})
.join("");

const tooltipLines = models
.filter((m) => (d.byModel.get(m) ?? 0) > 0)
.map((m) => {
const color = colorMap.get(m)!;
return `<span style="color:${color}">■</span> ${esc(m)}: ${fmtCost(d.byModel.get(m)!)}`;
})
.join("<br>");

return `
<div class="chart-col">
<div class="model-bar-stack" style="height:${max > 0 && d.total > 0 ? Math.max(1, Math.round((d.total / max) * 100)) : 0}%">
${segments}
</div>
<div class="chart-tooltip">${tooltipDate}<br>${tooltipLines}</div>
</div>`;
})
.join("");

const legend = models
.map((m) => {
const color = colorMap.get(m)!;
return `<span class="legend-item"><span class="legend-bar" style="background:${color}"></span>${esc(m)}</span>`;
})
.join("");

return `
<div class="daily-chart">
<div class="chart-title">Daily Cost by Model (last 60 days)</div>
<div class="chart-container">
${bars}
</div>
<div class="chart-legend">
${legend}
</div>
</div>`;
}
4 changes: 3 additions & 1 deletion src/dashboard/templates/page-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ export function renderHTML(
toolGroups: ToolGroupSummary[],
directories: string[] = [],
selectedDir?: string,
dailyCost: DailyTokens[] = [],
dailyModelCost: DailyModelTokens[] = [],
): string {
return `<!DOCTYPE html>
<html lang="en">
Expand All @@ -109,7 +111,7 @@ export function renderHTML(
</div>
</div>
<div id="sessions">
${renderSessionsFragment(sessions, summary, costSummary, daily, dailyModel, toolGroups, directories, selectedDir)}
${renderSessionsFragment(sessions, summary, costSummary, daily, dailyModel, toolGroups, directories, selectedDir, dailyCost, dailyModelCost)}
</div>
<script>${CLIENT_SCRIPT}</script>
</body>
Expand Down
13 changes: 11 additions & 2 deletions src/dashboard/templates/sessions-fragment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@ import type {
import type { DailyTokens } from "../../db/shared-types";
import type { ToolGroupSummary } from "../../db/tool-call/tool-call-repo";
import type { SessionStats } from "../services/types";
import { renderDailyChart } from "./daily-chart";
import { renderDailyChart, renderDailyCostChart } from "./daily-chart";
import { esc } from "./formatters";
import { renderDailyModelChart } from "./model-chart";
import {
renderDailyModelChart,
renderDailyModelCostChart,
} from "./model-chart";
import { renderSessionCard } from "./session-card";
import { renderStatsBar } from "./stats-bar";
import { renderToolUsage } from "./tool-usage";
Expand All @@ -22,18 +25,24 @@ export function renderSessionsFragment(
toolGroups: ToolGroupSummary[],
directories: string[] = [],
selectedDir?: string,
dailyCost: DailyTokens[] = [],
dailyModelCost: DailyModelTokens[] = [],
): string {
const bar = renderStatsBar(summary, costSummary);
const chart = renderDailyChart(daily);
const costChart = renderDailyCostChart(dailyCost);
const modelChart = renderDailyModelChart(dailyModel);
const modelCostChart = renderDailyModelCostChart(dailyModelCost);
const toolUsage = renderToolUsage(toolGroups);

const leftPanel = `
<div class="left-panel">
${bar}
<hr class="section-divider">
${chart}
${costChart}
${modelChart}
${modelCostChart}
${toolUsage}
</div>`;

Expand Down
4 changes: 4 additions & 0 deletions src/db/daily-usage/daily-usage-repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,8 @@ import type { DailyTokens } from "../shared-types";
export interface DailyUsageRepo {
recompute(fromDay: string, toDay: string): void;
getHistoryUntil(dayExclusive: string, lookbackDays: number): DailyTokens[];
getHistoryUntilCost(
dayExclusive: string,
lookbackDays: number,
): DailyTokens[];
}
15 changes: 15 additions & 0 deletions src/db/daily-usage/sqlite-daily-usage-repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,19 @@ export class SqliteDailyUsageRepo implements DailyUsageRepo {
`)
.all(dayExclusive, `-${lookbackDays} days`) as DailyTokens[];
}

getHistoryUntilCost(
dayExclusive: string,
lookbackDays: number,
): DailyTokens[] {
return this.db
.prepare(`
SELECT day AS date, cost_total AS total
FROM daily_usage
WHERE day < ?
AND day >= date('now', ?)
ORDER BY day ASC
`)
.all(dayExclusive, `-${lookbackDays} days`) as DailyTokens[];
}
}
2 changes: 2 additions & 0 deletions src/db/message/message-repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ export interface MessageRepo {
getTokenSummary(): TokenSummary;
getCostSummary(): CostSummary;
getTodayTokens(today: string): DailyTokens;
getTodayCost(today: string): DailyTokens;
getDailyTokensByModel(): DailyModelTokens[];
getDailyModelCost(): DailyModelTokens[];
deleteOlderThan(cutoffDate: string): number;
}
Loading