- Python 70.9%
- QML 28.8%
- Shell 0.2%
| backend | ||
| contents | ||
| docs | ||
| tests | ||
| updater | ||
| .gitignore | ||
| AUDIT.md | ||
| build-release.sh | ||
| install.sh | ||
| Makefile | ||
| metadata.json | ||
| README.md | ||
| uninstall.sh | ||
AI Quota Plasma widget
A Plasma 6 panel widget for Codex, Claude Code and OpenCode Go subscription allowances, plus Mistral monthly spend.
Quick start
- Install from a Git checkout:
git clone https://git.tsbprodesk.co.uk/localuser/quota.git && cd quota && ./install.sh. - Add the widget: use Plasma's widget chooser (Add Widgets) to add AI Quota to a panel.
- Sign in: open Settings with the gear button and use each provider card's Sign in or setup fields.
| Panel | Claude page | Settings |
|---|---|---|
![]() |
![]() |
![]() |
Features
- Codex first, followed by enabled Claude Code, OpenCode Go and Mistral tabs. A small settings button on the right opens provider settings and updates together.
- Compact panel percentages and the original number-in-ring/progress-bar layout. Percentages read as N% left (remaining allowance), identified in tooltips and accessibility labels. Reset countdowns include absolute-time tooltips.
- Extra Codex accounts: Add Codex account (+) in Settings adds another Codex tab (numbered badge) with its own name, Pi provider name, credential sources, widget login and taskbar choices.
- Daily API-equivalent cost (7d/30d, plus an all-time total) for Claude (Pi session logs) and Codex (Pi session logs plus local Codex CLI and VS Code extension sessions); Mistral's Pi-log estimate also shows its all-time spend.
- Usage statistics page (chart button beside Settings): total API-equivalent cost and tokens across all providers, then per provider, for the last 7 days, 30 days or all time (all time by default; the choice is remembered per widget), with input, output, cache-read and cache-write token breakdowns. Optional Merge provider variants in Settings groups OpenAI/Codex, Anthropic/Claude and Mistral accounts (off by default).
- Weekly and monthly pace with forecast details on hover, Codex credits below pace and above banked resets, Claude billing information, and the Mistral monthly spend against its budget - estimated locally from Pi session logs, or the console's real account-wide spend when a console cookie is saved. Unreported values are not treated as zero or disabled.
- Last-good values remain visible after refresh failures, with a prominent stale warning and the last successful refresh time. Expired reset windows show Reset due and keep the previous values; they are not treated as a new allowance.
- Provider enable/disable and on-demand setup instructions in Settings. Disabled providers have no tab and are not polled by that widget instance. Claude's one-time authorisation code can be entered in a masked widget field but is never stored in configuration. Widget-login tokens live only in the backend's private
0600credential file. - Automatic, all-selected-limits and summary panel modes. Automatic mode summarises the most constrained selected allowance on narrow panels; vertical panels use an icon with full details in the tooltip.
- Native theme icons, keyboard-operable panel control and named quota visibility checkboxes. Space/Enter opens details; Escape closes them.
- One shared user-service backend for all displays/widget instances. Concurrent requests share provider work and cached results.
- Git updates from the repository's latest default-branch commit. Checks never install. Installation is always explicitly confirmed.
Requirements
- KDE Plasma 6. The previous target is Plasma 6.7; native minimum-version/theme/accessibility testing remains outstanding.
- Python 3.10+ at
/usr/bin/python3, Git,/bin/sh, and user systemd. - Qt 6
qmlformatwith--ignore-settingssupport for pre-install QML validation, usually supplied by your distribution's Qt 6 declarative/development tools. The installer prefersqmlformat6,/usr/lib/qt6/bin/qmlformatand/usr/lib64/qt6/bin/qmlformatbefore unversionedqmlformat, and verifies the version and required option. An unversioned command can still point to Qt 5 on a Plasma 6 desktop. - A ChatGPT/Codex OAuth login (Codex CLI with app-server support, Pi or Widget login); a Claude subscription OAuth login (Claude Code, Pi or Widget login), an OpenCode Go dashboard login (workspace ID and
authcookie, set in the widget or in Pi'sauth.json) and a Mistral API key in Pi for those optional providers.
No Nerd Font or third-party Python runtime dependencies are required. kpackagetool6 is no longer used for upgrades: the user-local applet directory is staged/replaced with the same app ID, avoiding its numeric-version restriction without removing widget configuration.
Install or migrate from the old archive updater
Run as your desktop user, not root, from a Git checkout with a committed HEAD:
git clone https://git.tsbprodesk.co.uk/localuser/quota.git
cd quota
./install.sh
For an existing checkout, review/preserve any local work before fetching changes. Rerun ./install.sh from the updated checkout. The old archive updater cannot bootstrap this migration through its equal-version rules.
Installation:
- Validates source metadata, Python/shell/XML/SVG/QML syntax and user-local destinations.
- Stages the applet, backend, updater, wrappers, icons and user service files.
- Disables/removes the legacy automatic-update timer, excluding any running legacy updater through its lock.
- Replaces files transactionally, retaining backups until a new backend PID reports the expected version and passes health checks. Reported activation failures restore previous files and attempt to restart the previous backend.
The installer prints one progress line per phase (validating the source, staging the new files, activating the backend, waiting for the backend health check), then the final result.
Add AI Quota through Plasma's widget chooser. The backend listens on 127.0.0.1:17934. Existing panel instances may need a widget/Plasma reload after installation; the installer does not restart the desktop. Widget configuration is retained.
Installed versions are stamped as 12-character commit hash + UTC commit date, for example abcdef123456 (2026-10-16). The full commit is stored separately. A dirty checkout is labelled local changes; it is not represented as an unmodified remote revision. Source metadata.json does not contain its own commit hash, since committing that would change the hash. Git-free archive trees are not supported installation sources.
Custom user-local XDG paths are recorded in the generated services. Symlinked, overlapping or non-user-owned installation destinations are rejected. If user systemd is unavailable, files can be installed but the shared backend must be started manually in the desktop session.
Provider setup
The settings button opens a combined Settings and Updates page. Each provider's Show setup action reveals its instructions, including for disabled providers. Settings are per widget; another enabled widget may still request a provider through the shared backend.
Codex
Codex has three independently enabled credential sources, ordered in Settings. Defaults: codex-cli, pi, own, all enabled. The first working source wins; prioritising another source can select another account. The quota refresh tooltip identifies the source used.
| Source | Setup | Private plaintext store |
|---|---|---|
codex-cli |
Install Codex and run codex login. |
CLI-managed ~/.codex/auth.json |
pi |
Run /login in Pi and select OpenAI. |
<agentDir>/auth.json, openai-codex OAuth entry (or the custom Pi provider name set in Settings, e.g. openai-codex-2) |
own |
Select Sign in… on Codex's Widget login row, or run quota-codex-login. |
${XDG_CONFIG_HOME:-~/.config}/quota-widget/codex-oauth.json |
The CLI source retains the existing codex app-server --stdio initialise/account/rate-limits protocol unchanged. The CLI manages its own refresh; the backend never reads its token values or writes its credential file. Ensure codex is visible in the systemd user service's PATH, which may differ from your interactive shell. Local source status reports executable/login-file presence only, not remote validity.
Pi and Widget login query ChatGPT's usage API directly. Window durations, percentages, credits and reset timestamps map to the same app-server document shape. Missing fields stay unreported, never invented zeros. Reset-credit counts are supported; detail rows not defined by the usage reference remain unreported. API-key entries are not subscription logins. Pi uses the same agent-dir environment/locking rules as Claude below, but Codex stores actual expiry rather than Anthropic's pre-expiry deadline.
Device sign-in: select Sign in…, copy the displayed user code with Copy code, then select Open sign-in page. Enter that code in the browser. The backend polls in the background for up to 15 minutes, and Settings shows waiting, success or error. No pasted redirect/code is needed. Cancel discards only the pending flow. Closing Settings does not cancel it; reopen to see its progress. Starting again replaces any pending Codex flow across all widgets. A backend restart discards pending flows. If the server does not enable device sign-in, the widget reports that clearly; use codex login or Pi /login instead. There is no browser-PKCE fallback.
For terminal sign-in, run quota-codex-login, or python3 backend/quota_backend.py --codex-login from this checkout, in the backend's XDG environment. It prints only the verification page and public user code, then waits. Tokens and private device material are never printed or returned by the loopback API. Both interfaces use the reference Pi OpenAI client/device endpoints and token exchange redirect URI.
Sign out removes only the widget's Codex login, cancels its pending device flow and invalidates all Codex source caches. It does not change Codex CLI/Pi credentials or revoke remotely. Refresh tokens are rotating: Pi/own refresh under the shared credential lock, re-read after acquiring it, preserve unrelated JSON fields, and atomically save both tokens with mode 0600. Failed persistence or concurrent external account changes can still require signing in again. New credential directories use 0700; uninstall preserves saved logins.
Extra Codex accounts: select Add Codex account (+) next to Providers in Settings. Each account (codex-2, codex-3, ...) gets its own tab, a display Name, a Pi provider name (default openai-codex-N; log in with that name via Pi /login), its own source order (default pi, own, with codex-cli off since the CLI is shared with the main account) and its own Widget login, stored in codex-oauth-codex-N.json beside the main file so signing one out leaves the others signed in. Only one device sign-in can be pending at a time. Remove account removes it from the widget but keeps its Pi and widget login files. Accounts are stored per widget in the codexAccounts JSON setting.
Daily cost: each Codex page shows the API-equivalent cost of the last 7 or 30 UTC days (the toggle is shared with Claude). It sums Pi session costs whose provider is exactly that account's Pi provider name (so openai-codex-2 never counts towards openai-codex), and, for the main account only, local Codex CLI and VS Code extension rollouts in ${CODEX_HOME:-~/.codex}/sessions/YYYY/MM/DD/*.jsonl and archived_sessions/*.jsonl (both clients write there; set CODEX_HOME in the backend service's environment if you use a custom one). Rollout token counts are de-duplicated (re-emitted token_count events with an unchanged cumulative total are skipped), priced per model from the latest turn_context with cached input at the cached rate. Prices come from rates learned from Pi's logged costs for the same model, else a built-in OpenAI price table (longest model-name prefix), else gpt-5 rates. Compressed .jsonl.zst rollouts and forked rollouts that replay parent history are not specially handled. Figures are estimates, not money charged.
Upgrade compatibility
Existing config entry names, types and defaults are retained. Missing source keys select CLI first for Codex and Claude Code first for Claude. A valid Claude Code token outside the refresh margin is read without refresh/write-back, including HEAD's support for absent expiry metadata. Unknown Claude credential fields such as scopes, rateLimitTier and mcpOAuth survive rotation.
Old widgets omitting source parameters use the default order. New widgets still display the old quota document shape from a pre-restart backend; unknown status endpoints (404) hide status labels rather than breaking quota display. Source selection/sign-in needs the updated backend, so restart it to use those features. Source-specific caches are in memory and start empty on backend restart; no on-disk quota cache migration is needed. The installer replaces HEAD's applet/sidecars transactionally, adds both login wrappers and retains Plasma configuration and updater state. Temporary-home regression tests exercise this upgrade and compare the default CLI implementation/protocol with HEAD.
Claude Code
A Pro or Max subscription can use any of three credential sources. In the Claude provider's Settings section, toggle each source and use the up/down buttons to set priority. These settings are per widget. The default order is claude-code, pi, own, all enabled. The first working source wins, so prioritising a different source can select a different account. The last-refresh tooltip names the source used.
| Source | Setup / remedy | Private plaintext store |
|---|---|---|
claude-code |
Run claude and sign in. |
~/.claude/.credentials.json, claudeAiOauth entry |
pi |
Run /login in Pi and select Anthropic. |
<agentDir>/auth.json, anthropic OAuth entry; defaults to ~/.pi/agent/auth.json |
own |
Use Sign in… on the Widget login row in Settings, or run quota-claude-login in a terminal. |
${XDG_CONFIG_HOME:-~/.config}/quota-widget/claude-oauth.json |
Pi's agent directory honours PI_CODING_AGENT_DIR (including ~/...) in the backend service's environment, not just an interactive shell. For a custom location, set Environment=PI_CODING_AGENT_DIR=/absolute/path in systemctl --user edit quota-backend.service, then reload/restart the user service. The widget does not read KWallet.
Easiest: sign in inside the widget. Open Settings, find Claude's Widget login row and select Sign in… (or Sign in again). Your browser opens the authorisation page. After signing in, paste the full displayed code#state value into the password-masked field and press Submit or Enter. The code is cleared immediately on submit or cancel, and when Settings is hidden; it is never saved in Plasma configuration. Do not paste access or refresh tokens. Success refreshes source status and quota data, using your enabled source priority; enable/move Widget login first if you want it preferred over an existing Claude Code/Pi login.
Only one browser login can be pending across all widgets. A new start replaces it; it expires after ten minutes or a backend restart. Cancel discards the pending login, not an existing saved session. Each completion attempt consumes the pending login, including failures, so start again after an error. Concurrent login mutations are rejected while an exchange is busy. Sign out deletes only the widget's own credentials, cancels any pending login and clears the shared Claude cache. It does not sign out Claude Code/Pi or revoke the session remotely. Previously started quota requests may still finish.
Each source row shows local sign-in status and a remedy when needed. Status is read when Settings opens, after login/sign-out and after each Claude quota request. This inspection reads files only, without refreshing or checking server-side validity. Recognised plan metadata and stored expiry are available through the status API; Pi's stored expiry already includes its safety margin. A locally signed-in session may still be rejected remotely.
The terminal command remains available:
quota-claude-login
# From a source checkout, without installing:
python3 backend/quota_backend.py --claude-login
Open the printed authorisation URL, sign in, then paste Anthropic's displayed code into the terminal's hidden prompt. Both interfaces share the copy-code PKCE implementation, using Pi's client, scopes and redirect URI. OAuth state is separate from the private PKCE verifier. Widget completion requires matching returned state (code#state, or a callback URL/query containing both); the terminal also retains bare-code support. Tokens are saved atomically only to the backend's own 0600 file, not to Claude Code or Pi. The new credential directory is 0700. Run the command in the same XDG environment as the installed backend. Uninstall preserves this credential file; use Widget login's Sign out to remove it if no longer needed.
Automatic refresh writes credentials. Before using an expired token, or one within five minutes of its stored expiry, the backend attempts a refresh and saves both the new access token and rotated refresh token back to that source's store. Pi already stores a five-minute safety deadline; that convention is retained on write-back. Valid tokens outside the refresh margin cause no writes. Each source is re-read under its lock immediately before refreshing, so an owning app's completed refresh is reused. Other JSON entries/fields are preserved. Writes use a same-directory temporary file, file/directory fsync, atomic replacement, mode 0600 and the existing ownership. Symlinked credential files are rejected rather than replaced.
Backend requests sharing a store serialise refreshes, including across widget configurations. Pi's verified proper-lockfile protocol is respected through auth.json.lock directories with mtime heartbeats. Claude Code's own lock could not be verified; its widget-side lock excludes widget writers only. A final content/revision check detects intervening changes and prefers a valid newer on-disk token instead of overwriting it. No ordinary file replacement can eliminate the final check/replace race against an app that does not share the lock. Existing locks are never stolen; an abandoned widget .quota-refresh.lock directory may need removing only after stopping all processes using that store. Do not remove a live Pi lock.
Rotation risk: refresh tokens are treated as rotating, but Anthropic's actual rotation/reuse behaviour is unverified. Concurrent Claude Code/Pi logins or refreshes, crashes, and failed persistence can invalidate a shared session or lose a rotated token. A separate own login reduces file-sharing races, but does not guarantee server-side session independence. If necessary, sign in again using the remedy for that source. If every enabled source fails, last-good values stay visible with a stale warning and source-specific remedies. Disabling every source queries no Claude credentials; changing the source selection clears that widget's previous account data. There are no desktop notifications.
Weekly - Fable window. When the usage API's limits array reports a weekly_scoped limit scoped to a Fable model, the backend shows it as an extra Weekly - Fable limit: a seven-day window that shares the weekly reset. Its percent is a share of the Fable allowance itself, so it is displayed as reported (clamped to 0-100), never rescaled. It is toggleable in Settings like the other windows and is enabled automatically on the first successful pull that reports a usable value; a manual toggle is never overridden later. Plans without a Fable allowance simply omit it, so absence is normal: it never marks the document partial and never raises an error.
OpenCode Go
Set up OpenCode Go inside the widget. Open Settings, find the OpenCode Go card and fill in two fields:
- Workspace ID: the workspace segment of your OpenCode Go dashboard URL (
https://opencode.ai/workspace/<workspace ID>/go). - Cookie: the value of the
authcookie foropencode.ai. In your browser's developer tools, open the cookies foropencode.aiand copy theauthvalue. A bare value,auth=<value>and a fullCookie:header containingauth=are all accepted; only theauthvalue is stored.
Select Save. The status line reads Saved in the widget and the next refresh uses the new details. Remove deletes only the widget's copy and falls back to Pi's auth.json; it does not change Pi's file. The values are stored in the backend's private 0600 file ${XDG_CONFIG_HOME:-~/.config}/quota-widget/opencode-go.json (in a new 0700 directory). The backend never returns or logs the workspace ID or cookie. The cookie expires eventually; paste a new one and save again.
Pi fallback (read-only). When the widget file is absent, the backend reads ~/.pi/agent/auth.json:
{
"quota-status": {
"opencode-go": {
"workspaceId": "your workspace ID",
"authCookie": "your auth cookie"
}
}
}
The widget never writes this file. Keep it private. The backend requests the workspace's Go dashboard and normalises its rolling/weekly/monthly limits.
Mistral
Mistral has no usable usage API for standard API keys, so the monthly window is computed locally (ported from pid's quota bridge): the backend streams Pi session logs and sums this UTC month's Mistral costs, then reports the remaining percentage against a USD budget. No HTTP request is made and the API key itself is never read or sent; only the presence of a mistral (or mistral-...) api_key entry in ~/.pi/agent/auth.json is checked. A custom Pi provider name in Settings replaces mistral for both the auth check and the session-log match (<name> or <name>-...). Both names are sent to the backend as the optional piProvider query parameter.
- Budget:
PID_MISTRAL_MONTHLY_BUDGET_USDinquota-backend.service's environment (a systemd user drop-in such as~/.config/systemd/user/quota-backend.service.d/budget.confwithEnvironment=PID_MISTRAL_MONTHLY_BUDGET_USD=143), followed bysystemctl --user daemon-reloadandsystemctl --user restart quota-backend.service. The default is 143 USD (a 127.5 EUR plan expressed in USD);0hides the window. - Sessions:
PI_CODING_AGENT_SESSION_DIR, elsePI_CODING_AGENT_DIR/sessions, else~/.pi/agent/sessions. Only.jsonlfiles touched since the month started are read, bounded by the same scan limits as pid (2000 files, 256 MB of new bytes per refresh, depth 4). Scans are incremental and append-aware: each file resumes at the end of its last complete line, per-UTC-date cost buckets are reused when the window moves, and the byte budget limits new bytes per refresh, so a large session tree converges over a few refreshes and then costs almost nothing. A truncated scan is marked partial, never silently wrong. - The window resets at the next UTC month boundary, shows whole-number percentages and the spend in a detail card, tracks monthly pace (spend versus elapsed month), and names "Pi session logs" as its quota source.
- The monthly quota also carries
dailySpend: one entry per UTC day of the current month up to today, in the window's currency, for the widget's daily-spend strip. It isnullwhen the source cannot date its spend, such as console rows without a usable timestamp. - Console mode (optional, real spend): in Settings, under Mistral console cookie (optional), paste the
Cookierequest header of anyadmin.mistral.airequest from your browser's DevTools (Network tab, reload, first request, Headers), or Firefox's Cookies tab "Copy All" JSON. It must contain anory_session_*cookie. The backend then readshttps://admin.mistral.ai/api/billing/v2/usagefor the current UTC month, sumsvalue_paid x priceacross the Vibe Code usage entries (the response'svibe_codesection: tokens, audio seconds and every other category it bills) and reports that real spend in the console's currency. Studio API key usage, reported in the other sections of the same response, is deliberately excluded. The cookie is stored only in the backend's private0600credential file, never in widget configuration, never logged and never sent anywhere exceptadmin.mistral.ai. It can expire; an expired session is reported as a sign-in problem, and Remove (orPID_MISTRAL_MONTHLY_BUDGET_EUR=0) falls back to the local estimate. Budget:PID_MISTRAL_MONTHLY_BUDGET_EUR(default 127.5 EUR); the local estimate keepsPID_MISTRAL_MONTHLY_BUDGET_USD(default 143 USD). Console mode also reports the plan's separate included API allowance as anapiwindow: the Studio API usage in the response's other sections againstPID_MISTRAL_API_BUDGET_EUR(default 12.75 EUR;0hides it). Local-estimate mode cannot see this usage, so the window is omitted there. - The tab icon is Mistral's official mark, taken from
mistral.ai/favicon.svg(see Credits). - Without a console cookie, the spend is an estimate of Pi session usage, not a mirror of Mistral's bill. Pi computes each entry's cost locally from token counts (
totalFromProvider: false) using Mistral's published per-token prices, and the widget sums those. Mistral's console shows account-wide actual billing in EUR, which also includes usage that never enters Pi session logs - notably pid's Mistral dictation (Voxtral records no costs), and any other tool or device using the same API key. Expect the console to read higher than the widget.
Why no plan type or live limits from an API: Mistral's usage, spend-limit and rate-limit endpoints are Admin API routes available only on Enterprise plans, and a standard API key is explicitly refused there. The SDK's whoami model (which would expose org_tier) is not deployed: GET /v1/whoami returns 404. The only standard-key signals are undocumented rate-limit headers on inference responses, which this backend never makes. So the plan label stays a local "Pay as you go" (a working API key already proves billing activation), and spend is computed locally.
Refresh behaviour across multiple displays
Every widget uses the same quota-backend.service; it does not launch a backend per display. The registry shares concurrent reads separately for each provider (and each ordered Claude source selection), caches successful results for 60 seconds and failures for 15 seconds, and limits forced/manual refreshes to at least ten seconds apart per cache key. Another display's request during those intervals uses the shared result.
Widgets request enabled providers on load, every 15 minutes, when opening after a minute without an attempt, and on manual refresh. After a reset expires they recheck once per minute until fresh window data arrives, using the shared normal cache so displays do not independently force requests. The UI bounds and aborts stalled HTTP requests, clears busy controls and retains its last-good values. Shared-cache waiters also have a deadline.
Last-success and last-attempt times are separate. A failed request does not make data fresh. Stale values are explicitly marked in provider pages and the panel tooltip; they must not be interpreted as a current allowance. Last-good data is held in memory, not persisted to disk.
Updates: automatic check, manual installation
The source is fixed to:
https://git.tsbprodesk.co.uk/localuser/quota.git
The updater resolves the remote default branch (currently main) and compares complete commit IDs, not numeric release versions. Once per backend launch, including login, it requests one check only. Multiple widgets do not trigger extra startup Git checks. An already-active operation is coalesced. There is no periodic update timer and no automatic installation.
The Updates section in Settings shows installed/latest commit/date, last check, progress and failures. Details reveals the source and full commit IDs. Check only fetches/checks. Install opens confirmation of the exact checked commit. If the candidate changes, installation stops and requires a new review/confirmation. Loaded QML may require reloading after an update; the shared backend is restarted automatically and health-checked. After an install, Restart Plasma Shell restarts plasma-plasmashell.service (POST /v1/plasma/restart) to load the new widget.
CLI equivalents:
quota-widget-update --check # also the default with no arguments
quota-widget-update --apply --expect-commit <full-checked-SHA>
--apply without --expect-commit uses the last successfully checked candidate, but still explicitly requests installation and validates it against the remote. No previous successful check means no apply. Do not use systemctl start quota-widget-update.service as the manual interface: service workers consume correlated requests reserved by the backend/CLI.
The managed Git object store is under ~/.local/share/quota-widget-updater/repository.git. State is saved atomically with mode 0600 under ~/.local/state/quota-widget/updater.json; custom XDG homes are honoured. Known installed commits must be ancestors of the candidate. Ancestry beyond the bounded 256-commit fetch, rewritten history, invalid candidates and offline fetches stop safely without changing the installation.
Git over HTTPS and fast-forward enforcement are not publisher-signature verification. The retired Apache archive/checksum channel is no longer used. build-release.sh remains a legacy packaging utility, not an updater or supported Git-free installation path.
Backend API
All widget instances use http://127.0.0.1:17934:
GET /v1/quota?provider=codex|claude|opencode-go|mistral: shared normalised document.refresh=1requests a guarded manual refresh.codexSources=codex-cli,pi,ownfor Codex orclaudeSources=claude-code,pi,ownfor Claude supplies the enabled sources in priority order. Omit the parameter for defaults; an explicitcodexSources=orclaudeSources=disables all sources for that provider. Only the relevant three identifiers, without duplicates, are accepted. Invalid selections, repeated parameters or use with another provider return HTTP 400. No credential paths or token values are accepted through this API.GET /v1/codex/auth/status: read-only local source status, pluslogin: {status,message,...}. CLI status includesexecutableFoundandhasCredentials, without reading CLI secrets or spawning it. Pi/own status uses the same expiry states as Claude. While device login is pending,loginincludes only the publicuserCode, fixedverificationUrland initialexpiresIn(900 seconds). Terminal states areidle,success,error,expiredorcancelled.POST /v1/codex/auth/startwith{}: starts/replaces the in-memory device flow and background polling. Returnsok,status,userCode,verificationUrl,expiresIn,message, neverdevice_auth_id, token values, authorisation code or verifier. Device sign-in unavailable/exchange errors return safe errors, not upstream bodies.POST /v1/codex/auth/cancelor/v1/codex/auth/signoutwith{}: cancels the flow; sign-out also deletes only Codex own credentials. A cancelled/replaced worker cannot save a later token response.GET /v1/claude/auth/status:{"ok":true,"sources":{...}}, keyed byclaude-code,pi,own. Each source hasstatus(signed_in,expires_soon_will_refresh,expired_will_refresh,not_signed_inorerror),hint,planType(recognised subscription type ornull),expiresAt(stored Unix seconds ornull) andhasCredentials(file present). Read-only, no network calls and no credential values.POST /v1/claude/auth/startwith{}: creates a ten-minute in-memory PKCE login, replacing any previous one. Returns onlyokandauthoriseUrl, never the verifier.POST /v1/claude/auth/completewith{"code":"<code#state>"}: validates state, consumes the pending login and exchanges/saves tokens. Returns only a safe success/error message. Invalid codes return 400, absent/expired logins or concurrent mutations 409, and token exchange failures 502. Login/sign-out invalidate every Claude source-selection cache, including last-good data and manual-refresh guards.POST /v1/claude/auth/cancelwith{}: clears the pending login; saved credentials are unchanged.POST /v1/claude/auth/signoutwith{}: deletes only the own-source credential file; no remote revocation.GET /v1/mistral/console/status:{"ok":true,"configured":bool}- whether a console cookie is stored. The cookie value is never returned.POST /v1/mistral/console/savewith{"cookie":"<Cookie header>"}: validates that the header contains anory_session_*cookie (theCookie:prefix and Firefox's "Copy All" cookie JSON are tolerated), stores it in the backend's private0600credential file and invalidates the Mistral cache. Bodies are capped at 8 KiB.POST /v1/mistral/console/signoutwith{}: deletes the stored cookie and falls back to the local estimate.GET /v1/opencode/auth/status:{"ok":true,"configured":bool,"source":"widget"|"pi"|null}- where the OpenCode Go details come from, without returning either value.POST /v1/opencode/auth/savewith{"workspaceId":"<id>","authCookie":"<auth cookie value>"}: validates and stores both in the backend's private0600credential file and invalidates the OpenCode Go cache. Returns200 {"ok":true,"message"}; invalid input returns 400 with codeinvalid_workspaceorinvalid_cookie.POST /v1/opencode/auth/signoutwith{}: deletes only the widget's OpenCode Go file, so a Piauth.jsonentry is used instead if present.GET /v1/health: service/API identity, running PID and version captured when the backend started. This does not query providers.GET /v1/update/status: persistent operation status and installed/checked revision identities.POST /v1/update/check: check only.POST /v1/update/applywith JSON{"expectedCommit":"<full SHA>"}: explicitly apply a confirmed checked revision.
POSTs require the existing X-Quota-Widget: 1 marker. The Codex and Claude auth POSTs additionally require Content-Type: application/json, a JSON object (including for start/cancel/sign-out), no transfer encoding and at most 4096 body bytes. The OpenCode Go POSTs follow the same JSON rules with an 8704-byte body cap. Completion is single-flight and single-use. Update bodies retain their 1024-byte limit. All responses use Cache-Control: no-store, and the backend does not log HTTP requests or token-exchange bodies. The legacy POST /v1/update is check-only, regardless of supplied action. Status includes a correlated operation ID; it is not inferred from an old systemd exit result. During transactional activation the endpoint reports pending rather than an uncommitted success.
Claude success documents also carry dailySpend: {kind: "apiEquivalent", currency: "USD", startsAt, days, allTimeUsd, source: "pi-sessions", truncated}, with 30 two-decimal USD entries for the last 30 UTC days (oldest first, today last) summed from Anthropic-family Pi session costs, or null when the session logs are unavailable. Codex documents carry the same shape plus sources (pi-sessions and/or codex-sessions, joined with + in source), or null when neither log source exists. allTimeUsd is the two-decimal total over every readable log, not just the 30-day window. Mistral's Pi-log monthly quota carries allTimeAmount the same way (absent in console mode).
GET /v1/stats returns Pi usage statistics: {ok, currency, generatedAt, windows: ["7d","30d","all"], firstDay, providers: [{id, label, sources, cost: {7d,30d,all}, tokens: {7d|30d|all: {input, output, cacheRead, cacheWrite, total}}}], totals: {cost, tokens}, sources, truncated, filesTruncated}. Rows are raw Pi provider names, sorted by all-time cost; local Codex CLI and VS Code rollouts are merged into the openai-codex row (tokens: uncached input, cached input as cache read, output). Optional ?mergeProviders=1 (default 0, per-widget setting statsMergeProviders) groups exact names and hyphen-suffixed variants using openai → openai (including openai-codex and openai-codex-2), anthropic/claude → anthropic, and mistral → mistral; other names remain separate. Daily buckets are summed before cost rounding, including every token breakdown and de-duplicated source names. Grand totals, per-account quota data and daily spend cards are unchanged. It returns an error document when neither Pi sessions nor Codex rollouts exist.
Spend and statistics share one usage ledger: a single append-aware pass over every Pi session file and Codex rollout, bucketed per UTC day, provider and model. Its per-file progress is saved atomically to ${XDG_CACHE_HOME:-~/.cache}/quota-widget/usage-ledger-v1.json (mode 0600, paths and aggregates only, no message content), so a backend restart resumes from the cache instead of rereading every log. Rollout costs are recomputed from cached token counts, so price-table changes apply retroactively. Deleting the file only forces one full rescan. Session files that are deleted drop out of the totals.
Extra Codex accounts add account=codex-N to GET /v1/quota?provider=codex and GET /v1/codex/auth/status, and {"account":"codex-N"} to the Codex auth POST bodies. The account selects its own widget-login file and cache slot; its status reports another account's pending sign-in as idle. Invalid ids, or account with another provider, return HTTP 400.
Codex and Claude success documents also include credentialSource (codex-cli/claude-code, pi or own), retained on stale results. The ordered source subset keys the shared result cache, manual-refresh guard and last-good snapshot, so different widget configurations never borrow each other's results. Refresh/write-back locks are shared across those configurations. The CLI equivalents are quota-backend --provider claude --claude-sources pi,own and quota-backend --provider codex --codex-sources pi,own.
Quota documents include ok, stale, updatedAt, lastSuccessAt, lastAttemptAt, account, quotas and safe error: {code,message} or null. A retained success after failure has ok:true, stale:true with the old success timestamp. Without any success, failures use ok:false, updatedAt:null. Missing windows use available:false, not invented zeros. Codex retains a singular weekly quota compatibility alias and optional sanitised {hasCredits,unlimited,balance} credits. Valid partial five-hour/weekly/credit data is kept independently. Provider credentials, dashboard HTML and raw app-server output are never returned.
Every window also carries windowDurationMins (length in minutes, null when unavailable or unknown): Codex reports it from the usage API, Claude session 300 and weekly 10080, OpenCode Go rolling 300 and weekly 10080 with monthly null. OpenCode Go's sliding five-hour window sets rolling: true; fixed windows omit the field.
Deferred security hardening
The widget-to-backend connection is local. OpenAI, Claude, OpenCode and Mistral console requests are remote, however: they target OpenAI's OAuth/device and ChatGPT usage APIs, Claude's OAuth token/usage APIs, OpenCode's dashboard and Mistral's console billing API (only when a console cookie is saved); browser sign-in opens the relevant provider's page. At the user's request, cross-origin credential-redirect restrictions and loopback Host/Origin validation were not changed in this round. The loopback backend has no real authentication. The POST marker is not a secret or authentication. For login endpoints, requiring this marker plus application/json rejects simple cross-origin form posts; no CORS permission or preflight handler is provided. State validation, an independent private PKCE verifier, a ten-minute expiry, single-use completion and single-flight mutation reduce abuse, but do not authenticate the caller. A local process can call these endpoints, inspect Codex's public pending user code, replace/cancel a pending login, complete one it initiated or delete the widget's credentials. Device polling is limited to 15 minutes, private device identifiers stay in memory, and cancelled/replaced workers cannot persist late token responses; these are not caller authentication. A cross-origin page able to bypass browser CORS restrictions or exploit the deferred Host/Origin/DNS-rebinding protections could also trigger them. Do not rely on CORS to protect against a compromised local application/browser; keep the backend bound to loopback and never expose it publicly. See AUDIT.md for the qualified findings, not evidence of an observed real credential leak.
Troubleshooting
systemctl --user status quota-backend.service
journalctl --user -u quota-backend.service
journalctl --user -u quota-widget-check.service -u quota-widget-update.service
After source changes, rerun ./install.sh; a running widget/backend does not execute your development files directly. Commit and push changes before expecting another installation's Git updater to fetch them.
An installation failure at QML validation occurs before replacing the deployed applet/backend or changing services. Do not uninstall the previous widget to fix it. The error includes the selected tool, exit status and its actual diagnostic, or identifies a timeout/execution failure. qmlformat checks formatting round-trips as well as parsing, so a non-zero exit is not by itself proof of a source syntax error. If reporting a failure, include the full installer diagnostic and the output of <reported-tool-path> --version; do not bypass validation with --force.
Codex requests have 20-second deadlines per protocol call. Error text names the failing call, while process exits are separate. The reader drains buffered notifications/replies and handles fragmented lines without extending those deadlines. If trouble persists, report codex --version and safe widget error text, not credential files or raw protocol output.
Installation rollback handles reported failures and cancellation, not power-loss recovery. If rollback reports retained backups, preserve those paths and follow its recovery message. A failed restored-backend restart needs manual investigation.
Development and verification
make test # synthetic Python, Git, install and HTTP tests
make check # compilation, QML/XML/JSON and shell syntax
make test-ui # optional: PySide6, offscreen QtQuick integration
make check needs Qt 6 qmllint and xmllint in addition to the installer requirements. Override QMLLINT/XMLLINT if your distribution uses versioned executables. make test-ui requires PySide6 in the selected Python environment; it substitutes explicit KDE stand-ins, captures screenshots and tests multiple widgets against a synthetic local backend. It does not establish native Plasma styling, screen-reader behaviour or live deployment correctness. Set QUOTA_UI_ARTIFACTS to retain screenshots at a chosen path.
The install tests use any discoverable compatible Qt formatter to validate all shipped QML, reject malformed syntax without changing source files, and exercise migration from a synthetic 0.5.2 installation. To test a particular Qt tool explicitly, run QUOTA_TEST_QMLFORMAT=/path/to/qt6/qmlformat make test. Without a compatible formatter these two real-tool tests are skipped; tool discovery, diagnostic and preservation tests still run. Migration tests use temporary homes and mocked services, not a running Plasma session.
Remaining test/reliability work includes actual Plasma/KPackage configuration retention and deployment testing, screen readers and multi-monitor scaling, automated CI, provider-wide total response deadlines and Codex buffer/resource bounds. Provider HTTP socket timeouts alone are not total operation deadlines. OpenCode hydration fields and Claude's undocumented OAuth API can change.
Uninstall
From this Git checkout:
./uninstall.sh
This stops and disables the backend and update services, then removes their service files, the quota-backend, quota-widget-update, quota-claude-login and quota-codex-login wrappers, the icons, the installed applet, backend and updater files, and the updater state. It prints:
Uninstalled AI Quota. Kept: widget configuration and saved sign-ins. Remove the widget from your panel if it is still there.
Plasma widget configuration and every saved sign-in (~/.config/quota-widget/, Pi's auth.json, Codex CLI and Claude Code credentials) are kept, so a reinstall does not need signing in again. The fixed backend port remains 17934; custom port configuration is not yet exposed.
Credits
OpenCode Go dashboard request and hydration-field discovery were informed by @mjfuertesf/pi-quota-status. The widget uses its own Python adapter and normalised multi-window response.
The Mistral tab icon is Mistral AI's official logo mark (geometry and colours from mistral.ai/favicon.svg). It is a trademark of Mistral AI, used here for identification of the provider only.


