Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(usage): daily token history and an activity heat map
Salman Qureshib22a91d6c229
diff --git a/apps/desktop/src/views/settings/Analytics.tsx b/apps/desktop/src/views/settings/Analytics.tsxnew file mode 100644index 00000000..790acb90--- /dev/null+++ b/apps/desktop/src/views/settings/Analytics.tsx@@ -0,0 +1,143 @@+import { useEffect, useMemo, useState } from "react";+import { http } from "~/api/client";+import { Spinner } from "~/components/ui/bits";+import { compact } from "~/views/bots/Usage";+import { cx } from "~/lib/cx";++/**+ * Analytics: a year of token use as a GitHub-style heat map (one square per+ * day, darker = more), with the basics beside it. Built to take more panels+ * (trends, providers, bots) as they arrive.+ */++interface Day { date: string; tokens: number; inputTokens: number; outputTokens: number; requests: number }++const WEEKS = 53;+const CELL = 12;+const GAP = 3;++export function Analytics() {+ const [days, setDays] = useState<Day[] | null>(null);+ const [since, setSince] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [hover, setHover] = useState<Day | null>(null);++ useEffect(() => {+ http.get<{ days: Day[]; since: string | null }>(`/api/usage/history?days=${WEEKS * 7 + 7}`)+ .then((r) => { setDays(r.days); setSince(r.since); })+ .catch((e) => setError(e instanceof Error && /404/.test(e.message) ? "This runtime doesn't keep daily history yet (needs Mercury 1.5)." : String(e instanceof Error ? e.message : e)));+ }, []);++ const view = useMemo(() => (days ? layout(days) : null), [days]);+ const stats = useMemo(() => (days ? summarise(days) : null), [days]);++ if (error) return <p className="text-sm text-ink3">{error}</p>;+ if (!days || !view || !stats) return <div className="py-10 text-ink3"><Spinner size={18} /></div>;++ return (+ <section className="flex flex-col gap-5">+ <div className="grid grid-cols-4 gap-3">+ <Tile label="Last 12 months" value={compact(stats.total)} sub="tokens" />+ <Tile label="Active days" value={String(stats.activeDays)} sub={`current streak ${stats.streak} day${stats.streak === 1 ? "" : "s"}`} />+ <Tile label="Busiest day" value={stats.best ? compact(stats.best.tokens) : "—"} sub={stats.best ? fmtDate(stats.best.date) : "no activity yet"} />+ <Tile label="Average active day" value={stats.activeDays ? compact(Math.round(stats.total / stats.activeDays)) : "—"} sub={`${compact(stats.requests)} requests in all`} />+ </div>++ <div className="rounded-xl border border-line bg-surface p-4">+ <div className="mb-3 flex items-baseline justify-between">+ <span className="text-sm font-medium text-ink">Tokens per day</span>+ <span className="text-xs text-ink4">{since ? `Recorded since ${fmtDate(since)}` : "Recording starts today"}</span>+ </div>+ <div className="overflow-x-auto">+ <svg width={WEEKS * (CELL + GAP) + 28} height={7 * (CELL + GAP) + 18} role="img" aria-label="Token use per day over the last year" onMouseLeave={() => setHover(null)}>+ {view.months.map((m) => <text key={`${m.label}-${m.week}`} x={28 + m.week * (CELL + GAP)} y={10} className="fill-[rgb(var(--ink-4))] text-[10px]">{m.label}</text>)}+ {["Mon", "Wed", "Fri"].map((d, i) => <text key={d} x={0} y={18 + (1 + i * 2) * (CELL + GAP) + CELL - 2} className="fill-[rgb(var(--ink-4))] text-[10px]">{d}</text>)}+ {view.cells.map((c) => c.day && (+ <rect key={c.day.date} x={28 + c.week * (CELL + GAP)} y={16 + c.weekday * (CELL + GAP)} width={CELL} height={CELL} rx={3}+ className={cx(LEVEL_CLASS[c.level], hover?.date === c.day.date && "stroke-[rgb(var(--ink))]")} strokeWidth={1.2}+ onMouseEnter={() => setHover(c.day)}>+ <title>{`${fmtDate(c.day.date)}: ${c.day.tokens.toLocaleString()} tokens`}</title>+ </rect>+ ))}+ </svg>+ </div>+ <div className="mt-2 flex items-center justify-between text-xs text-ink3">+ <span className="min-h-[18px]">+ {hover ? <><span className="text-ink">{fmtDate(hover.date)}</span> · {hover.tokens.toLocaleString()} tokens · {compact(hover.inputTokens)} in · {compact(hover.outputTokens)} out · {hover.requests} requests</> : "Hover a day for its numbers"}+ </span>+ <span className="flex items-center gap-1">Less {LEVEL_CLASS.map((cls, i) => <svg key={i} width={CELL} height={CELL}><rect width={CELL} height={CELL} rx={3} className={cls} /></svg>)} More</span>+ </div>+ </div>+ <p className="text-xs text-ink4">Counts every model request Mercury makes: chat, code, bots and channels. Days are in this computer's time zone.</p>+ </section>+ );+}++const LEVEL_CLASS = [+ "fill-[rgb(var(--ink)/0.07)]",+ "fill-[rgb(var(--accent)/0.3)]",+ "fill-[rgb(var(--accent)/0.5)]",+ "fill-[rgb(var(--accent)/0.75)]",+ "fill-[rgb(var(--accent))]",+];++/** Weeks as columns (Sunday first, like GitHub), the last column ending today. */+function layout(days: Day[]) {+ const byDate = new Map(days.map((d) => [d.date, d]));+ const today = new Date();+ const end = new Date(today.getFullYear(), today.getMonth(), today.getDate());+ const start = new Date(end);+ start.setDate(end.getDate() - end.getDay() - (WEEKS - 1) * 7);+ const values = days.map((d) => d.tokens).filter((v) => v > 0).sort((a, b) => a - b);+ const q = (p: number) => values.length ? values[Math.min(values.length - 1, Math.floor(p * values.length))] : 0;+ const cuts = [q(0.25), q(0.5), q(0.75)];+ const cells: Array<{ week: number; weekday: number; day: Day | null; level: number }> = [];+ const months: Array<{ label: string; week: number }> = [];+ let lastMonth = -1;+ for (let w = 0; w < WEEKS; w++) {+ for (let wd = 0; wd < 7; wd++) {+ const d = new Date(start);+ d.setDate(start.getDate() + w * 7 + wd);+ if (d > end) continue;+ const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;+ const day = byDate.get(key) ?? { date: key, tokens: 0, inputTokens: 0, outputTokens: 0, requests: 0 };+ const level = day.tokens <= 0 ? 0 : day.tokens <= cuts[0] ? 1 : day.tokens <= cuts[1] ? 2 : day.tokens <= cuts[2] ? 3 : 4;+ cells.push({ week: w, weekday: wd, day, level });+ if (wd === 0 && d.getMonth() !== lastMonth && d.getDate() <= 7) {+ lastMonth = d.getMonth();+ if (w < WEEKS - 2) months.push({ label: d.toLocaleString([], { month: "short" }), week: w });+ }+ }+ }+ return { cells, months };+}++function summarise(days: Day[]) {+ const recent = days.slice(-365);+ const total = recent.reduce((n, d) => n + d.tokens, 0);+ const requests = recent.reduce((n, d) => n + d.requests, 0);+ const active = recent.filter((d) => d.tokens > 0);+ const best = active.reduce<Day | null>((b, d) => (!b || d.tokens > b.tokens ? d : b), null);+ let streak = 0;+ for (let i = days.length - 1; i >= 0; i--) {+ if (days[i].tokens > 0) streak++;+ else if (i === days.length - 1) continue; // today may not have started yet+ else break;+ }+ return { total, requests, activeDays: active.length, best, streak };+}++function fmtDate(key: string): string {+ const [y, m, d] = key.split("-").map(Number);+ return new Date(y, m - 1, d).toLocaleDateString([], { weekday: "short", month: "short", day: "numeric", year: "numeric" });+}++function Tile({ label, value, sub }: { label: string; value: string; sub: string }) {+ return (+ <div className="rounded-xl border border-line bg-surface p-4">+ <div className="text-xs text-ink4">{label}</div>+ <div className="mt-1 text-2xl font-semibold tracking-tight text-ink">{value}</div>+ <div className="mt-0.5 truncate text-xs text-ink3">{sub}</div>+ </div>+ );+}diff --git a/apps/desktop/src/views/settings/SettingsView.tsx b/apps/desktop/src/views/settings/SettingsView.tsxindex 69e67383..c0fb5bde 100644--- a/apps/desktop/src/views/settings/SettingsView.tsx+++ b/apps/desktop/src/views/settings/SettingsView.tsx@@ -1,4 +1,4 @@-import { Info, PanelBottom, Palette, Power, Server, Smartphone } from "lucide-react";+import { Activity, Info, PanelBottom, Palette, Power, Server, Smartphone } from "lucide-react";import { useEffect, useState } from "react";import { cx } from "~/lib/cx";import * as api from "~/api/mercury";@@ -12,17 +12,19 @@ import { Badge, Mono, Segmented } from "~/components/ui/bits";import { Dialog } from "~/components/ui/Dialog";import { AddRemote } from "~/shell/AddRemote";import { StateOrb } from "~/components/indicators/StateOrb";+import { Analytics } from "./Analytics";import { isVisible, orderedIds, useContributions, type ContributionArea } from "~/extensions/registry";/*** Settings: a section list on the left, one section on the right. Most-used* first (Appearance), plain labels, every control explains itself in one line.*/-type Section = "appearance" | "statusbar" | "connections" | "devices" | "startup" | "about";+type Section = "appearance" | "statusbar" | "analytics" | "connections" | "devices" | "startup" | "about";const SECTIONS: Array<{ id: Section; label: string; icon: typeof Palette }> = [{ id: "appearance", label: "Appearance", icon: Palette },{ id: "statusbar", label: "Status bar", icon: PanelBottom },+ { id: "analytics", label: "Analytics", icon: Activity },{ id: "connections", label: "Connections", icon: Server },{ id: "devices", label: "Paired devices", icon: Smartphone },{ id: "startup", label: "Start-up", icon: Power },@@ -48,14 +50,15 @@ export function SettingsView({ connection, health, onSwitchConnection }: { conne</nav></aside><div className="min-h-0 flex-1 overflow-y-auto">- <div className="mx-auto flex max-w-[680px] flex-col gap-6 px-8 py-8">+ <div className={cx("mx-auto flex flex-col gap-6 px-8 py-8", section === "analytics" ? "max-w-[960px]" : "max-w-[680px]")}><h1 className="text-xl font-semibold tracking-tight text-ink">{SECTIONS.find((s) => s.id === section)?.label}</h1>{section === "appearance" && <Appearance />}{section === "statusbar" && <StatusBarSettings />}+ {section === "analytics" && <Analytics />}{section === "connections" && <Connections current={connection} health={health} onSwitchConnection={onSwitchConnection} />}{section === "devices" && <Devices current={connection} />}{section === "startup" && <Startup />}- {section === "about" && <About health={health} />}+ {section === "about" && <About health={health} onAnalytics={() => setSection("analytics")} />}</div></div></div>@@ -190,7 +193,7 @@ function Startup() {);}-function About({ health }: { health: HealthInfo }) {+function About({ health, onAnalytics }: { health: HealthInfo; onAnalytics?: () => void }) {const [appVersion, setAppVersion] = useState("");useEffect(() => {if (!isTauri) return;@@ -202,6 +205,7 @@ function About({ health }: { health: HealthInfo }) {<div className="flex items-center justify-between"><span>Mercury Desktop</span><Mono>{appVersion || "dev"}</Mono></div><div className="mt-1 flex items-center justify-between"><span>Runtime</span><Mono>{health.version} · API v{health.apiVersion ?? "?"}</Mono></div><button className="mt-3 text-xs text-accent hover:underline" onClick={() => void desktop.openExternal("https://mercuryagent.sh")}>mercuryagent.sh</button>+ {onAnalytics && <button className="ml-4 mt-3 text-xs text-accent hover:underline" onClick={onAnalytics}>Your activity →</button>}</div></section>);diff --git a/src/channels/web-reasoning.test.ts b/src/channels/web-reasoning.test.tsindex 8eab0659..4fabb099 100644--- a/src/channels/web-reasoning.test.ts+++ b/src/channels/web-reasoning.test.ts@@ -4,7 +4,7 @@ import { WebChannel } from './web.js';describe('web channel reasoning stream', () => {it('batches deltas and closes the block when the answer starts', async () => {vi.useFakeTimers();- const ch = new WebChannel();+ const ch = new WebChannel('Mercury');const sent: Array<{ type: string; data?: Record<string, unknown> }> = [];(ch as unknown as { broadcast: (e: { type: string; data?: Record<string, unknown> }) => boolean }).broadcast = (e) => { sent.push(e); return true; };ch.sendReasoning('Let me ', 's1');diff --git a/src/utils/token-history.test.ts b/src/utils/token-history.test.tsnew file mode 100644index 00000000..aef34fc8--- /dev/null+++ b/src/utils/token-history.test.ts@@ -0,0 +1,34 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { historySince, localDay, readHistory, recordDay, seedToday } from './token-history.js';++describe('token history', () => {+ let home: string;+ const previous = process.env.MERCURY_HOME;+ beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'mercury-history-')); process.env.MERCURY_HOME = home; });+ afterEach(() => { if (previous === undefined) delete process.env.MERCURY_HOME; else process.env.MERCURY_HOME = previous; rmSync(home, { recursive: true, force: true }); });++ it('adds requests to their local day and fills empty days', () => {+ const now = new Date(2026, 9, 27, 15, 0, 0);+ const yesterday = new Date(2026, 9, 26, 23, 30, 0).getTime();+ recordDay(100, 20, 120, yesterday);+ recordDay(50, 10, 60, now.getTime());+ recordDay(5, 5, 0, now.getTime());+ const rows = readHistory(3, now);+ expect(rows.map((r) => r.date)).toEqual(['2026-10-25', '2026-10-26', '2026-10-27']);+ expect(rows[0]).toMatchObject({ tokens: 0, requests: 0 });+ expect(rows[1]).toMatchObject({ tokens: 120, inputTokens: 100, outputTokens: 20, requests: 1 });+ expect(rows[2]).toMatchObject({ tokens: 70, requests: 2 });+ expect(historySince()).toBe('2026-10-26');+ });++ it('seeds today once, and never over an existing row', () => {+ seedToday(500, 400, 100, 3);+ seedToday(9999, 1, 1, 1);+ const today = readHistory(1)[0];+ expect(today.date).toBe(localDay());+ expect(today.tokens).toBe(500);+ });+});diff --git a/src/utils/token-history.ts b/src/utils/token-history.tsnew file mode 100644index 00000000..e3d4c772--- /dev/null+++ b/src/utils/token-history.ts@@ -0,0 +1,111 @@+import { existsSync, readFileSync, renameSync, writeFileSync, mkdirSync } from 'node:fs';+import { join } from 'node:path';+import { getMercuryHome } from './config.js';++/**+ * Day-by-day token ledger: `~/.mercury/token-history.json`.+ *+ * The daily budget counter (tokens.ts) resets at midnight and forgets the+ * day; this keeps one small row per local calendar day so clients can draw+ * history (the desktop app's activity heat map) and, later, trends.+ * Rows: tokens, input, output, requests. Capped at ~3 years.+ */++export interface DayUsage {+ date: string;+ tokens: number;+ inputTokens: number;+ outputTokens: number;+ requests: number;+}++interface HistoryFile {+ version: 1;+ days: Record<string, Omit<DayUsage, 'date'>>;+}++const FILE = 'token-history.json';+const MAX_DAYS = 1100;++export function historyPath(): string {+ return join(getMercuryHome(), FILE);+}++/** YYYY-MM-DD in the machine's local time zone. */+export function localDay(at: number | Date = Date.now()): string {+ const d = at instanceof Date ? at : new Date(at);+ const m = String(d.getMonth() + 1).padStart(2, '0');+ const day = String(d.getDate()).padStart(2, '0');+ return `${d.getFullYear()}-${m}-${day}`;+}++function read(): HistoryFile {+ const path = historyPath();+ if (!existsSync(path)) return { version: 1, days: {} };+ try {+ const data = JSON.parse(readFileSync(path, 'utf-8')) as Partial<HistoryFile>;+ if (data.version !== 1 || !data.days || typeof data.days !== 'object') return { version: 1, days: {} };+ return { version: 1, days: data.days };+ } catch {+ return { version: 1, days: {} };+ }+}++function write(file: HistoryFile): void {+ const keys = Object.keys(file.days).sort();+ if (keys.length > MAX_DAYS) for (const k of keys.slice(0, keys.length - MAX_DAYS)) delete file.days[k];+ const home = getMercuryHome();+ if (!existsSync(home)) mkdirSync(home, { recursive: true });+ const path = historyPath();+ const tmp = `${path}.${process.pid}.tmp`;+ writeFileSync(tmp, JSON.stringify(file), 'utf-8');+ renameSync(tmp, path);+}++const n = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);++/** Add one request's tokens to its day. Never throws: history is a convenience. */+export function recordDay(inputTokens: number, outputTokens: number, totalTokens: number, at: number = Date.now()): void {+ try {+ const file = read();+ const key = localDay(at);+ const row = file.days[key] ?? { tokens: 0, inputTokens: 0, outputTokens: 0, requests: 0 };+ row.tokens += n(totalTokens) || n(inputTokens) + n(outputTokens);+ row.inputTokens += n(inputTokens);+ row.outputTokens += n(outputTokens);+ row.requests += 1;+ file.days[key] = row;+ write(file);+ } catch { /* best effort */ }+}++/** First run with history: start it from today's counter so today isn't blank. */+export function seedToday(tokens: number, inputTokens: number, outputTokens: number, requests: number): void {+ try {+ const file = read();+ const key = localDay();+ if (file.days[key] || n(tokens) === 0) return;+ file.days[key] = { tokens: n(tokens), inputTokens: n(inputTokens), outputTokens: n(outputTokens), requests: n(requests) };+ write(file);+ } catch { /* best effort */ }+}++/** The last `days` days, oldest first, with empty days filled in. */+export function readHistory(days: number, now: Date = new Date()): DayUsage[] {+ const file = read();+ const out: DayUsage[] = [];+ const count = Math.max(1, Math.min(MAX_DAYS, Math.floor(days)));+ for (let i = count - 1; i >= 0; i--) {+ const d = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i);+ const key = localDay(d);+ const row = file.days[key];+ out.push({ date: key, tokens: n(row?.tokens), inputTokens: n(row?.inputTokens), outputTokens: n(row?.outputTokens), requests: n(row?.requests) });+ }+ return out;+}++/** The earliest day the ledger has, or null. */+export function historySince(): string | null {+ const keys = Object.keys(read().days).sort();+ return keys[0] ?? null;+}diff --git a/src/utils/tokens.ts b/src/utils/tokens.tsindex e6f1ff1c..a09fb26f 100644--- a/src/utils/tokens.ts+++ b/src/utils/tokens.ts@@ -4,6 +4,7 @@ import type { MercuryConfig } from './config.js';import { getMercuryHome, saveConfig } from './config.js';import { logger } from './logger.js';import { formatNumber } from './format.js';+import { recordDay, seedToday } from './token-history.js';export interface TokenTracker {dailyUsed: number;@@ -51,6 +52,12 @@ export class TokenBudget {this.lifetimeSaved = lifetime;}this.restore();+ // The ledger starts with today's counter on its first run, so today isn't blank.+ if (this.dailyUsed > 0) {+ const input = this.requestLog.reduce((a, e) => a + safeNumber(e.inputTokens), 0);+ const output = this.requestLog.reduce((a, e) => a + safeNumber(e.outputTokens), 0);+ seedToday(this.dailyUsed, input, output, this.requestLog.length);+ }}canAfford(estimatedTokens: number): boolean {@@ -106,6 +113,7 @@ export class TokenBudget {const logEntry: TokenLogEntry = { ...safeEntry, timestamp: Date.now() };this.dailyUsed += totalTokens;this.requestLog.push(logEntry);+ recordDay(inputTokens, outputTokens, totalTokens, logEntry.timestamp);if (entry.agentId) {const agentUsed = this.perAgentUsage.get(entry.agentId) ?? 0;diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex 8bee6b6c..0c03d08a 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -35,6 +35,7 @@ export const API_FEATURES: readonly string[] = Object.freeze(['code.session', // POST /api/chat/send { programming, cwd } — per-session coding'chat.uploads', // attachments on messages + GET /api/chat/uploads/:month/:file'voice', // /api/voice, /api/voice/events, /api/voice/control (Optimus)+ 'usage.history', // GET /api/usage/history?days= — tokens per local day]);export interface ApiContractInfo {diff --git a/src/web/api/system.ts b/src/web/api/system.tsindex c8f8fc79..7771dcda 100644--- a/src/web/api/system.ts+++ b/src/web/api/system.ts@@ -1,4 +1,5 @@import { Hono } from 'hono';+import { readHistory, historySince } from '../../utils/token-history.js';import { existsSync, readFileSync } from 'node:fs';import { join } from 'node:path';import { SkillLoader } from '../../skills/loader.js';@@ -144,6 +145,13 @@ system.put('/api/permissions', async (c) => {return c.json({ success: true, manifest: next });});+/** Day-by-day tokens for the activity heat map: ?days=1..1100 (default 371). */+system.get('/api/usage/history', (c) => {+ const parsed = parseInt(c.req.query('days') ?? '371', 10);+ const days = Number.isFinite(parsed) ? Math.max(1, Math.min(1100, parsed)) : 371;+ return c.json({ days: readHistory(days), since: historySince() });+});+system.get('/api/usage', (c) => {const usagePath = join(getMercuryHome(), 'token-usage.json');let data: {