Skip to content

feat(providers): surface usage limits and paid usage notices - #697

Merged
nixuuu merged 1 commit into
devfrom
feat/provider-usage-warnings
Nov 14, 2026
Merged

nixuuu merged 1 commit into
devfrom
feat/provider-usage-warnings

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

Canopy previously showed no provider plan limits. This adds durable account snapshots from official harnesses, compact provider settings meters, composer warnings at 90%, reached-limit notices, and limit-specific failure headings on web and mobile.

  • Codex 0.164.0: read limits at app-server startup/account read and forward account notifications. Preserve the reported 5-hour/weekly percentages and resets; discard credit balances.
  • Claude Agent SDK 0.3.316: merge rate-limit events, recognize official warning/error/transition prefixes, and optionally read usage from an existing active session at most once per 15 minutes. Paid-turn notices stay visible outside collapsed activity, including after success.
  • Store sanitized snapshots per worker/provider/profile and runtime/home identity. Reject obsolete reports and enforce worker/instance ownership. Deliver changed workers through the existing incremental overview stream. Bot and text-generation harness events update the same source account.
  • Add migration 0141 and additive protobuf fields with generated contracts. Keep expired-login handling separate.

Billing boundaries

Codex reports credit availability, not whether this turn uses credits. An exhausted plan with available credits therefore says “Plan limit reached. Further turns may use credits.” Claude's explicit extra-usage signal shows the account state and preserves “This turn uses extra usage credits.” in the thread.

Neither pinned harness exposes a supported per-turn switch that prevents paid fallback. There is no fake stop setting, direct provider API call, reset-credit action, or inferred billing from token/cost data. Grok ACP exposes no account plan windows, so nothing is shown. A harness may report a transition after work starts; Canopy cannot promise pre-charge prevention.

Validation

  • Install, generation consistency, whole-repo typecheck, lint, formatting, and web production build passed.
  • Focused checks passed: 57 tests covering official fake Codex/Claude harnesses over WorkerHost/gRPC/Postgres, startup and account refresh after notifications, changed runtime identity, incremental delivery, restart/offline persistence, owner scoping, stale reports, error mapping, bot collection, adapter shutdown, and schema checks. The final turn/adapter rerun passed 9 tests.
  • Full check:tmp completed with 2,978 passed, 175 skipped, and one SQL diagnostics failure. The usage query now uses the existing workers.store diagnostics family; its rerun passed. CI also caught loss of Codex's original error code without a reported plan window; that code is now preserved. All 41 bot/usage/diagnostics regression tests passed after both fixes. The full suite was not repeated locally.
  • iOS and Android exports passed. Native fingerprints exactly match dev: iOS 138e0c6b171c82b4933e86808cdfef56da73b8c6, Android 906dc944f94eb8333fa384ed9f198834fdd30d13.
  • Manual browser review used real isolated gateway/worker fixtures: light/dark, desktop/390 px phone, settings meters, 92% composer warning, reached-limit heading, and visible paid-turn notice with activity collapsed. Short, typical, and long labels stayed within the viewport. Review services/container and temporary checkout were removed. Native simulator visuals remain unverified: device discovery twice failed with “Could not communicate with device support.” No live provider tests or charges.

Rebased onto the expired-login change (#696), retaining its sign-in flow and adding meters alongside it. Regenerated contracts preserve both additive changes; migration 0141 remains the next number on dev. On the rebased head, generation consistency, typecheck, lint, formatting, web build, both mobile exports, and all 45 usage/bot/diagnostics/expired-login tests passed. New CI checks are running; no review has been submitted.

Copy audit (§8)

Before After Reason
No usage text “5-hour · 25% used”, “Weekly · 92% used”, localized reset times Name the reported window and keep meters compact.
No near-limit action “Weekly limit 92% used · resets …” + “Check usage in provider settings” State the condition and provide an action without blocking the composer.
Generic failure heading “Weekly limit reached · resets …” Preserve the window/reset from the failed turn; retain existing actions and technical details disclosure.
No billing notice “Extra usage credits are active.” for account state; “This turn uses extra usage credits.” for durable turn history Distinguish current account state from the specific turn, using explicit harness signals.
No Codex credit warning “Plan limit reached. Further turns may use credits.” Credit availability alone cannot establish that a charge occurred.

New copy uses short active sentences, sentence case, glossary terms, localized numbers/dates, visible text alongside meter colours, and live status announcements. No new empty states, destructive actions, jargon, blame, or humour. Long-name and phone-width review passed; unavailable data stays hidden.

@nixuuu
nixuuu force-pushed the feat/provider-usage-warnings branch 2 times, most recently from ad768c4 to 926cace Compare November 14, 2026 09:32
@nixuuu
nixuuu force-pushed the feat/provider-usage-warnings branch from 926cace to a05d066 Compare November 14, 2026 09:48
@nixuuu
nixuuu marked this pull request as ready for review November 14, 2026 09:49
@nixuuu
nixuuu merged commit 04617ce into dev Nov 14, 2026
11 checks passed
@nixuuu
nixuuu deleted the feat/provider-usage-warnings branch November 14, 2026 10:02
nixuuu added a commit that referenced this pull request Nov 14, 2026
Claude device logins stored in macOS Keychain appeared as **Not signed
in** because Canopy changed `CLAUDE_CONFIG_DIR` to its shadow home.
Claude scopes its keychain service by that directory; linking
`.credentials.json` cannot share a login that has no file. The existing
JSON parser already accepts the reported 2.1.325 response.

Select the login separately with Claude's
`CLAUDE_SECURESTORAGE_CONFIG_DIR` for both account probes and instance
turns. Preserve the empty value for the default, unhashed keychain
service, and preserve explicit config directories for scoped logins.
Sessions, settings, hooks and plugins remain in the isolated home.
Own-login instances and workers with device login disabled keep their
isolated credential store. Reserve this environment variable against
profile overrides; no tokens are read or exported by Canopy.

### Evidence

- Inspected #696 and #697: empty `login_revision` does not create a
signed-out state; rejected-login marks produce `expired`, and usage
reports stay separate. This predates those changes. Desktop already
preserves `HOME`, `USER` and `LOGNAME`.
- Fake CLI through real WorkerHost, gRPC and PostgreSQL covers the
reported keychain-backed JSON without a credentials file, a file-backed
login, signed out with exit code 1, and the older JSON shape without the
new optional fields. It also completes a real SDK turn while asserting
that shadow home and default keychain scope remain separate, and rejects
fallback from an empty own-login instance.
- Account adapter coverage uses the desktop's actual
`serviceEnvironment()` allowlist and the worker's process-governor spawn
path.
- macOS SSH check found Claude 2.1.325 and no credentials file. Both
plain `auth status --json` and the sanitized desktop-like environment
reported `loggedIn:false` in that SSH session, so a live GUI-session
keychain login and real model turn remain unverified. No keychain tokens
were read and no inference was requested.

### Validation

Run with `nice -n 10` and `TMPDIR=/var/tmp`:

- `bun install`, `bun run gen:check`, whole-repo `bun run typecheck`,
`bun run lint`, `bun run format:check`: passed. The integration
typecheck was repeated after the final test edits.
- Focused tests: **28 passed, 0 failed**, across
`provider-account-status`, `provider-accounts.integration`,
`provider-sign-in-expired`, `provider-usage`, `provider-usage-bots`, and
profile environment validation.
- No UI copy changed. No browser/E2E or live inference tests were run.

Related: #125
Related: #696
Related: #697
nixuuu added a commit that referenced this pull request Nov 14, 2026
The sidebar now shows provider plan usage without opening Settings. One
quiet, reserved footer slot contains a mini-bar for each provider with
data, showing its highest active window across enabled instances. Hover
on desktop or tap opens per-instance meters, reset times, billing
notices and **Open provider settings**. The native mobile drawer has the
same glance and details.

- Below 70% is neutral, 70–89% warning, and 90%+ danger. Explicit extra
usage uses a violet split bar; available credits alone never imply paid
activity.
- Reads the existing incremental worker overview. No additional requests
or polling. Shared client clocks expire old windows and refresh reset
labels, stopping when hidden.
- Proxy instances are excluded. `ProxyUsageSection` exposes the small
typed shape for a later upstream-account section without fetching or
rendering proxy status.
- Existing settings, worker and update controls retain their positions
when usage disappears. Overlays reuse compact kit typography,
truncated-name hints and existing motion with reduced-motion support.

Related: #697

### Validation

- `bun install`, `bun run gen:check`, whole-repo typecheck, lint,
formatting and the web production build passed. Final overlay primitive
changes were checked again with typecheck, lint, formatting and web
build.
- Focused tests: **9 passed**, covering the new aggregation/projection
and existing provider usage/bot WorkerLink integration. Includes
threshold boundaries, worst active window across computers, expired
windows, explicit extra usage, credit availability, missing data and
proxy exclusion. No UI test suite was added or run.
- iOS and Android exports passed with one Metro worker. Native
fingerprints are unchanged: iOS
`138e0c6b171c82b4933e86808cdfef56da73b8c6`, Android
`906dc944f94eb8333fa384ed9f198834fdd30d13`. Tracked fingerprint source
inputs have no differences from dev. No native dependency or
configuration changes; eligible for the normal OTA release pipeline, no
update published manually.
- Manual browser review used a private remote gateway/BFF/database with
synthetic usage and long instance/computer names: light and dark, 1280
px desktop, 760 px narrow drawer and 390 px phone sheet. Verified
hover/tap, reset labels, neutral/warning/danger meters, distinct
extra-usage glance, Settings navigation and no horizontal overflow.
Removing all usage hid the trigger while settings/workers/updates
retained identical measured positions. Review services, database
container, tunnel and temporary checkout were removed afterwards.
- Native mobile visuals remain unverified: no running simulator was
available; device discovery reported a device-hub timeout. Exports and
native fingerprints passed. No live provider calls or charges.

### Copy audit (§8)

| Before | After | Reason |
| --- | --- | --- |
| No sidebar usage text | “Show provider usage” and accessible provider
percentages or “extra usage active” | Name the action and convey meaning
without relying only on colour. |
| Settings required for details | “Provider usage”, instance and
computer labels, existing “5-hour”, “Weekly”, “Resets in …” | Keep the
overlay compact and reuse established, localized meter copy. |
| No sidebar details action | “Open provider settings” | Verb-first
action points directly to Providers. |
| No sidebar billing notice | Existing “Extra usage credits are active.”
/ “Plan limit reached. Further turns may use credits.” | Preserve the
distinction between confirmed extra usage and available credits. |

New copy uses sentence case, short labels, glossary terms, localized
numbers and reset times. No new jargon, errors, empty states,
destructive actions or humour. Full labels remain available through
truncated-text hints; short, typical and long names were reviewed at
desktop and phone widths. Status meaning is present in text and
accessible labels as well as bar colour/shape.
nixuuu added a commit that referenced this pull request Nov 14, 2026
Harness rate limits through a proxy, an API key or a custom endpoint belong to
whatever upstream account the endpoint picked, so they never describe the
user's plan. The worker no longer reports them or puts a plan window into the
failure code, the gateway drops and hides such reports from older workers,
and migration 0143 clears stored snapshots. The limit failure card stays,
worded as a proxy limit.

Fixes: #697
nixuuu added a commit that referenced this pull request Nov 14, 2026
Harness rate limits through a proxy, an API key or a custom endpoint
describe whichever upstream account the endpoint picked, not the user's
plan. Before this change, Settings → Providers showed a "Weekly · 1%
used" meter on one worker of a CLIProxyAPI-backed Codex instance.

- Worker: `reportsPlanUsage` turns off usage reports and failure-code
enrichment for `cliproxyapi` instances and for instances whose env has
an API key or base URL (`ANTHROPIC_*`, `OPENAI_*`, `CODEX_*`,
`CLIPROXY_API_KEY`).
- Gateway: `ProviderUsage.report/read` accept and return only native
instances without a proxy (instance or worker override), so older
workers can't bring the meters back.
- Migration `0143_provider_usage_endpoints` deletes stored snapshots of
such instances.
- Failure card: kept for real limit failures. Through a proxy it no
longer names a plan window, and the explanation reads "The proxy
reported a usage limit…". Mobile `TurnEnd` now gets `proxy`, matching
web.
- Docs: `docs/provider-accounts.md`.

Fixes: #697

## Tests
- `tests/integration/provider-usage.test.ts`: a proxy instance never
exposes or stores plan windows. Its limit failure names no plan window,
and an older-worker report is dropped. I checked that this test fails
without the worker change.
- Also run: `packages/db/test/schema.test.ts`,
`provider-usage-bots.test.ts`, `proxies.test.ts`, gen:check, typecheck,
lint, format:check, web build, mobile export (android, ios).

## Copy audit (§8)
| Before | After | Reason |
| --- | --- | --- |
| (proxy) "Weekly limit reached · resets …" | "Usage limit reached" |
The window belongs to an unknown upstream account |
| (proxy) "A usage or turn limit was reached. Wait for it to reset or
check your plan, then retry." | "The proxy reported a usage limit. Wait
for it to reset or check the proxy's accounts, then retry." | Doesn't
claim the user's plan. Says what happened, then what to do. Two
sentences, each ≤ 13 words. Uses "proxy" from the glossary. |
nixuuu added a commit that referenced this pull request Nov 14, 2026
Saving a management key starts a background accounts read. A concurrent
`RefreshProxyAccounts` could lose the database lease and return an empty
account state in two orderings: while the winner was acquiring its
lease, or after a stale target lookup outlived the completed winner.
Register the shared promise before claiming the lease and reload the
committed snapshot after a refused claim. Keep cached and forced refresh
decisions unchanged.

The original proxy test and its assertions are unchanged. Add a
regression with explicit target/lease gates that holds a stale lookup
until the winning refresh has committed. Restoring the stale-snapshot
fallback makes this regression fail deterministically with an empty
account state; restoring the fix makes it pass.

For the Claude usage test, coordinate the fake CLI and WatchThread
explicitly: the CLI announces turn admission, then waits for the watch's
initial snapshot before emitting the existing limit events and result.
The existing 10-second watch budget and 60-second test budget are
unchanged, as are all five assertions. Include the caller's proxy
credential variable in fixture environment isolation so native plan
reporting remains enabled in developer/agent shells.

### Repeated focused runs

All runs used `nice -n 10`, with temporary files under a private
directory in `/var/tmp`. Each 200-run sample consists of four batches of
50 using `--rerun-each=50` and the exact test-name filter.

| Test | Before | After |
| --- | --- | --- |
| Encrypted management key / proxy accounts | 152 passed, 48 failed /
200 | 200 passed, 0 failed / 200 |
| Claude reached window / paid-usage notice | 200 passed, 0 failed / 200
| 200 passed, 0 failed / 200 |

The proxy baseline failures returned `state: ""`, `total: 0` rather than
the sanitized account snapshot, matching the fast CI failure. The Claude
cancellation in Release run 43622538704 was not reproduced locally; ten
additional runs with the preceding gateway-restart test also passed. Its
change removes scheduling of CLI startup and stream subscription from
the timed event-observation phase; it does not claim a provider product
fix.

Standalone Docker-per-iteration baselines also encountered 12 proxy and
4 Claude teardown-hook timeouts, separate from the test-body counts
above. Final repeated runs and focused files use the repository's
`check:tmp` runner, which shares PostgreSQL across iterations and checks
cleanup.

### Validation

- `nice -n 10 bun install`
- `nice -n 10 bun run typecheck`
- `nice -n 10 bun run lint`
- `nice -n 10 bun run format:check`
- `nice -n 10 bun run check:tmp tests/integration/proxy-accounts.test.ts
tests/integration/provider-usage.test.ts
tests/integration/provider-usage-bots.test.ts` — 16 passed, 0 failed; no
temp directories left

Fixes: #727
Related: #697
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant