Repository navigation
feat(quota): add ZCode (z.ai coding plan) live quota provider - #1347
Conversation
The Plans sidebar gains a ZCode panel fed by the same usage endpoint the ZCode app's embedded coding-plan browser calls — the sibling of the zai provider (Pi CLI login), serving the ZCode desktop app's own login: - GET https://api.z.ai/api/monitor/usage/quota/limit with a bearer token - credential: `oauth:zai:access_token` scanned read-only out of the coding-plan webview's Chromium Local Storage journal (*.log), newest journal first, last write of the key wins; ZCODE_DATA_DIR overrides the app-data root - the stored JWT has no exp claim, so a body-level code 401/403 on an HTTP 200 is the expiry signal -> terminalFailure with reopen guidance (only the ZCode app can mint a new login) - windows/labels/percent semantics shared with zai.ts (unit 3x5 -> 5-hour, unit 6x1 -> Weekly; percentage as used, fallback currentValue/usage) Surfaces: desktop Plans page (app/electron/quota + renderer registries) and the CLI quota command (src/quota), per the two-copies convention. Journal compaction into .ldb is a documented blind spot that degrades to disconnected. Verified live against a real ZCode login (plan "Pro", 5-hour + Weekly windows). Menubar Swift mirror left for a follow-up.
0041a6a to
7313925
Compare
|
Also wired ZCode into the native macOS menubar Capacity Dock (6f2eb10), mirroring the zai adapter: Verified: 51/51 across the affected Swift suites, 29/29 on the TS side, live fetch against a real login returns connected/Pro with both windows, and the dock rail renders Codex/Claude/ZCode with the Z glance on a local build. |
6f2eb10 to
54c040f
Compare
Mirrors the zai adapter: a ZcodeSubscriptionService recovers the z.ai OAuth token from the ZCode app's coding-plan Local Storage journal (same scan as the CLI and Electron providers, ZCODE_DATA_DIR override honored) and calls the usage endpoint with it as a bearer token. Registers the catalog entry (live, local-app auth), the quota-service dispatch, a bundled provider-zcode.svg mark, and the pinned-inventory test updates.
54c040f to
2d66f13
Compare
iamtoruk
left a comment
There was a problem hiding this comment.
Not merging yet. Tests pass, rebase is clean, back-off matches zai. Three things first.
- Overlap. This hits the same endpoint as
src/quota/zai.tswith the same decoder, just a different credential. If I am signed into z.ai in the Pi CLI and the ZCode app, do I get two rings on the dock showing the same numbers? Answer that directly. If yes, say what the dedupe is. - Proof. Real screenshots of the dock and the popover with a live ZCode account, dark and light.
- The fixture.
journalEntrywrites marker0x01then latin-1 bytes, but the adapter comment says0x01is UTF-16. So the journal tests do not match real Chromium. Post the recorded response you built the fixtures from, redacted, and a real journal hexdump.
Also: decodeZcodeUsage is a verbatim copy of decodeZaiUsage, three times over counting Swift. Factor it. And inventoryRevision is still the old sha with the count at 70.
…aithful journal fixtures Four items from the getagentseal#1347 review: 1. Overlap answered and handled: ZCode now yields to Z.ai wherever the two could show the same numbers. The CLI's collectQuota drops a connected ZCode row while Z.ai is connected (with a note naming why) and never lets a rejected/stale Z.ai state hide a working ZCode row; the dock's auto-seed skips ZCode while Z.ai is connected, and the popover quota candidates do the same. A manual ZCode pin always wins. The desktop Electron app runs only the ZCode adapter, so it has no overlap to dedupe. 2. decodeZcodeUsage/decodeZaiUsage are no longer verbatim twins: the body decode lives in src/quota/zai-plan.ts and, in Swift, in ZaiPlanQuotaDecoder; both adapters map the shared outcome onto their own error vocabulary. TS wrappers keep the existing exported names. 3. Journal fixtures and comments now match a recorded journal: the map key is origin + NUL + 0x01 one-byte-string flag + key name; the value frame is a varint length (the recorded 1,403-byte login encodes as fb 0a), the same 0x01 flag, then Latin-1 bytes. The earlier comments had the marker semantics backwards. Redacted hexdump and recorded response are posted on the review thread. 4. inventoryRevision bumped; the catalog pin test follows.
|
All four points addressed in 5caa065. 1. Overlap — answered directly: yes, you would have gotten two rings. Both adapters hit
Tests pin all three surfaces ( 2. Screenshots — live ZCode account (Pro), dock card and popover, light and dark, follow this comment. 3. The fixture vs. the recording — you were right that they disagreed, and the recording settles which way. Redacted hexdump of the real So the recorded structure is: map key = origin, The recorded 200 response the decode fixtures mirror (redacted — it carries no account identity at all, only limits and the plan level): {
"code": 200,
"msg": "Operation successful",
"data": {
"limits": [
{
"type": "CREDIT_LIMIT",
"unit": 3,
"number": 5,
"usage": 12000,
"currentValue": 657,
"remaining": 11342,
"percentage": 5,
"nextResetTime": 1789523594808
},
{
"type": "CREDIT_LIMIT",
"unit": 6,
"number": 1,
"usage": 60000,
"currentValue": 27288,
"remaining": 32711,
"percentage": 45,
"nextResetTime": 1789899227973
}
],
"level": "pro"
},
"success": true
}4. Factored. The body decode now exists once per language: |
…t enum The 5-hour and weekly windows are fixed cycles — the unit enum says so — so the adapter vouches for their lengths (windowSeconds from the same metadata the labels come from, never inferred from the label text). This is what the early-reset monitor's windowSeconds contract needs (getagentseal#1339): an adapter that cannot vouch for fixed cycling passes no length and its windows get no opinion. zcode accounts do early-reset for real — one did today on the machine this was tested on.
|
The CI failure on e956fe5 was the zai twin of the legacy-window expectation the durations commit updated — debfd20 brings it in line. Also on that branch: the follow-up promised in the #1339 thread, deriving zcode's window lengths from the payload's unit/count enum so the early-reset monitor's windowSeconds contract covers it the moment both PRs land. |
|
Gentle nudge: all four review points were addressed in 5caa065 back on Sep 15 (dedupe shipped and tested on all three surfaces, screenshots, the redacted journal hexdump, and the CI fix landed in debfd20), and the branch has been rebased clean since. Happy to rework anything that doesn't fit — just pointing at it in case it fell off the queue. |
iamtoruk
left a comment
There was a problem hiding this comment.
Thanks for this. The ZCode provider itself is in good shape: the shared quota decoder (src/quota/zai-plan.ts and ZaiPlanQuotaDecoder.swift) is reused by both Z.ai and ZCode, the reader uses the bounded quotaRequestSignal with graceful disconnected/waiting/error states and never opens a socket when there is no login, numbers stay put (report/models never load the quota path), and the logo is wired on the CLI label, the Plans provider card (embossed via ProviderLogo, zcode.jpg), and the menubar tile (provider-zcode.svg). Root tests, swift test (728), test:locks (36) and tsc all pass.
One blocker after merging current main. Main added app/renderer/lib/menubarProviders.ts, whose MENUBAR_QUOTA_PROVIDERS is the desktop "supported providers" list rendered in MenuBarAbout.tsx and guarded by menubarProviders.test.ts, which re-reads ProviderConnectionCatalog.swift and fails the moment the two disagree. This PR marks zcode live: true in that catalog but does not add ZCode to MENUBAR_QUOTA_PROVIDERS, so:
- the desktop supported-providers list omits ZCode, and
- menubarProviders.test.ts fails (app vitest).
The PR CI is green only because it ran against the pre-guard base; merged into current main it goes red.
Fix is one line: add 'ZCode' to MENUBAR_QUOTA_PROVIDERS right after 'Z.ai' in app/renderer/lib/menubarProviders.ts (matching the catalog's live order), then merge latest main so CI runs against the guard. Once that lands this is good to go.
iamtoruk
left a comment
There was a problem hiding this comment.
Blocker resolved: pushed the one-line fix (85d3342) adding ZCode to MENUBAR_QUOTA_PROVIDERS so the desktop supported-provider list includes it and menubarProviders.test.ts passes. Full CI is green on the new head; root suite, app suite (only pre-existing env failures), swift test (728) and test:locks (36) all pass. Logo present and rendering on every surface, numbers untouched. Good to merge.
…dd UTF-16 frames A record now counts as a write of the login only when its key is ZCode's own origin prefix (`_https://zcode.z.ai`, a NUL, the string flag) followed by the key name, as in the recorded journal from #1347 (tag 01, key length 2b, `_https://zcode.z.ai`, 00 01, `oauth:zai:access_token`); the same key under another origin is ignored. A UTF-16 value with an odd byte count was trimmed by the decoder and could still look like a token; it is now read as unreadable for this poll, with no request and no older token. Not changed: a counterfeit record header embedded inside another entry's value. The journal is ZCode's own local storage on the user's machine, not input from anyone else; whoever can write those bytes already holds the account, and with the origin check a forged record would also have to carry ZCode's exact origin prefix and a matching key length.
…y, expired Gemini login reported once (#1904) * fix(quota): stop at the first keychain Deny instead of prompting again for the same item A refused or unanswered lookup on the user account fell through to the service-only lookup, which matches the same item and raised a second prompt. An unanswered dialog then waited twice, past the quota timeout, and ended as "Timed out." The reader now returns accessDenied at the first refusal; only a genuine miss tries the next account. The CLI row says the access was denied or not answered. * fix(quota): end the ZCode token at its journal frame length The token was read greedily up to the first non-token byte, so when the login ended a write batch the next record's checksum bytes could be appended to it, and every poll sent a corrupted token and reported a false "Login expired". The reader now decodes the value's varint length and slices exactly the string after the encoding flag. * fix(quota): report an expired Gemini login as needing the user Without a refresh client an expired Gemini CLI token was sent as-is and the 401 read as a transient failure on every poll, so the row stayed "Temporarily unavailable" and never said what to do. A 401 on a token whose expiry has passed and that nothing refreshed is now terminal, with a footer to run Gemini CLI once, as Claude already does. * fix(quota): stop only at a keychain Deny or unanswered prompt, and remember it for the run An error that showed no prompt (an I/O failure, interaction not allowed) moves on to the next account again, as before. A Deny or a prompt left open until the timeout ends the lookup, and the CLI keeps that refusal for the rest of the process, so a second read of the same service answers without a prompt. Nothing is persisted, so the next run asks once. The Claude row now says which it was: denied, or not answered. * fix(quota): treat a rejected Gemini login without a refresher as terminal The stored expiry can be missing or skewed, so it no longer decides: with no client credentials or refresh token nothing here can mint a new token, and the 401 needs the user to run Gemini CLI. With a refresher configured the 401 stays transient. * fix(quota): pick the newest ZCode login by journal position across encodings Latin-1 matches were preferred over UTF-16LE ones, so a rotation that changed the string encoding returned the older token. The last write by offset now wins regardless of encoding. * fix(quota): remember a keychain refusal per account and classify only our own timeout as unanswered The run's refusal memo is keyed by service and account, so denying one account no longer hides another account's item. Only the kill from our own timeout counts as an unanswered prompt; any other signal is an ordinary error that moves on. A string exit code is normalised, so "128" is a Deny like 128. * fix(quota): report a ZCode login the app cleared as expired An empty newest write for the key means the app cleared the login. It used to be skipped, so an older token in the same or an older journal was sent instead. It now reads as an expired login without a request. * fix(quota): skip a refused keychain account, time prompts with our own timer, and remember refusals in the desktop app A refusal remembered for one account now skips that account (and the service-only lookup, which can match the same item) and goes on to the next named account, instead of ending the read. An unanswered prompt is now only our own 90 s timer firing: the lookup runs under an AbortSignal whose timer sets a flag, and a kill or signal we did not cause is an ordinary error that moves on. The desktop app keeps the same service-plus-account refusals; a keychain-allowed refresh, which is the user acting again, clears them, so one action asks at most once per item. * fix(quota): treat a malformed newest ZCode write as unreadable, not as the older token Only the newest write of the key is read now. If its frame does not parse (no length, zero length, a length past the end of the file, an unknown flag, or bytes that are not a token) the poll reports a transient failure without a request, instead of falling back to an older token the app already replaced. This cannot be narrowed to in-progress writes: the leveldb log splits a record that crosses a 32 KiB block boundary with a 7-byte header, so a complete write can also fail to parse as one contiguous frame, and a torn tail after a crash looks the same. Both are treated as unreadable for this poll. * fix(quota): count only real leveldb records of the ZCode key as writes The newest write was the last place the key name appeared, so another entry whose value mentions the key (a settings blob, say) was read as a newer, malformed write and the login was reported unreadable. A token value itself cannot hold the key, since ':' is outside the token alphabet. An occurrence now counts only when it ends the key of a leveldb record: tag, varint key length, then `_`, origin, NUL, string flag and the name. A delete record of the key reads as a cleared login. * fix(desktop): say whether the Claude keychain prompt was denied or left unanswered The desktop keychain reader now carries the same refusal reason as the CLI's, and the Claude adapter turns it into the same footer line. The Plans card and the Settings row show that line in place of the generic keychain message for an access-denied row, keeping the generic copy when no reason is known. * fix(quota): read the ZCode key only under its own origin and reject odd UTF-16 frames A record now counts as a write of the login only when its key is ZCode's own origin prefix (`_https://zcode.z.ai`, a NUL, the string flag) followed by the key name, as in the recorded journal from #1347 (tag 01, key length 2b, `_https://zcode.z.ai`, 00 01, `oauth:zai:access_token`); the same key under another origin is ignored. A UTF-16 value with an odd byte count was trimmed by the decoder and could still look like a token; it is now read as unreadable for this poll, with no request and no older token. Not changed: a counterfeit record header embedded inside another entry's value. The journal is ZCode's own local storage on the user's machine, not input from anyone else; whoever can write those bytes already holds the account, and with the origin check a forged record would also have to carry ZCode's exact origin prefix and a matching key length. * fix(quota): skip a later service-only keychain lookup once an account of the service was refused A service-only lookup can match the item the user just refused, so a refusal for any account now also marks the service-only lookup as refused for the run. A later read with only the service-only candidate answers from memory instead of prompting again. Named accounts that were not refused are still read. Not changed: a Deny for one account still ends that read without trying the next account. That is deliberate: the consent policy is stop at Deny, and prompting for the next account right after the user declined is the double prompt this branch exists to remove.




What
Adds live plan quota for ZCode (the z.ai coding plan) to the Plans sidebar — the panel the usage provider from #537 never had. Desktop Plans page + Settings→Plans, plus CLI parity in
codeburn quota.How
GET https://api.z.ai/api/monitor/usage/quota/limit(sibling of thezaiprovider, which serves the Pi CLI login; this one serves the ZCode desktop app's own login).oauth:zai:access_tokenJWT read-only out of the coding-plan webview's Chromium Local Storage journal (…/ZCode/session/Partitions/zcode-coding-plan/Local Storage/leveldb/*.log); newest journal first, last write of the key wins,ZCODE_DATA_DIRoverrides the app-data root. Chromium owns that file's mode bits, so it's a plain capped read rather thanreadSecureFile.code: 401/403on an HTTP 200, which maps toterminalFailurewith "open the ZCode app and sign in again" guidance (only the app can mint a new login).zai.ts(unit 3 × number 5→ 5-hour,unit 6 × number 1→ Weekly;percentageas used, fallbackcurrentValue / usage;data.level→ plan label).Surfaces
app/electron/quota/zcode.ts(origin) + registries:types.ts,index.ts(PROVIDERSafter kimi), rendererproviders.ts/types.ts/ConnectAffordancenote /ProviderLogo(asset already exists).src/quota/zcode.ts(ported copy) +READERSinsrc/quota/index.ts, per the two-copies convention.docs/providers/zcode.md+ index row.Known limitation (documented)
When leveldb compacts the journal into
.ldb, records are snappy-compressed and invisible to the raw scan; the gauge degrades todisconnecteduntil the webview writes a fresh journal entry. Menubar Swift mirror left for a follow-up, matching how other quota providers landed.Testing
app/electron/quota/zcode.test.ts(journal scan incl. UTF-16LE + rotation + newest-journal, decode suite, terminal/transient classification, business-401, 429 Retry-After, redaction) andtests/quota-zcode.test.ts(CLI).index.test.tsprovider order; all quota suites green (24 + 11 + 54 checks across runs), app typecheck clean, full app + root suites pass except pre-existing flakes unrelated to quota (verified: the failing sets differ run-to-run on this branch and on pristineupstream/main).connected, planPro, 5-hour + Weekly windows with reset timestamps.