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
fix: render /usage reset times in the machine timezone + review fixes
Adam Eivyd6bcdc15f43b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9f29a1bdd4..7b038aa3b1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -97,7 +97,7 @@## 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`)+- **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. Reset times render in the **machine's timezone** — resolved from the OS, not the server process's env — so a server running under PM2/systemd in UTC still shows the same reset times as an interactive `/usage`, instead of UTC-shifted ones. 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`)## Fixeddiff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex 054eefcf74..ec446a0587 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -209,8 +209,13 @@ function ClaudeCodeUsagePanel() {setLoading(true);setError(false);const result = await api.getClaudeCodeUsage({ refresh }).catch(() => null);- if (!result) setError(true);- setData(result);+ if (result) {+ setData(result);+ } else {+ // Keep previously-loaded meters on a transient refresh failure instead of+ // replacing them with the generic error state.+ setError(true);+ }setLoading(false);};@@ -238,8 +243,9 @@ function ClaudeCodeUsagePanel() {<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.+ {data+ ? 'Couldn’t refresh Claude Code usage — showing the last successful reading.'+ : <>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>)}diff --git a/server/services/claudeCodeUsage.js b/server/services/claudeCodeUsage.jsindex e28772e596..ecf863c0f4 100644--- a/server/services/claudeCodeUsage.js+++ b/server/services/claudeCodeUsage.js@@ -1,4 +1,5 @@import { spawn } from 'child_process';+import { existsSync, lstatSync, readlinkSync } from 'fs';import { stripAnsi } from '../lib/ansiStrip.js';/**@@ -30,6 +31,32 @@ const CACHE_TTL_MS = 60_000;const toInt = (s) => (s == null ? null : parseInt(String(s).replace(/,/g, ''), 10));+/**+ * Pull the IANA zone (e.g. `America/Los_Angeles`) out of an `/etc/localtime`+ * symlink target (`.../zoneinfo/America/Los_Angeles`). Returns null if the path+ * doesn't look like a zoneinfo link. Pure — unit-tested.+ */+export function zoneFromLocaltimeLink(link) {+ const m = (link || '').match(/zoneinfo\/(.+)$/);+ return m ? m[1] : null;+}++// Claude Code renders /usage reset times in the child process's timezone (and+// labels them with it). A server started under PM2/systemd/Docker commonly runs+// in UTC, which would shift every reset time away from what the user sees in an+// interactive terminal. Resolve the machine's real timezone from the OS —+// independent of this process's own (possibly UTC) TZ env — and pass it to the+// child so headless output matches the interactive TUI. Memoized; best-effort+// (null → inherit the process env unchanged).+let cachedSystemTz;+function systemTimeZone() {+ if (cachedSystemTz !== undefined) return cachedSystemTz;+ cachedSystemTz = existsSync('/etc/localtime') && lstatSync('/etc/localtime').isSymbolicLink()+ ? zoneFromLocaltimeLink(readlinkSync('/etc/localtime'))+ : null;+ return cachedSystemTz;+}+/*** Parse one `Current …: N% used · resets <when> (<tz>)` limit line.* Returns null when the line isn't a limit line.@@ -137,7 +164,9 @@ let inflight = null;*/function runUsageCli() {return new Promise((resolve, reject) => {- const child = spawn(CLI_COMMAND, CLI_ARGS, { stdio: ['pipe', 'pipe', 'pipe'] });+ const tz = systemTimeZone();+ const env = tz ? { ...process.env, TZ: tz } : process.env;+ const child = spawn(CLI_COMMAND, CLI_ARGS, { stdio: ['pipe', 'pipe', 'pipe'], env });let stdout = '';let stderr = '';let settled = false;@@ -151,6 +180,11 @@ function runUsageCli() {child.stdout.on('data', (d) => { stdout += d.toString(); });child.stderr.on('data', (d) => { stderr += d.toString(); });+ // Same crash class as the stdin guard below: a pipe read error (e.g. the+ // child is SIGKILL'd mid-stream) would otherwise go unhandled and crash the+ // process. The 'close'/'error'/timeout handlers still settle the promise.+ child.stdout.on('error', () => {});+ child.stderr.on('error', () => {});child.on('error', (err) => {if (settled) return;diff --git a/server/services/claudeCodeUsage.test.js b/server/services/claudeCodeUsage.test.jsindex dc24bbef1e..4b29989630 100644--- a/server/services/claudeCodeUsage.test.js+++ b/server/services/claudeCodeUsage.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { parseUsageOutput } from './claudeCodeUsage.js';+import { parseUsageOutput, zoneFromLocaltimeLink } 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@@ -99,4 +99,26 @@ describe('parseUsageOutput', () => {const { limits } = parseUsageOutput('Current session: 50% used');expect(limits[0]).toMatchObject({ percentUsed: 50, resetsAt: null, timezone: null });});++ it('keeps a reset time that has no (timezone) suffix', () => {+ const { limits } = parseUsageOutput('Current session: 10% used · resets Jul 7 at 2pm');+ expect(limits[0]).toMatchObject({ resetsAt: 'Jul 7 at 2pm', timezone: null });+ });++ it('detects an API (pay-as-you-go) plan', () => {+ expect(parseUsageOutput('You are using the Claude API (pay as you go) for usage').plan).toBe('api');+ });+});++describe('zoneFromLocaltimeLink', () => {+ it('extracts the IANA zone from an /etc/localtime symlink target', () => {+ expect(zoneFromLocaltimeLink('/var/db/timezone/zoneinfo/America/Los_Angeles')).toBe('America/Los_Angeles');+ expect(zoneFromLocaltimeLink('/usr/share/zoneinfo/Europe/Berlin')).toBe('Europe/Berlin');+ });++ it('returns null when the target is not a zoneinfo path', () => {+ expect(zoneFromLocaltimeLink('/some/other/path')).toBeNull();+ expect(zoneFromLocaltimeLink('')).toBeNull();+ expect(zoneFromLocaltimeLink(null)).toBeNull();+ });});