Skip to content

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

fix Usage page crash: unwrap getAllProviders() { providers } shape in usage routes

[._.]/ Adam Eivy30d58159ba68
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d9045b2a6e..02834bbede 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -58,3 +58,4 @@
- **[issue-2542] Fix VideoGen busy-retry timer cleanup and FeatureAgentDetail load race.** The VideoGen queue worker's BUSY-backoff `setTimeout` was a local `let busyRetryTimer` assigned inside an async `.catch`, so the effect's own cleanup (consumed on every `setQueue`/`setRunningQueueId` re-run before the timer was ever assigned) couldn't clear it — an unmount during the 1.5s backoff, or a newer dispatch, could still fire `setRunningQueueId` on a torn-down component or steal a slot a newer item owned. The timer now lives on a `useRef`, is cleared by a dedicated unmount cleanup, and every deferred `then`/`catch`/`finally` (and the timer callback) is gated by a per-dispatch generation token plus a `mountedRef` so stale callbacks bail. Separately, `FeatureAgentDetail`'s `getFeatureAgent(id)` load had no stale guard, so an A→B navigation whose A response resolved late could paint the wrong agent; the load is now sequence-tokened (late/stale results ignored) with a `mountedRef` guard, and an A→B switch clears to the spinner immediately instead of flashing the previous agent.
- **[issue-2533] Extract JIRA-ticket claim assembly out of the route into `buildJiraTicketTask` (next to `buildClaimWorkTask`).** `POST /api/cos/tasks/jira-ticket` (the sprint-board per-card play button) inlined its reviewer-CSV resolution (`resolveClaimReviewersCsv`), the target-ticket constraint block (`buildTargetTicketBlock`), and the `claim-issue-jira` prompt assembly directly in `server/routes/cosTaskRoutes.js`. That logic now lives in `server/services/cosTaskGenerator.js` as an exported `buildJiraTicketTask(app, ticketKey)` that returns `{ ticketKey, prompt, taskMetadata }` — beside `buildClaimWorkTask`, sharing the same reviewer/isolation conventions. The route stays thin: validate → JIRA-enabled gate → assemble → queue. Pure refactor — the queued task's context, description, and `useWorktree/openPR` posture are byte-for-byte unchanged; new unit tests cover the extracted assembly.
- **[issue-2539] Serialize `createCachedStore` and `backup.saveState` writes; bound the rate-limit state maps.** `createCachedStore` now runs every write through an internal single-tail `createFileWriteQueue` and exposes a `mutate(fn)` primitive that serializes the whole `load → modify → persist` cycle, so two concurrent read-modify-write paths can no longer clobber each other; the feeds, social-accounts, platform-accounts, agent-personalities, and automation-scheduler services were migrated off the racy `load()` + `save()` pair onto `mutate()`. `backup.saveState` gained the same promise-tail so a run completing while the scheduler stamps a status can't lose fields. The moltbook/moltworld rate-limiters, which kept one in-memory state entry per API key / agent id forever, now store it in a new bounded `createBoundedStateMap({ maxSize, ttlMs })` helper (`server/lib/boundedStateMap.js`) that lazily evicts idle (TTL) and least-recently-used (LRU) entries. (The idle pipeline `writeQueues` pruning called for by the issue already shipped via `createKeyedFileWriteQueue`/`createKeyCachedQueue` in #2528/#2524.) Behavior is otherwise unchanged; new unit tests cover the serialized `mutate`, the bounded map, and the rate-limiter.
+- **Fix the DevTools → Usage page crashing with "(providers || []).map/filter is not a function".** `services/providers.getAllProviders()` returns the wrapped `{ activeProvider, providers }` object, but `routes/usage.js` (GET `/api/usage`) and `services/providerUsage.js#getProviderQuotas` (GET `/api/usage/providers`) passed that object straight into `.map`/`.filter`, throwing on every request so the Usage page showed "Couldn't read provider usage." / "No usage data available." Both call sites now unwrap `.providers` via the `Array.isArray(result) ? result : (result?.providers || [])` pattern already used in `jiraReports.js`/`loops.js`. The two test suites mocked `getAllProviders` as a bare array (masking the bug); their mocks now return the real object shape, plus a new `getProviderQuotas` regression test asserts the unwrap.
diff --git a/server/routes/usage.js b/server/routes/usage.js
index bdb27c1d81..29a58de176 100644
--- a/server/routes/usage.js
+++ b/server/routes/usage.js
@@ -14,7 +14,8 @@ const router = Router();
router.get('/', asyncHandler(async (req, res) => {
const query = validateRequest(usageQuerySchema, req.query);
const { from, to } = resolveUsageRange(query);
- const providers = await getAllProviders();
+ const result = await getAllProviders();
+ const providers = Array.isArray(result) ? result : (result?.providers || []);
const summary = usage.getUsageSummary({ from, to, providers });
res.json(summary);
}));
diff --git a/server/routes/usage.test.js b/server/routes/usage.test.js
index fa774a8734..0517f2be87 100644
--- a/server/routes/usage.test.js
+++ b/server/routes/usage.test.js
@@ -13,7 +13,9 @@ vi.mock('../services/usage.js', () => ({
}));
vi.mock('../services/providers.js', () => ({
- getAllProviders: vi.fn().mockResolvedValue([])
+ // getAllProviders returns the wrapped { activeProvider, providers } shape —
+ // the route must unwrap `.providers` before passing to getUsageSummary.
+ getAllProviders: vi.fn().mockResolvedValue({ activeProvider: null, providers: [] })
}));
vi.mock('../services/providerUsage.js', () => ({
@@ -55,7 +57,7 @@ describe('usage routes', () => {
it('GET /api/usage passes an explicit from/to range through', async () => {
usage.getUsageSummary.mockReturnValue({});
- getAllProviders.mockResolvedValue([{ id: 'ollama' }]);
+ getAllProviders.mockResolvedValue({ activeProvider: 'ollama', providers: [{ id: 'ollama' }] });
const res = await request(buildApp()).get('/api/usage?from=2026-01-01&to=2026-02-01');
expect(res.status).toBe(200);
expect(usage.getUsageSummary).toHaveBeenCalledWith({
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index 6cdda83d73..de2f514254 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -279,7 +279,8 @@ const fetchFamilyQuota = (family, { refresh }) =>
* as `error` entries.
*/
export async function getProviderQuotas({ refresh = false } = {}) {
- const providers = await getAllProviders();
+ const result = await getAllProviders();
+ const providers = Array.isArray(result) ? result : (result?.providers || []);
const families = resolveEnabledFamilies(providers);
return Promise.all(families.map((family) => fetchFamilyQuota(family, { refresh })));
}
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index 64474401bc..c439b6be43 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -3,13 +3,16 @@ import { describe, it, expect, vi } from 'vitest';
// providerUsage imports the provider config service (toolkit-backed) and the
// claude CLI wrapper — mock both so this suite stays hermetic.
vi.mock('./providers.js', () => ({
- getAllProviders: vi.fn().mockResolvedValue([])
+ // getAllProviders returns the wrapped { activeProvider, providers } shape —
+ // getProviderQuotas must unwrap `.providers` before resolving families.
+ getAllProviders: vi.fn().mockResolvedValue({ activeProvider: null, providers: [] })
}));
vi.mock('./claudeCodeUsage.js', () => ({
getClaudeCodeUsage: vi.fn()
}));
-import { parseCodexRateLimits, mapCodexQuota, resolveEnabledFamilies } from './providerUsage.js';
+import { parseCodexRateLimits, mapCodexQuota, resolveEnabledFamilies, getProviderQuotas } from './providerUsage.js';
+import { getAllProviders } from './providers.js';
// Synthetic rollout line matching the codex event_msg/token_count shape —
// invented values only, never a transcript from a real session.
@@ -99,3 +102,18 @@ describe('resolveEnabledFamilies', () => {
expect(resolveEnabledFamilies(undefined)).toEqual([]);
});
});
+
+describe('getProviderQuotas', () => {
+ it('unwraps the { providers } object shape from getAllProviders', async () => {
+ // Regression: getAllProviders returns { activeProvider, providers }, not a
+ // bare array — passing the object straight into resolveEnabledFamilies threw
+ // "(providers || []).filter is not a function" and broke the Usage page.
+ getAllProviders.mockResolvedValueOnce({
+ activeProvider: 'grok',
+ providers: [{ id: 'grok', enabled: true, type: 'api', endpoint: 'https://api.x.ai/v1' }]
+ });
+ const quotas = await getProviderQuotas();
+ expect(Array.isArray(quotas)).toBe(true);
+ expect(quotas.map((q) => q.family)).toEqual(['grok']);
+ });
+});