Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(api): a route that has no answer says so, instead of answering zero (#242)
tournierjcf7e4e290c37d
diff --git a/src/web/api/availability.test.ts b/src/web/api/availability.test.tsnew file mode 100644index 00000000..b27e39ed--- /dev/null+++ b/src/web/api/availability.test.ts@@ -0,0 +1,106 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import system, { setScheduler } from './system.js';+import status from './status.js';+import type { Scheduler } from '../../core/scheduler.js';++/**+ * The witness key.+ *+ * Every one of these routes can answer with a shape that a client decodes into plausible defaults —+ * zeros, "off", "unlimited", "no routines". A body is only evidence of the server's state when it+ * says so; `available` is that statement. These tests pin both directions: the honest answer, and+ * the one that admits it has none.+ */++let home = '';++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'mercury-availability-'));+ process.env.MERCURY_HOME = home;+});++afterEach(() => {+ setScheduler(null);+ delete process.env.MERCURY_HOME;+ rmSync(home, { recursive: true, force: true });+});++function writeUsage(payload: unknown): void {+ writeFileSync(join(home, 'token-usage.json'), JSON.stringify(payload));+}++describe('GET /api/status', () => {+ it('says it is available and gives the uptime as a number', async () => {+ const res = await status.request('/api/status');+ expect(res.status).toBe(200);+ const body = (await res.json()) as Record<string, unknown>;++ expect(body.available).toBe(true);+ expect(typeof body.uptimeSeconds).toBe('number');+ expect(Number.isFinite(body.uptimeSeconds)).toBe(true);+ // The field the dashboard already read stays, with the same number.+ expect(body.uptime).toBe(body.uptimeSeconds);+ });+});++describe('GET /api/usage', () => {+ it('is available when the tracker holds a real record', async () => {+ writeUsage({+ dailyUsed: 1234,+ dailyBudget: 80000000,+ lastResetDate: '2026-10-28',+ requestLog: [+ { timestamp: 1, provider: 'deepseek', model: 'flash', inputTokens: 10, outputTokens: 2, totalTokens: 12, channelType: 'internal' },+ ],+ });++ const res = await system.request('/api/usage');+ const body = (await res.json()) as Record<string, unknown>;++ expect(body.available).toBe(true);+ expect(body.dailyUsed).toBe(1234);+ expect(body.dailyBudget).toBe(80000000);+ });++ it('is NOT available when the tracker exists and cannot be read', async () => {+ // A truncated file is the case that used to read as "0 used, unlimited budget".+ writeFileSync(join(home, 'token-usage.json'), '{"dailyUsed": 12');++ const res = await system.request('/api/usage');+ const body = (await res.json()) as Record<string, unknown>;++ expect(res.status).toBe(200);+ expect(body.available).toBe(false);+ });++ it('is available on a fresh instance with no tracker yet', async () => {+ const res = await system.request('/api/usage');+ const body = (await res.json()) as Record<string, unknown>;++ expect(body.available).toBe(true);+ expect(body.dailyUsed).toBe(0);+ });+});++describe('GET /api/schedules', () => {+ it('admits it has no scheduler instead of reporting an empty schedule list', async () => {+ const res = await system.request('/api/schedules');+ const body = (await res.json()) as Record<string, unknown>;++ expect(res.status).toBe(200);+ expect(body.available).toBe(false);+ expect(body.schedules).toEqual([]);+ expect(body.total).toBe(0);+ });++ it('is available once a scheduler is attached', async () => {+ const fake = { getManifests: () => [] } as unknown as Scheduler;+ setScheduler(fake);++ const body = (await (await system.request('/api/schedules')).json()) as Record<string, unknown>;+ expect(body.available).toBe(true);+ });+});diff --git a/src/web/api/status.ts b/src/web/api/status.tsindex a520e858..6d7e5e66 100644--- a/src/web/api/status.ts+++ b/src/web/api/status.ts@@ -88,9 +88,14 @@ status.get('/api/status', (c) => {}return c.json({+ // The witness: a caller that does not find `available: true` must not read the rest of this+ // body as fact. `uptimeSeconds` is the number, so no client has to invent a zero from an+ // absent field — `uptime` stays for the dashboard that already reads it.+ available: true,running: s.running,state: s.state,uptime: Math.floor(process.uptime()),+ uptimeSeconds: Math.floor(process.uptime()),providers: providersMap,tokens: {dailyUsed: s.tokensUsed,diff --git a/src/web/api/system.ts b/src/web/api/system.tsindex c63a25b6..b0db6d77 100644--- a/src/web/api/system.ts+++ b/src/web/api/system.ts@@ -227,10 +227,14 @@ system.get('/api/usage', (c) => {requestLog: [],};+ // A tracker that exists and cannot be read is not a tracker reporting zeros: the file is the+ // answer, and losing it makes `dailyBudget: 0` read as "unlimited" on the console.+ let available = true;if (existsSync(usagePath)) {try {data = { ...data, ...(JSON.parse(readFileSync(usagePath, 'utf8')) as Record<string, any>) };} catch {+ available = false;// keep defaults}}@@ -243,6 +247,7 @@ system.get('/api/usage', (c) => {}return c.json({+ available,dailyUsed: data.dailyUsed || 0,dailyBudget: data.dailyBudget || 0,lastResetDate: data.lastResetDate,@@ -254,9 +259,11 @@ system.get('/api/usage', (c) => {});system.get('/api/schedules', (c) => {- if (!scheduler) return c.json({ schedules: [], total: 0 });+ // No scheduler in this process is not an empty schedule: the pair is the same shape, and the+ // console cannot tell a bot with no routines from a runtime that never started the scheduler.+ if (!scheduler) return c.json({ available: false, schedules: [], total: 0 });const schedules = scheduler.getManifests().sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));- return c.json({ schedules, total: schedules.length });+ return c.json({ available: true, schedules, total: schedules.length });});system.put('/api/schedules/:id', async (c) => {