import { describe, expect, it } from 'vitest'; import type { UsageRow } from './dashboard-usage-rows.js'; import { buildWebUsageRowsForSnapshot, createCoalescingTrigger, editStatusMessageWithRetry, formatStatusHeader, msUntilNextMinuteBoundary, getDashboardDuplicateCleanupIntervalMs, readCpuUtilizationPct, renderUsageTable, resetCpuUtilizationSample, shouldPurgeDashboardChannelOnStart, summarizeWatcherTasks, } from './unified-dashboard.js'; describe('readCpuUtilizationPct', () => { it('computes busy percentage from consecutive /proc/stat samples', () => { resetCpuUtilizationSample(); expect( readCpuUtilizationPct(() => 'cpu 100 0 100 800 0 0 0 0 0 0\n'), ).toBeNull(); // +100 total ticks: +30 busy, +70 idle => 30%. expect( readCpuUtilizationPct(() => 'cpu 115 0 115 870 0 0 0 0 0 0\n'), ).toBe(30); }); it('counts iowait as idle and rejects malformed samples', () => { resetCpuUtilizationSample(); expect(readCpuUtilizationPct(() => 'not-a-cpu-line\n')).toBeNull(); expect( readCpuUtilizationPct(() => 'cpu 100 0 100 700 100 0 0 0 0 0\n'), ).toBeNull(); // +100 total, all +100 is iowait: CPU busy must be 0%, not 100%. expect( readCpuUtilizationPct(() => 'cpu 100 0 100 700 200 0 0 0 0 0\n'), ).toBe(0); }); }); describe('summarizeWatcherTasks', () => { it('counts active and paused watcher tasks only', () => { const summary = summarizeWatcherTasks([ { prompt: '[BACKGROUND CI WATCH]\n\nWatch target:\nGitHub Actions run 1\n\nCheck instructions:\na', status: 'active', }, { prompt: '[BACKGROUND CI WATCH]\n\nWatch target:\nGitHub Actions run 2\n\nCheck instructions:\nb', status: 'paused', }, { prompt: '[BACKGROUND CI WATCH]\n\nWatch target:\nGitHub Actions run 3\n\nCheck instructions:\nc', status: 'completed', }, { prompt: 'normal scheduled task', status: 'active', }, ]); expect(summary).toEqual({ active: 1, paused: 1, }); }); }); describe('formatStatusHeader', () => { it('shows active watcher count in the dashboard header', () => { expect( formatStatusHeader({ totalActive: 3, totalRooms: 8, watchers: { active: 2, paused: 0 }, }), ).toBe('**πŸ“Š μ—μ΄μ „νŠΈ μƒνƒœ** β€” ν™œμ„± 3 / 8 | κ°μ‹œ 2'); }); it('adds paused watcher count only when present', () => { expect( formatStatusHeader({ totalActive: 3, totalRooms: 8, watchers: { active: 2, paused: 1 }, }), ).toBe('**πŸ“Š μ—μ΄μ „νŠΈ μƒνƒœ** β€” ν™œμ„± 3 / 8 | κ°μ‹œ 2 | μΌμ‹œμ •μ§€ 1'); }); }); describe('shouldPurgeDashboardChannelOnStart', () => { it('purges on startup when explicitly requested, even with a stored message id', () => { expect( shouldPurgeDashboardChannelOnStart({ purgeOnStart: true, storedMessageId: 'status-message-1', }), ).toBe(true); }); it('does not purge when startup purge is disabled', () => { expect( shouldPurgeDashboardChannelOnStart({ purgeOnStart: false, storedMessageId: null, }), ).toBe(false); }); }); describe('getDashboardDuplicateCleanupIntervalMs', () => { it('sweeps for stray duplicates only every 5 minutes', () => { // Was 2s (~43k Discord fetches a day). Fresh posts clean up immediately. expect(getDashboardDuplicateCleanupIntervalMs()).toBe(300_000); }); }); describe('renderUsageTable', () => { const claudeRow: UsageRow = { name: 'Claude pro', h5pct: 50, h5reset: '', d7pct: 30, d7reset: '', }; const codexRow: UsageRow = { name: 'Codex', h5pct: 40, h5reset: '', d7pct: 25, d7reset: '', }; it('renders Claude before separator before Codex', () => { const lines = renderUsageTable([claudeRow], [codexRow]); const claudeIdx = lines.findIndex((l) => l.includes('Claude')); const sepIdx = lines.findIndex((l) => /^─+$/.test(l)); const codexIdx = lines.findIndex((l) => l.includes('Codex')); expect(claudeIdx).toBeGreaterThan(-1); expect(sepIdx).toBeGreaterThan(claudeIdx); expect(codexIdx).toBeGreaterThan(sepIdx); }); it('omits separator when only Claude rows exist', () => { const lines = renderUsageTable([claudeRow], []); expect(lines.some((l) => /^─+$/.test(l))).toBe(false); expect(lines.some((l) => l.includes('Claude'))).toBe(true); }); it('omits separator when only Codex rows exist', () => { const lines = renderUsageTable([], [codexRow]); expect(lines.some((l) => /^─+$/.test(l))).toBe(false); expect(lines.some((l) => l.includes('Codex'))).toBe(true); }); it('renders an unknown (-1) window as the empty placeholder, not a %', () => { const lines = renderUsageTable( [{ ...claudeRow, h5pct: -1 }], [{ ...codexRow, h5pct: -1 }], ); const claudeLine = lines.find((l) => l.startsWith('Claude'))!; const codexLine = lines.find((l) => l.startsWith('Codex'))!; for (const line of [claudeLine, codexLine]) { expect(line).toContain('─────'); // Only the 7d column carries a percentage. expect(line.match(/%/g)).toHaveLength(1); } }); it('returns fallback text when both groups are empty', () => { const lines = renderUsageTable([], []); expect(lines).toEqual(['_쑰회 λΆˆκ°€_']); }); }); describe('buildWebUsageRowsForSnapshot', () => { it('keeps real Claude rows ahead of Codex rows for snapshots', () => { const rows = buildWebUsageRowsForSnapshot({ serviceAgentType: 'claude-code', claudeUsage: { usage: { five_hour: { utilization: 0.2, resets_at: '2026-04-26T12:00:00.000Z', }, seven_day: { utilization: 0.4, resets_at: '2026-04-27T12:00:00.000Z', }, }, }, codexRows: [ { name: 'Codex1', h5pct: 25, h5reset: '1h', d7pct: 35, d7reset: '2d', }, ], }); const names = rows.map((row) => row.name); expect(names[0]).toMatch(/^Claude/); expect(names[1]).toBe('Codex1'); }); it('does not invent Claude rows for codex-only services', () => { const rows = buildWebUsageRowsForSnapshot({ serviceAgentType: 'codex', claudeUsage: { usage: null }, codexRows: [ { name: 'Codex1', h5pct: 25, h5reset: '1h', d7pct: 35, d7reset: '2d', }, ], }); expect(rows.map((row) => row.name)).toEqual(['Codex1']); }); }); describe('editStatusMessageWithRetry', () => { it('succeeds on the first attempt without sleeping', async () => { let calls = 0; let slept = 0; const ok = await editStatusMessageWithRetry({ editOnce: async () => { calls++; }, maxRetries: 2, retryDelayMs: 15_000, sleep: async () => { slept++; }, }); expect(ok).toBe(true); expect(calls).toBe(1); expect(slept).toBe(0); }); it('retries after a failure and succeeds on the second attempt', async () => { let calls = 0; const delays: number[] = []; const ok = await editStatusMessageWithRetry({ editOnce: async () => { calls++; if (calls === 1) throw new Error('503'); }, maxRetries: 2, retryDelayMs: 15_000, sleep: async (ms) => { delays.push(ms); }, }); expect(ok).toBe(true); expect(calls).toBe(2); expect(delays).toEqual([15_000]); // one 15s wait between the two attempts }); it('gives up after maxRetries (3 total attempts) and reports each failure', async () => { let calls = 0; const attempts: Array<{ attempt: number; willRetry: boolean }> = []; let slept = 0; const ok = await editStatusMessageWithRetry({ editOnce: async () => { calls++; throw new Error('503'); }, maxRetries: 2, retryDelayMs: 15_000, sleep: async () => { slept++; }, onAttemptFailed: (attempt, willRetry) => attempts.push({ attempt, willRetry }), }); expect(ok).toBe(false); expect(calls).toBe(3); // initial + 2 retries expect(slept).toBe(2); // only between attempts, not after the last expect(attempts).toEqual([ { attempt: 1, willRetry: true }, { attempt: 2, willRetry: true }, { attempt: 3, willRetry: false }, ]); }); it('uses 15s spacing via the default sleep only when a retry is needed', async () => { // Sanity: with maxRetries 0, a single failure returns false and never sleeps. let slept = 0; const ok = await editStatusMessageWithRetry({ editOnce: async () => { throw new Error('nope'); }, maxRetries: 0, retryDelayMs: 15_000, sleep: async () => { slept++; }, }); expect(ok).toBe(false); expect(slept).toBe(0); }); it('works with a channel method that relies on `this` when bound (regression)', async () => { class FakeChannel { client = { ok: true }; edits = 0; async editMessage(): Promise { // Mirrors the real editMessage: throws if `this` is lost. if (!this.client) throw new Error('this.client is undefined'); this.edits++; } } const channel = new FakeChannel(); // A detached method reference loses `this` β†’ every attempt fails. const detached = channel.editMessage; const detachedOk = await editStatusMessageWithRetry({ editOnce: () => detached(), maxRetries: 0, retryDelayMs: 0, sleep: async () => {}, }); expect(detachedOk).toBe(false); expect(channel.edits).toBe(0); // Binding to the channel (the fix) preserves `this` and succeeds. const bound = channel.editMessage.bind(channel); const boundOk = await editStatusMessageWithRetry({ editOnce: () => bound(), maxRetries: 0, retryDelayMs: 0, sleep: async () => {}, }); expect(boundOk).toBe(true); expect(channel.edits).toBe(1); }); }); describe('msUntilNextMinuteBoundary', () => { it('returns time to the next :00 boundary', () => { expect(msUntilNextMinuteBoundary(120_000)).toBe(60_000); // exactly on boundary expect(msUntilNextMinuteBoundary(120_000 + 15_000)).toBe(45_000); // 15s in expect(msUntilNextMinuteBoundary(120_000 + 59_000)).toBe(1_000); // 59s in expect(msUntilNextMinuteBoundary(120_000 + 1)).toBe(59_999); // 1ms in }); }); describe('createCoalescingTrigger', () => { it('coalesces a burst into one run and re-arms after firing', () => { let runs = 0; let fire: (() => void) | null = null; const timer = { set: (cb: () => void) => { fire = cb; return 0 as unknown as ReturnType; }, }; const trigger = createCoalescingTrigger(() => runs++, 1500, timer); trigger(); trigger(); trigger(); expect(runs).toBe(0); // nothing runs until the debounce window elapses fire!(); expect(runs).toBe(1); // three calls collapsed into a single run // A new request after the run schedules and fires again. trigger(); fire!(); expect(runs).toBe(2); }); });