Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
perf: cache usage report activity scans (#5127)
[._.]/ Adam Eivye20ad3adce2a
diff --git a/scripts/migrations/303-cache-earliest-usage-day.js b/scripts/migrations/303-cache-earliest-usage-day.jsnew file mode 100644index 0000000000..a397538fda--- /dev/null+++ b/scripts/migrations/303-cache-earliest-usage-day.js@@ -0,0 +1,41 @@+/**+ * Cache the first recorded usage day so all-time usage queries do not rescan+ * every retained daily and monthly activity key on each request.+ */++import { readFile, rename, writeFile } from 'fs/promises';+import { join } from 'path';++const DAY_KEY_RE = /^\d{4}-\d{2}-\d{2}$/;+const MONTH_KEY_RE = /^\d{4}-\d{2}$/;++const findEarliestActivityDay = (usage) => {+ const days = [+ ...Object.keys(usage.dailyActivity || {}).filter((key) => DAY_KEY_RE.test(key)),+ ...Object.keys(usage.monthlyActivity || {})+ .filter((key) => MONTH_KEY_RE.test(key))+ .map((key) => `${key}-01`)+ ];+ return days.reduce((earliest, day) => (!earliest || day < earliest ? day : earliest), null);+};++export async function up({ rootDir }) {+ const usagePath = join(rootDir, 'data', 'usage.json');+ const raw = await readFile(usagePath, 'utf8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return;++ const usage = JSON.parse(raw);+ const earliestActivityDay = findEarliestActivityDay(usage);+ if (usage.earliestActivityDay === earliestActivityDay) return;++ usage.earliestActivityDay = earliestActivityDay;+ const tempPath = `${usagePath}.303.tmp`;+ await writeFile(tempPath, `${JSON.stringify(usage, null, 2)}\n`);+ await rename(tempPath, usagePath);+ console.log('📊 Migration 303: cached earliest usage activity day');+}++export default { up };diff --git a/scripts/migrations/303-cache-earliest-usage-day.test.js b/scripts/migrations/303-cache-earliest-usage-day.test.jsnew file mode 100644index 0000000000..b1c2af6cb4--- /dev/null+++ b/scripts/migrations/303-cache-earliest-usage-day.test.js@@ -0,0 +1,51 @@+import { afterEach, describe, expect, it } from 'vitest';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { up } from './303-cache-earliest-usage-day.js';++const roots = [];++const makeRoot = async () => {+ const root = await mkdtemp(join(tmpdir(), 'migration-303-'));+ roots.push(root);+ await mkdir(join(root, 'data'), { recursive: true });+ return root;+};++const readUsage = async (rootDir) =>+ JSON.parse(await readFile(join(rootDir, 'data', 'usage.json'), 'utf8'));++afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+});++describe('migration 303 — earliest usage activity day', () => {+ it('caches the earliest daily or rolled-up activity date', async () => {+ const rootDir = await makeRoot();+ await writeFile(join(rootDir, 'data', 'usage.json'), JSON.stringify({+ dailyActivity: { '2026-08-20': {}, '2026-08-24': {} },+ monthlyActivity: { '2025-11': {}, '2026-07': {} }+ }));++ await up({ rootDir });++ expect((await readUsage(rootDir)).earliestActivityDay).toBe('2025-11-01');+ });++ it('writes null for an empty history and is idempotent', async () => {+ const rootDir = await makeRoot();+ await writeFile(join(rootDir, 'data', 'usage.json'), JSON.stringify({ dailyActivity: {}, monthlyActivity: {} }));++ await up({ rootDir });+ const first = await readUsage(rootDir);+ await up({ rootDir });++ expect(first.earliestActivityDay).toBeNull();+ expect(await readUsage(rootDir)).toEqual(first);+ });++ it('is a no-op when usage.json does not exist', async () => {+ await expect(up({ rootDir: await makeRoot() })).resolves.toBeUndefined();+ });+});diff --git a/server/services/usage.js b/server/services/usage.jsindex 02aec71b21..9bc179f570 100644--- a/server/services/usage.js+++ b/server/services/usage.js@@ -13,8 +13,11 @@ const USAGE_FILE = join(DATA_DIR, 'usage.json');// any useful streak/report window — while collapsing everything older to per-month.const ROLLUP_RETENTION_DAYS = 400;const DAY_KEY_RE = /^\d{4}-\d{2}-\d{2}$/;+const MONTH_KEY_RE = /^\d{4}-\d{2}$/;+const SUMMARY_CACHE_LIMIT = 20;let usageData = null;+const summaryCache = new Map();const UNKNOWN_PROVIDER_ID = 'unknown';const UNKNOWN_PROVIDER_NAME = 'Unknown provider';const LEGACY_PROVIDER_ID = 'legacy';@@ -62,6 +65,7 @@ function getEmptyUsage() {byModel: {},dailyActivity: {},monthlyActivity: {},+ earliestActivityDay: null,hourlyActivity: Array(24).fill(0),lastUpdated: null};@@ -119,11 +123,33 @@ export function rollupOldDailyActivity(dailyActivity, monthlyActivity, { retentireturn changed;}+const findEarliestActivityDay = (dailyActivity, monthlyActivity) => {+ let earliest = null;+ const consider = (day) => {+ if (!earliest || day < earliest) earliest = day;+ };+ for (const key of Object.keys(dailyActivity || {})) {+ if (DAY_KEY_RE.test(key)) consider(key);+ }+ for (const key of Object.keys(monthlyActivity || {})) {+ if (MONTH_KEY_RE.test(key)) consider(`${key}-01`);+ }+ return earliest;+};++const cacheActivityDay = (day) => {+ if (!DAY_KEY_RE.test(day)) return;+ if (!usageData.earliestActivityDay || day < usageData.earliestActivityDay) {+ usageData.earliestActivityDay = day;+ }+};+/*** Load usage data from disk*/export async function loadUsage() {await ensureDir(DATA_DIR);+ summaryCache.clear();// STRICT (#4115): the `!usageData` branch below does not just report an empty// total — it atomically OVERWRITES usage.json with zeros on the same tick. A@@ -153,7 +179,10 @@ export async function loadUsage() {normalizedProviders = normalizeUndefinedProviderBucket(bucket?.byProvider) || normalizedProviders;}const rolledUp = rollupOldDailyActivity(usageData.dailyActivity, usageData.monthlyActivity);- if (rolledUp || normalizedProviders) {+ const earliestActivityDay = findEarliestActivityDay(usageData.dailyActivity, usageData.monthlyActivity);+ const earliestChanged = usageData.earliestActivityDay !== earliestActivityDay;+ usageData.earliestActivityDay = earliestActivityDay;+ if (rolledUp || normalizedProviders || earliestChanged) {if (normalizedProviders) console.log('📊 Normalized undefined usage providers to unknown');if (rolledUp) console.log(`📊 Rolled up old daily usage into ${Object.keys(usageData.monthlyActivity).length} monthly buckets`);await saveUsage();@@ -167,6 +196,7 @@ export async function loadUsage() {* Save usage data to disk*/async function saveUsage() {+ summaryCache.clear();usageData.lastUpdated = new Date().toISOString();await atomicWrite(USAGE_FILE, usageData);}@@ -189,19 +219,7 @@ export function getUsage() {* unbounded one (see lib/subscriptionSavings.js).*/export function getFirstActivityDay() {- const data = getUsage();- // Min over the keys rather than sort-then-head: on a full 400-day retention- // window that is one linear pass instead of three intermediate arrays and an- // O(n log n) string sort. YYYY-MM-DD compares correctly as a string.- let earliest = null;- const consider = (day) => { if (!earliest || day < earliest) earliest = day; };- for (const key of Object.keys(data.dailyActivity || {})) {- if (DAY_KEY_RE.test(key)) consider(key);- }- for (const key of Object.keys(data.monthlyActivity || {})) {- if (/^\d{4}-\d{2}$/.test(key)) consider(`${key}-01`);- }- return earliest;+ return getUsage().earliestActivityDay ?? null;}/**@@ -430,6 +448,7 @@ function todayBucket() {const today = new Date().toISOString().split('T')[0];if (!usageData.dailyActivity[today]) {usageData.dailyActivity[today] = { sessions: 0, messages: 0, tokens: 0 };+ cacheActivityDay(today);}return usageData.dailyActivity[today];}@@ -987,6 +1006,20 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})};}+ const cacheKey = JSON.stringify({+ day: new Date().toISOString().split('T')[0],+ from,+ to,+ providers: providers.map((provider) => ({+ id: provider.id,+ name: provider.name,+ free: isFreeProvider(provider),+ family: familyForProvider(provider)+ }))+ });+ const cached = summaryCache.get(cacheKey);+ if (cached) return cached;+// Get last 7 days activityconst last7Days = [];for (let i = 6; i >= 0; i--) {@@ -1016,7 +1049,7 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})}): report;- return {+ const summary = {totalSessions: usageData.totalSessions,totalMessages: usageData.totalMessages,totalToolCalls: usageData.totalToolCalls,@@ -1040,6 +1073,11 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})report,lastUpdated: usageData.lastUpdated};+ if (summaryCache.size >= SUMMARY_CACHE_LIMIT) {+ summaryCache.delete(summaryCache.keys().next().value);+ }+ summaryCache.set(cacheKey, summary);+ return summary;}/**diff --git a/server/services/usage.test.js b/server/services/usage.test.jsindex e4b9b6fd3d..46a12223eb 100644--- a/server/services/usage.test.js+++ b/server/services/usage.test.js@@ -311,6 +311,43 @@ describe('usage.js — streak calculations', () => {await loadUsage();expect(getFirstActivityDay()).toBeNull();});++ it('backfills a stale cached value during load and persists it', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage(+ { '2025-06-08': { sessions: 1 } },+ { earliestActivityDay: '2025-06-10', monthlyActivity: { '2024-03': { sessions: 5 } } }+ ));++ await loadUsage();++ expect(getFirstActivityDay()).toBe('2024-03-01');+ expect(atomicWrite).toHaveBeenCalled();+ });++ it('updates the cached value when the first day bucket is recorded', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({}));+ await loadUsage();++ await recordSession('codex', 'Codex', 'gpt-5.6');++ expect(getFirstActivityDay()).toBe(daysAgo(0));+ });+ });++ describe('summary memoization', () => {+ it('reuses a summary until usage changes', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({ [daysAgo(0)]: { sessions: 1 } }));+ await loadUsage();++ const first = getUsageSummary();+ const cached = getUsageSummary();+ await recordSession('codex', 'Codex', 'gpt-5.6');+ const updated = getUsageSummary();++ expect(cached).toBe(first);+ expect(updated).not.toBe(first);+ expect(updated.totalSessions).toBe(2);+ });});describe('time-dimensioned capture', () => {