diff --git a/dotfiles/quickshell/HyprChrome/Widgets/Bar/Claude/ClaudePanel.qml b/dotfiles/quickshell/HyprChrome/Widgets/Bar/Claude/ClaudePanel.qml new file mode 100644 index 0000000..51c7106 --- /dev/null +++ b/dotfiles/quickshell/HyprChrome/Widgets/Bar/Claude/ClaudePanel.qml @@ -0,0 +1,149 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import qs.HyprChrome.Theme +import qs.HyprChrome.Widgets.Bar.Panels +import qs.HyprChrome.Widgets.Bar.Vitals + +// Claude subscription limits on the rail: the 5-hour session window and the +// weekly one, plus any per-model weekly caps the plan reports. +BarPanel { + id: claude + + // Overridable so the headless render can stage it without the network. + property var fiveHour: usage.fiveHour + property var sevenDay: usage.sevenDay + property var extra: usage.extra + property string error: usage.error + property bool ready: usage.ready + + readonly property var usage: ClaudeState {} + + panelId: "CLD" + title: "CLAUDE" + meta: claude.error !== "" ? (claude.ready ? "STALE" : "OFFLINE") : claude.ready ? "LIMITS" : "PRIMING" + + // Ticks the reset countdowns without re-polling. + property date now: new Date() + Timer { + interval: 30000 + running: true + repeat: true + onTriggered: claude.now = new Date() + } + + implicitWidth: claude.expanded + ? Math.max(claude.headerMinWidth, claude.padding * 2 + body.width) + : Math.max(claude.headerMinWidth, claude.briefLeft + brief.implicitWidth + claude.padding) + + function fraction(w) { + return w ? Math.max(0, Math.min(1, w.utilization / 100)) : 0; + } + + function pct(w) { + return w ? Math.round(w.utilization) + "%" : "--"; + } + + function until(w) { + if (!w || !w.resets_at) + return ""; + const mins = Math.max(0, Math.round((new Date(w.resets_at) - claude.now) / 60000)); + if (mins >= 1440) + return `${Math.floor(mins / 1440)}D ${Math.floor(mins % 1440 / 60)}H`; + if (mins >= 60) + return `${Math.floor(mins / 60)}H ${mins % 60}M`; + return `${mins}M`; + } + + function tone(w) { + const f = claude.fraction(w); + return !claude.ready ? Theme.disabled : f >= 0.85 ? Theme.hot : Theme.text; + } + + summary: Row { + id: brief + spacing: 10 + + Repeater { + model: [ + { label: "5H", window: claude.fiveHour }, + { label: "7D", window: claude.sevenDay } + ] + + Row { + required property var modelData + spacing: 4 + anchors.verticalCenter: parent.verticalCenter + + Text { + anchors.verticalCenter: parent.verticalCenter + text: parent.modelData.label + color: Theme.muted + font.family: Theme.microFont + font.pixelSize: 10 + } + + Text { + anchors.verticalCenter: parent.verticalCenter + text: claude.pct(parent.modelData.window) + color: claude.tone(parent.modelData.window) + font.family: Theme.displayFont + font.pixelSize: 13 + font.bold: true + } + } + } + } + + Column { + id: body + width: 260 + spacing: 5 + + Repeater { + model: [ + { label: "SESSION", window: claude.fiveHour }, + { label: "WEEKLY", window: claude.sevenDay } + ].concat(claude.extra) + + Column { + required property var modelData + width: body.width + spacing: 2 + + VitalRow { + width: parent.width + labelWidth: 64 + label: parent.modelData.label + value: claude.fraction(parent.modelData.window) + readout: claude.pct(parent.modelData.window) + ready: claude.ready && !!parent.modelData.window + } + + Text { + x: 64 + visible: text !== "" + text: { + const t = claude.until(parent.modelData.window); + return t ? `RESETS IN ${t}` : ""; + } + color: Theme.muted + font.family: Theme.microFont + font.pixelSize: 9 + font.letterSpacing: 1.2 + } + } + } + + Text { + width: body.width + visible: claude.error !== "" + text: claude.error.toUpperCase() + color: Theme.hot + font.family: Theme.microFont + font.pixelSize: 9 + font.letterSpacing: 1.2 + wrapMode: Text.WordWrap + } + } +} diff --git a/dotfiles/quickshell/HyprChrome/Widgets/Bar/Claude/ClaudeState.qml b/dotfiles/quickshell/HyprChrome/Widgets/Bar/Claude/ClaudeState.qml new file mode 100644 index 0000000..a72aa4f --- /dev/null +++ b/dotfiles/quickshell/HyprChrome/Widgets/Bar/Claude/ClaudeState.qml @@ -0,0 +1,69 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import Quickshell.Io + +// Claude subscription limits, polled through `claude-usage` (pkgs/claude-usage.nix), +// which reuses Claude Code's OAuth login and prints the usage endpoint's JSON. +QtObject { + id: root + + // Each window is { utilization: 0..100, resets_at: ISO string } or null. + property var fiveHour: null + property var sevenDay: null + // Per-model weekly windows the plan reports, as [{ label, window }]. + property var extra: [] + property string error: "" + property bool ready: false + + // The endpoint is rate-limited and the numbers move slowly. + property int interval: 300000 + + readonly property var proc: Process { + id: proc + command: ["claude-usage"] + + stdout: StdioCollector { + onStreamFinished: root.ingest(this.text) + } + } + + readonly property var poll: Timer { + interval: root.interval + running: true + repeat: true + triggeredOnStart: true + onTriggered: { + if (!proc.running) + proc.running = true; + } + } + + function ingest(text: string): void { + let msg; + try { + msg = JSON.parse(text); + } catch (e) { + root.error = "no output"; + return; + } + if (msg.error) { + // Keep the last good numbers; a failed poll is not zero usage. + root.error = msg.error; + return; + } + root.error = ""; + root.fiveHour = msg.five_hour ?? null; + root.sevenDay = msg.seven_day ?? null; + + const found = []; + for (const key of Object.keys(msg)) { + const m = key.match(/^seven_day_(\w+)$/); + const w = msg[key]; + if (m && w && typeof w.utilization === "number") + found.push({ label: m[1].toUpperCase().replace(/_/g, " "), window: w }); + } + root.extra = found; + root.ready = true; + } +} diff --git a/dotfiles/quickshell/HyprChrome/Widgets/Bar/HyprChromeBar.qml b/dotfiles/quickshell/HyprChrome/Widgets/Bar/HyprChromeBar.qml index 68edbf2..c319c1e 100644 --- a/dotfiles/quickshell/HyprChrome/Widgets/Bar/HyprChromeBar.qml +++ b/dotfiles/quickshell/HyprChrome/Widgets/Bar/HyprChromeBar.qml @@ -5,6 +5,7 @@ import Quickshell import Quickshell.Wayland import qs.HyprChrome.Theme import qs.HyprChrome.Widgets.Bar.Luna +import qs.HyprChrome.Widgets.Bar.Claude import qs.HyprChrome.Widgets.Bar.Host import qs.HyprChrome.Widgets.Bar.Vitals import qs.HyprChrome.Widgets.Bar.Workspaces @@ -87,8 +88,8 @@ PanelWindow { // // The zone still follows the target height, so tiled windows reflow once // per toggle, at the start, and slide while the panels animate. - readonly property real expandedContent: Math.max(hostPanel.expandedHeight, workspacesPanel.expandedHeight, vitalsPanel.expandedHeight, lunaPanel.expandedHeight, trayPanel.expandedHeight) + window.margin * 2 - readonly property real contentHeight: Math.max(hostPanel.targetHeight, workspacesPanel.targetHeight, vitalsPanel.targetHeight, lunaPanel.targetHeight, trayPanel.targetHeight) + window.margin * 2 + readonly property real expandedContent: Math.max(hostPanel.expandedHeight, workspacesPanel.expandedHeight, vitalsPanel.expandedHeight, lunaPanel.expandedHeight, claudePanel.expandedHeight, trayPanel.expandedHeight) + window.margin * 2 + readonly property real contentHeight: Math.max(hostPanel.targetHeight, workspacesPanel.targetHeight, vitalsPanel.targetHeight, lunaPanel.targetHeight, claudePanel.targetHeight, trayPanel.targetHeight) + window.margin * 2 implicitHeight: Math.round(window.expandedContent) @@ -161,6 +162,19 @@ PanelWindow { id: lunaPanel expanded: window.expanded + // Claude butts against its right edge. + rightChamfer: false + + toggleOnClick: false + Layout.fillHeight: true + } + + ClaudePanel { + id: claudePanel + + expanded: window.expanded + leftChamfer: false + toggleOnClick: false Layout.fillHeight: true } diff --git a/dotfiles/quickshell/tests/ClaudePanelHeadless.qml b/dotfiles/quickshell/tests/ClaudePanelHeadless.qml new file mode 100644 index 0000000..0479aec --- /dev/null +++ b/dotfiles/quickshell/tests/ClaudePanelHeadless.qml @@ -0,0 +1,59 @@ +import QtQuick +import qs.HyprChrome.Widgets.Bar.Claude + +// The rail's claude panel collapsed and expanded, healthy and failing. +// +// ./tools/quickshell-preview/render.sh \ +// tests/ClaudePanelHeadless.qml \ +// .artifacts/quickshell-preview/claude-panel.png 640 420 +Rectangle { + width: 640 + height: 420 + color: "#0f1012" + + readonly property var soon: new Date(Date.now() + 2 * 3600000 + 17 * 60000).toISOString() + readonly property var later: new Date(Date.now() + 4 * 86400000 + 5 * 3600000).toISOString() + + Row { + x: 16 + y: 16 + spacing: 24 + + Column { + spacing: 12 + + ClaudePanel { + expanded: false + ready: true + fiveHour: ({ utilization: 42, resets_at: soon }) + sevenDay: ({ utilization: 91, resets_at: later }) + } + + ClaudePanel { + expanded: false + ready: false + error: "token refresh HTTP 400" + } + } + + Column { + spacing: 12 + + ClaudePanel { + expanded: true + ready: true + fiveHour: ({ utilization: 42, resets_at: soon }) + sevenDay: ({ utilization: 91, resets_at: later }) + extra: [{ label: "SONNET", window: { utilization: 12, resets_at: later } }] + } + + ClaudePanel { + expanded: true + ready: true + error: "usage HTTP 429" + fiveHour: ({ utilization: 8, resets_at: soon }) + sevenDay: ({ utilization: 30, resets_at: later }) + } + } + } +} diff --git a/hosts/terra/home.nix b/hosts/terra/home.nix index d47b196..9728ded 100644 --- a/hosts/terra/home.nix +++ b/hosts/terra/home.nix @@ -1,6 +1,7 @@ { pkgs, unstable, inputs, ... }: let tome = pkgs.callPackage ../../pkgs/tome.nix { src = inputs.tome; }; + claude-usage = pkgs.callPackage ../../pkgs/claude-usage.nix { }; # SUDO_ASKPASS helper: shows sudo's password prompt in quickshell # (HyprChrome/Widgets/Askpass) instead of the terminal. sudo doesn't speak @@ -95,6 +96,7 @@ in pkgs.opencode pkgs.quickshell qs-askpass + claude-usage pkgs.github-cli pkgs.tea pkgs.docker-compose diff --git a/pkgs/claude-usage.nix b/pkgs/claude-usage.nix new file mode 100644 index 0000000..195c78e --- /dev/null +++ b/pkgs/claude-usage.nix @@ -0,0 +1,11 @@ +{ writeShellApplication, coreutils, curl, jq, util-linux }: + +# Prints the Claude subscription's rate-limit windows as one JSON line, for the +# rail's CLD panel. Reuses Claude Code's OAuth login rather than a key of its +# own, so there is nothing to provision; always exits 0 with `{"error": ...}` +# so the panel can show why instead of going blank. +writeShellApplication { + name = "claude-usage"; + runtimeInputs = [ coreutils curl jq util-linux ]; + text = builtins.readFile ./claude-usage.sh; +} diff --git a/pkgs/claude-usage.sh b/pkgs/claude-usage.sh new file mode 100644 index 0000000..b5fc1d2 --- /dev/null +++ b/pkgs/claude-usage.sh @@ -0,0 +1,57 @@ +creds="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/.credentials.json" + +fail() { + jq -cn --arg e "$1" '{error: $e}' + exit 0 +} + +[ -r "$creds" ] || fail "not logged in" + +# The refresh token rotates, so the new one must be written back or the CLI's +# next refresh fails and forces a re-login. +refresh() { + local rt scope body code tmp + rt="$(jq -r '.claudeAiOauth.refreshToken // empty' "$creds")" + [ -n "$rt" ] || fail "no refresh token" + scope="$(jq -r '.claudeAiOauth.scopes // [] | join(" ")' "$creds")" + body="$(mktemp)" + code="$(jq -cn --arg rt "$rt" --arg s "$scope" \ + '{grant_type: "refresh_token", refresh_token: $rt, + client_id: "9d1c250a-e61b-44d9-88ed-5944d1962f5e", scope: $s}' \ + | curl -s -m 20 -o "$body" -w '%{http_code}' \ + https://platform.claude.com/v1/oauth/token \ + -H 'Content-Type: application/json' --data-binary @-)" || code=000 + if [ "$code" != 200 ]; then + rm -f "$body" + fail "token refresh HTTP $code" + fi + tmp="$(mktemp "$creds.XXXXXX")" + chmod 600 "$tmp" + jq --slurpfile r "$body" '.claudeAiOauth += { + accessToken: $r[0].access_token, + refreshToken: ($r[0].refresh_token // .claudeAiOauth.refreshToken), + expiresAt: (now * 1000 + $r[0].expires_in * 1000 | floor) + }' "$creds" > "$tmp" && mv "$tmp" "$creds" + rm -f "$body" "$tmp" +} + +expired() { + jq -e '(.claudeAiOauth.expiresAt // 0) < (now * 1000 + 300000)' "$creds" >/dev/null +} + +if expired; then + exec 9>"${XDG_RUNTIME_DIR:-/tmp}/claude-usage.lock" + flock 9 + # Another run may have refreshed while this one waited. + if expired; then refresh; fi +fi + +token="$(jq -r '.claudeAiOauth.accessToken // empty' "$creds")" +[ -n "$token" ] || fail "not logged in" + +body="$(curl -s -m 20 -w '\n%{http_code}' https://api.anthropic.com/api/oauth/usage \ + -H "Authorization: Bearer $token" \ + -H 'anthropic-beta: oauth-2025-04-20')" || fail "usage request failed" +code="${body##*$'\n'}" +[ "$code" = 200 ] || fail "usage HTTP $code" +printf '%s' "${body%$'\n'*}" | jq -c . || fail "bad usage response"