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

feat: Claude Code subscription usage panel on the Usage page

Adam Eivyd07cd5651e7c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ac27feefff..9f29a1bdd4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -95,6 +95,10 @@
- **[issue-2121] Reference analysis can now pull a voice out of a stacked mix, not just solo spans.** The "analyze a reference's attached audio" workbench used to only transcribe time ranges where a voice sings *alone* — useless for the many layered TikTok builds where a new part enters over the layers already playing and never appears solo. Each segment now has a **Stacked** toggle: turn it on and set a short *backing reference* window from the moment just before the voice enters, and extraction subtracts that backing layer's spectrum (a hand-rolled FFT + spectral-diff, all pure local DSP — zero AI calls) to recover the newly-added voice's pitch line, then transcribes it onto the round's tempo/key grid exactly like the solo path. Enabling the toggle auto-seeds a sensible backing window ending right where the voice enters; you can nudge it or set it from the playhead. Solo extraction is unchanged.
- **[issue-2108] Built-in rounds now document their melody variant points.** Ah Poor Bird, Rose Rose Rose Red, and Zum Gali Gali carried melody/lyric choices that differ from other printed versions with no note explaining why — so a future accuracy check (or the AI evaluate feature) could mistake a deliberate variant for an error. Their notation now spells out each variant (Ah Poor Bird's C natural vs. the harmonic-minor C♯; Rose's verse and ending-note choices; Zum Gali Gali's D-minor transposition and refrain-only form) and cites the sources it was checked against.
+## Dev Tools
+
+- **The Usage page now shows your Claude Code subscription rate limits, not just PortOS's own token counts.** The `/devtools/usage` page previously only reported PortOS's internal AI-toolkit accounting (its own sessions/messages/tokens). It now leads with a **Claude Code Subscription** panel that surfaces the same numbers as the CLI's `/usage` command — current-session %, weekly % (all models and per-model, e.g. Fable), how much is left in each, and when each window resets — as color-coded meters that load on page open with a manual Refresh. Because there's no structured usage endpoint in the CLI, the server reads it the only way available: it runs `claude -p` with `/usage` on stdin (a read-only call that consumes zero tokens), parses the human-readable output into JSON, and caches it for 60s. The numbers are a per-machine local approximation (they don't include other devices or claude.ai), and the panel says so. If the `claude` CLI isn't installed/signed-in, the panel shows a friendly note instead of erroring. (`server/services/claudeCodeUsage.js`, `server/routes/usage.js`, `client/src/pages/UsagePage.jsx`)
+
## Fixed
- **Scheduled improvement tasks no longer run twice.** When the periodic evaluation loop and the improvement-check timer fired close together, each took its own snapshot of the pending-task list, both found no matching task, and both queued an identical managed-app improvement (e.g. two overlapping `[Improvement: PortOS] Performance Analysis` runs). The `addTask` duplicate backstop that should have caught the second was silently disabled for these tasks: it read the candidate app only from top-level `taskData.app`, but queue-path improvement tasks arrive pre-built (`raw: true`) with the app in `metadata.app` — so the app-scoped dedup compared `null` against the existing task's `portos` and never matched. `addTask` now reads the candidate app from `taskData.metadata?.app` too, so the second concurrent queue is correctly rejected. (`server/services/cosTaskStore.js`)
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index dd98ea578a..054eefcf74 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -1,10 +1,10 @@
import { useState, useEffect } from 'react';
-import { RefreshCw } from 'lucide-react';
+import { RefreshCw, Clock, AlertTriangle } from 'lucide-react';
import * as api from '../services/api';
import BrailleSpinner from '../components/BrailleSpinner';
import { formatCompactCount } from '../utils/formatters';
-export function UsagePage() {
+function InternalUsageMetrics() {
const [usage, setUsage] = useState(null);
const [loading, setLoading] = useState(true);
@@ -34,7 +34,7 @@ export function UsagePage() {
return (
<div className="space-y-6">
- <h1 className="text-2xl font-bold text-white">Usage Metrics</h1>
+ <h2 className="text-lg font-semibold text-white">PortOS AI Usage</h2>
{/* Summary Stats */}
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4">
@@ -160,4 +160,136 @@ export function UsagePage() {
);
}
+// Color a usage meter by how much is consumed: comfortable → warning → critical.
+function meterColor(percentUsed) {
+ if (percentUsed == null) return 'bg-gray-500';
+ if (percentUsed >= 90) return 'bg-port-error';
+ if (percentUsed >= 70) return 'bg-port-warning';
+ return 'bg-port-success';
+}
+
+function UsageMeter({ limit }) {
+ const used = limit.percentUsed ?? 0;
+ const remaining = limit.percentRemaining;
+ return (
+ <div className="py-2 border-b border-port-border last:border-0">
+ <div className="flex items-baseline justify-between gap-2 mb-1">
+ <span className="text-white text-sm sm:text-base">{limit.label}</span>
+ <span className="text-xs sm:text-sm text-gray-400">
+ {remaining == null ? '—' : `${remaining}% left`}
+ </span>
+ </div>
+ <div className="h-2 rounded-full bg-port-bg overflow-hidden">
+ <div
+ className={`h-full rounded-full ${meterColor(limit.percentUsed)}`}
+ style={{ width: `${Math.min(100, Math.max(0, used))}%` }}
+ />
+ </div>
+ <div className="flex items-center justify-between mt-1">
+ <span className="text-[10px] sm:text-xs text-gray-500">{used}% used</span>
+ {limit.resetsAt && (
+ <span className="text-[10px] sm:text-xs text-gray-500 flex items-center gap-1">
+ <Clock size={11} /> resets {limit.resetsAt}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// Claude Code SUBSCRIPTION rate-limit usage, parsed server-side from the CLI
+// `/usage` output. Self-contained: owns its own fetch/loading/error state so it
+// always renders (above the PortOS-internal token metrics below).
+function ClaudeCodeUsagePanel() {
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(false);
+
+ const load = async (refresh = false) => {
+ setLoading(true);
+ setError(false);
+ const result = await api.getClaudeCodeUsage({ refresh }).catch(() => null);
+ if (!result) setError(true);
+ setData(result);
+ setLoading(false);
+ };
+
+ useEffect(() => { load(); }, []);
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">
+ <div className="flex items-center justify-between mb-3">
+ <h2 className="text-lg font-semibold text-white">Claude Code Subscription</h2>
+ <button
+ onClick={() => load(true)}
+ disabled={loading}
+ className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-400 hover:text-white disabled:opacity-50"
+ title="Refresh from the Claude Code CLI"
+ >
+ <RefreshCw size={15} className={loading ? 'animate-spin' : ''} /> Refresh
+ </button>
+ </div>
+
+ {loading && !data && (
+ <div className="py-6"><BrailleSpinner text="Reading Claude Code usage" /></div>
+ )}
+
+ {!loading && error && (
+ <div className="flex items-start gap-2 text-sm text-gray-400 py-2">
+ <AlertTriangle size={16} className="text-port-warning mt-0.5 shrink-0" />
+ <span>
+ Couldn't read Claude Code usage. The <code className="text-gray-300">claude</code> CLI must be
+ installed and signed in on this machine.
+ </span>
+ </div>
+ )}
+
+ {data && (
+ <div className="space-y-3">
+ {data.limits?.length > 0 ? (
+ <div>
+ {data.limits.map((limit) => (
+ <UsageMeter key={limit.key} limit={limit} />
+ ))}
+ </div>
+ ) : (
+ <div className="text-gray-500 text-sm">No rate-limit data reported</div>
+ )}
+
+ {data.activity?.length > 0 && (
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-1">
+ {data.activity.map((a) => (
+ <div key={a.period} className="bg-port-bg border border-port-border rounded-lg p-3">
+ <div className="text-xs text-gray-400 mb-1">{a.period}</div>
+ <div className="text-sm text-white">
+ {formatCompactCount(a.requests)} requests
+ <span className="mx-2 text-gray-600">•</span>
+ {formatCompactCount(a.sessions)} sessions
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {data.approximate && (
+ <p className="text-[10px] sm:text-xs text-gray-500">
+ Approximate — based on local sessions on this machine only; does not include other devices or claude.ai.
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function UsagePage() {
+ return (
+ <div className="space-y-6">
+ <h1 className="text-2xl font-bold text-white">Usage</h1>
+ <ClaudeCodeUsagePanel />
+ <InternalUsageMetrics />
+ </div>
+ );
+}
+
export default UsagePage;
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 825e3bc98b..7dc74e036c 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -94,6 +94,12 @@ export const getUsage = () => request('/usage');
export const getUsageRaw = () => request('/usage/raw');
export const resetUsage = () => request('/usage', { method: 'DELETE' });
+// Claude Code subscription rate-limit usage (parsed from the CLI `/usage` output).
+// Callers own their own inline error UI, so default to silent to avoid a toast
+// on machines without the `claude` CLI.
+export const getClaudeCodeUsage = ({ refresh = false, ...options } = {}) =>
+ request(`/usage/claude-code${refresh ? '?refresh=1' : ''}`, { silent: true, ...options });
+
// Backup
export const getBackupStatus = (options) => request('/backup/status', options);
export const triggerBackup = (options) => request('/backup/run', { method: 'POST', ...options });
diff --git a/server/routes/usage.js b/server/routes/usage.js
index 6ecd3cd69d..f9e4663705 100644
--- a/server/routes/usage.js
+++ b/server/routes/usage.js
@@ -1,5 +1,6 @@
import { Router } from 'express';
import * as usage from '../services/usage.js';
+import { getClaudeCodeUsage } from '../services/claudeCodeUsage.js';
import { asyncHandler } from '../lib/errorHandler.js';
const router = Router();
@@ -10,6 +11,15 @@ router.get('/', asyncHandler(async (req, res) => {
res.json(summary);
}));
+// GET /api/usage/claude-code - Claude Code SUBSCRIPTION rate-limit usage,
+// parsed from the CLI's `/usage` output. Distinct from the PortOS-internal
+// token accounting above. `?refresh=1` bypasses the 60s cache.
+router.get('/claude-code', asyncHandler(async (req, res) => {
+ const refresh = req.query.refresh === '1' || req.query.refresh === 'true';
+ const data = await getClaudeCodeUsage({ refresh });
+ res.json(data);
+}));
+
// GET /api/usage/raw - Get raw usage data
router.get('/raw', asyncHandler(async (req, res) => {
const data = usage.getUsage();
diff --git a/server/services/claudeCodeUsage.js b/server/services/claudeCodeUsage.js
new file mode 100644
index 0000000000..e94170c5cb
--- /dev/null
+++ b/server/services/claudeCodeUsage.js
@@ -0,0 +1,198 @@
+import { spawn } from 'child_process';
+import { stripAnsi } from '../lib/ansiStrip.js';
+
+/**
+ * Claude Code SUBSCRIPTION usage — the plan rate-limit numbers surfaced by the
+ * `/usage` slash command (session %, weekly %, per-model weekly %, reset times).
+ *
+ * This is DISTINCT from `server/services/usage.js`, which is PortOS's own
+ * accounting of AI-toolkit provider runs. Here we shell out to the Claude Code
+ * CLI in print mode and parse its human-readable `/usage` output into JSON:
+ *
+ * echo "/usage" | claude -p
+ *
+ * The CLI has no structured usage endpoint — the text output is the only
+ * surface — so the parser below is deliberately tolerant of missing lines and
+ * strips ANSI. Running `/usage` is read-only and consumes 0 tokens, so it is
+ * safe to call on page load (does NOT violate the no-cold-bootstrap-LLM policy:
+ * it's a direct user action and no provider call is made).
+ *
+ * The numbers are a per-machine local approximation — the CLI itself notes they
+ * "do not include other devices or claude.ai" — which is preserved verbatim in
+ * `raw` for display.
+ */
+
+const CLI_COMMAND = 'claude';
+const CLI_ARGS = ['-p'];
+const STDIN_INPUT = '/usage\n';
+const SPAWN_TIMEOUT_MS = 60_000;
+const CACHE_TTL_MS = 60_000;
+
+const toInt = (s) => (s == null ? null : parseInt(String(s).replace(/,/g, ''), 10));
+
+/**
+ * Parse one `Current …: N% used · resets <when> (<tz>)` limit line.
+ * Returns null when the line isn't a limit line.
+ */
+function parseLimitLine(line) {
+ const match = line.match(/^(Current [^:]+):\s*(\d+)%\s*used(?:\s*·\s*resets\s+(.+?))?$/i);
+ if (!match) return null;
+ const label = match[1].trim();
+ const percentUsed = toInt(match[2]);
+ let resetsAt = match[3] ? match[3].trim() : null;
+ let timezone = null;
+ if (resetsAt) {
+ const tz = resetsAt.match(/\(([^)]+)\)\s*$/);
+ if (tz) {
+ timezone = tz[1];
+ resetsAt = resetsAt.slice(0, tz.index).trim();
+ }
+ }
+ // Derive a stable key + optional model from the label.
+ // "Current session" → session; "Current week (all models)" → week (model: all models);
+ // "Current week (Fable)" → week (model: Fable).
+ const scopeMatch = label.match(/^Current\s+(\w+)(?:\s*\(([^)]+)\))?/i);
+ const scope = scopeMatch ? scopeMatch[1].toLowerCase() : label.toLowerCase();
+ const model = scopeMatch && scopeMatch[2] ? scopeMatch[2].trim() : null;
+ const key = model ? `${scope}:${model.toLowerCase().replace(/\s+/g, '-')}` : scope;
+ return {
+ key,
+ label,
+ scope,
+ model,
+ percentUsed,
+ percentRemaining: percentUsed == null ? null : Math.max(0, 100 - percentUsed),
+ resetsAt,
+ timezone,
+ };
+}
+
+/**
+ * Parse a `Last 24h · 1700 requests · 18 sessions` activity header.
+ */
+function parseActivityHeader(line) {
+ const match = line.match(/^(Last\s+\S+)\s*·\s*([\d,]+)\s*requests\s*·\s*([\d,]+)\s*sessions/i);
+ if (!match) return null;
+ return { period: match[1].trim(), requests: toInt(match[2]), sessions: toInt(match[3]), notes: [] };
+}
+
+/**
+ * Pure parser: `/usage` text → structured object. Tolerant of absent lines so a
+ * future CLI format tweak degrades gracefully instead of throwing.
+ */
+export function parseUsageOutput(text) {
+ const raw = (text || '').trim();
+ const lines = stripAnsi(raw).split('\n');
+
+ let plan = 'unknown';
+ if (/using your subscription/i.test(raw)) plan = 'subscription';
+ else if (/pay[- ]as[- ]you[- ]go|api\b/i.test(raw)) plan = 'api';
+
+ const limits = [];
+ const activity = [];
+ let currentActivity = null;
+
+ for (const rawLine of lines) {
+ const line = rawLine.replace(/\s+$/, '');
+ const trimmed = line.trim();
+
+ const limit = parseLimitLine(trimmed);
+ if (limit) {
+ limits.push(limit);
+ currentActivity = null;
+ continue;
+ }
+
+ const activityHeader = parseActivityHeader(trimmed);
+ if (activityHeader) {
+ currentActivity = activityHeader;
+ activity.push(currentActivity);
+ continue;
+ }
+
+ // Indented detail lines belong to the most recent activity block.
+ if (currentActivity && /^\s{2,}\S/.test(rawLine) && trimmed) {
+ currentActivity.notes.push(trimmed);
+ } else if (trimmed === '') {
+ // blank line ends an activity block's detail run
+ currentActivity = null;
+ }
+ }
+
+ const approximate = /does not include other devices/i.test(raw);
+
+ return { plan, limits, activity, approximate, raw };
+}
+
+// --- fetch + cache -------------------------------------------------------
+
+let cache = null; // { data, at }
+let inflight = null;
+
+/**
+ * Spawn the Claude Code CLI in print mode, feed `/usage` on stdin, and resolve
+ * with the buffered stdout. Rejects on spawn error, timeout, or non-zero exit
+ * with no usable output. Runs outside the Express request lifecycle, so the
+ * child's error/timeout paths are handled explicitly here rather than bubbling.
+ */
+function runUsageCli() {
+ return new Promise((resolve, reject) => {
+ const child = spawn(CLI_COMMAND, CLI_ARGS, { stdio: ['pipe', 'pipe', 'pipe'] });
+ let stdout = '';
+ let stderr = '';
+ let settled = false;
+
+ const timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ child.kill('SIGKILL');
+ reject(new Error(`Claude Code /usage timed out after ${SPAWN_TIMEOUT_MS}ms`));
+ }, SPAWN_TIMEOUT_MS);
+
+ child.stdout.on('data', (d) => { stdout += d.toString(); });
+ child.stderr.on('data', (d) => { stderr += d.toString(); });
+
+ child.on('error', (err) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ const hint = err.code === 'ENOENT'
+ ? 'Claude Code CLI (`claude`) not found on PATH'
+ : err.message;
+ reject(new Error(`Failed to run Claude Code /usage: ${hint}`));
+ });
+
+ child.on('close', (code) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (stdout.trim()) return resolve(stdout);
+ reject(new Error(`Claude Code /usage exited ${code} with no output${stderr ? `: ${stderr.trim()}` : ''}`));
+ });
+
+ child.stdin.write(STDIN_INPUT);
+ child.stdin.end();
+ });
+}
+
+/**
+ * Get parsed Claude Code subscription usage, cached for 60s. Concurrent callers
+ * share one in-flight CLI run. `refresh: true` bypasses the cache.
+ */
+export async function getClaudeCodeUsage({ refresh = false } = {}) {
+ if (!refresh && cache && Date.now() - cache.at < CACHE_TTL_MS) {
+ return cache.data;
+ }
+ if (inflight) return inflight;
+
+ inflight = runUsageCli()
+ .then((stdout) => {
+ const parsed = parseUsageOutput(stdout);
+ const data = { ...parsed, fetchedAt: new Date().toISOString() };
+ cache = { data, at: Date.now() };
+ return data;
+ })
+ .finally(() => { inflight = null; });
+
+ return inflight;
+}
diff --git a/server/services/claudeCodeUsage.test.js b/server/services/claudeCodeUsage.test.js
new file mode 100644
index 0000000000..dc24bbef1e
--- /dev/null
+++ b/server/services/claudeCodeUsage.test.js
@@ -0,0 +1,102 @@
+import { describe, it, expect } from 'vitest';
+import { parseUsageOutput } from './claudeCodeUsage.js';
+
+// Real `echo "/usage" | claude -p` output captured from a subscription install.
+const SAMPLE = `You are currently using your subscription to power your Claude Code usage
+
+Current session: 4% used · resets Jul 7 at 2:59am (America/Los_Angeles)
+Current week (all models): 94% used · resets Jul 7 at 1:59pm (America/Los_Angeles)
+Current week (Fable): 76% used · resets Jul 7 at 1:59pm (America/Los_Angeles)
+
+What's contributing to your limits usage?
+Approximate, based on local sessions on this machine — does not include other devices or claude.ai. Behaviors are independent characteristics, not a breakdown.
+
+Last 24h · 1700 requests · 18 sessions
+ 76% of your usage came from subagent-heavy sessions
+ 70% of your usage was at >150k context
+ Top skills: /do:pr 9%, /simplify 3%
+ Top subagents: general-purpose 15%
+ Top plugins: do 15%, superpowers 8%
+
+Last 7d · 17034 requests · 125 sessions
+ 85% of your usage came from subagent-heavy sessions
+ Top plugins: do 22%, superpowers 5%`;
+
+describe('parseUsageOutput', () => {
+ it('detects a subscription plan', () => {
+ expect(parseUsageOutput(SAMPLE).plan).toBe('subscription');
+ });
+
+ it('parses each limit line with percent, remaining, reset time and timezone', () => {
+ const { limits } = parseUsageOutput(SAMPLE);
+ expect(limits).toHaveLength(3);
+
+ expect(limits[0]).toMatchObject({
+ key: 'session',
+ label: 'Current session',
+ scope: 'session',
+ model: null,
+ percentUsed: 4,
+ percentRemaining: 96,
+ resetsAt: 'Jul 7 at 2:59am',
+ timezone: 'America/Los_Angeles',
+ });
+
+ expect(limits[1]).toMatchObject({
+ key: 'week:all-models',
+ scope: 'week',
+ model: 'all models',
+ percentUsed: 94,
+ percentRemaining: 6,
+ });
+
+ expect(limits[2]).toMatchObject({
+ key: 'week:fable',
+ model: 'Fable',
+ percentUsed: 76,
+ percentRemaining: 24,
+ });
+ });
+
+ it('parses activity blocks with comma-separated counts and detail notes', () => {
+ const { activity } = parseUsageOutput(SAMPLE);
+ expect(activity).toHaveLength(2);
+
+ expect(activity[0]).toMatchObject({ period: 'Last 24h', requests: 1700, sessions: 18 });
+ expect(activity[0].notes).toContain('76% of your usage came from subagent-heavy sessions');
+ expect(activity[0].notes).toContain('Top plugins: do 15%, superpowers 8%');
+
+ expect(activity[1]).toMatchObject({ period: 'Last 7d', requests: 17034, sessions: 125 });
+ // The blank line before "Last 7d" must close the previous block — its notes
+ // must not leak into the 24h block.
+ expect(activity[0].notes).not.toContain('Top plugins: do 22%, superpowers 5%');
+ });
+
+ it('flags the approximate/local-only disclaimer', () => {
+ expect(parseUsageOutput(SAMPLE).approximate).toBe(true);
+ });
+
+ it('preserves the raw text for display', () => {
+ expect(parseUsageOutput(SAMPLE).raw).toContain('Current session: 4% used');
+ });
+
+ it('strips ANSI escape codes before parsing', () => {
+ const withAnsi = 'Current session: 12% used · resets Jul 7 at 2:59am (America/Los_Angeles)';
+ const { limits } = parseUsageOutput(withAnsi);
+ expect(limits[0]).toMatchObject({ percentUsed: 12, percentRemaining: 88 });
+ });
+
+ it('degrades gracefully on empty or unrecognized output', () => {
+ const empty = parseUsageOutput('');
+ expect(empty).toMatchObject({ plan: 'unknown', limits: [], activity: [], approximate: false });
+
+ const junk = parseUsageOutput('some unrelated CLI banner\nnothing useful here');
+ expect(junk.limits).toEqual([]);
+ expect(junk.activity).toEqual([]);
+ });
+
+ it('handles a limit line with no reset clause', () => {
+ const { limits } = parseUsageOutput('Current session: 50% used');
+ expect(limits[0]).toMatchObject({ percentUsed: 50, resetsAt: null, timezone: null });
+ });
+});