CodexBar icon indicating copy to clipboard operation
CodexBar copied to clipboard

Add LongCat usage provider

Open LeoLin990405 opened this issue 5 months ago • 13 comments

What

Adds LongCat (Meituan) as a disabled-by-default usage provider, surfacing token quota (总额度) and fuel-pack balance (加油包) in the menu bar / Overview.

Why this is a cookie provider

LongCat's public OpenAI/Anthropic-compatible API (api.longcat.chat) exposes no usage/balance/quota endpoint: billing/usage paths return 404 and responses carry no useful rate-limit headers. Usage is only available from the web console (longcat.chat) session, so this mirrors the existing Kimi / MiniMax cookie providers.

Supported auth sources:

  • Manual Cookie: header via settings/env.
  • Automatic browser-cookie import for longcat.chat.

Auth and privacy boundary

Maintainer decision requested: this intentionally forwards the full longcat.chat cookie header because the Meituan-passport auth cookie name is undocumented. If that boundary is not acceptable, this should wait for a documented LongCat usage endpoint or a narrower supported auth token.

Current guardrails:

  • Provider is disabled by default.
  • Off disables web auth entirely, including lingering env cookies.
  • Manual only uses the pasted/manual cookie header and does not import browser cookies.
  • Browser import is limited to app runtime, user-initiated refreshes, and Auto cookie source.
  • LongCat Auto import defaults to Chrome-only on macOS to avoid probing unrelated browser stores/keychains.
  • user-current response bodies are never logged because they can include a session token and phone number.

Endpoints and mapping (verified against redacted live response shapes)

Endpoint Fields used
GET /api/v1/user-current data.name (account)
GET /api/lc-platform/v1/tokenUsage data.usage.{totalToken, usedToken, availableToken}
GET /api/lc-platform/v1/pending-fuel-packages data.totalQuota + data.list[]

Mapping behavior:

  • Primary window = token quota used percent.
  • Secondary window = fuel-pack balance, with nearest expiry when available.
  • Missing/undecodable quota data leaves primary nil instead of rendering a fake 0% window.
  • Envelope auth failures from required user-current surface as invalid-session errors, so expired cookies prompt re-auth instead of an empty successful snapshot.

Review follow-up

Addressed Codex review findings:

  • Surfaced required envelope auth failures.
  • Removed the unreachable/nonexistent today-token path.
  • Routed env cookies through LongCatSettingsReader for lower-case alias and quote trimming.
  • Honored Off before env-cookie fallback.
  • Kept Manual from importing browser cookies.
  • Omitted the primary quota window when quota data is missing.
  • Changed LongCat Auto cookie import to Chrome-only by default.
  • Removed the release-owned changelog edit from this PR.

Wiring

.longcat added to UsageProvider / IconStyle, descriptor registry, settings snapshot + builder, implementation registry, logging categories, widget metadata, cost-usage scanner, debug-log switch, provider icon, docs/configuration.md provider-id list, and focused unit tests covering the redacted live response shapes and cookie-source behavior.

Testing

  • swift test --filter 'LongCat|BrowserCookieOrder' ✅ (28 tests)
  • make check ✅
  • PR CI ✅ (changes, lint, Linux x64/arm64 builds, macOS shards 0-3, lint-build-test, GitGuardian)

LeoLin990405 avatar Jun 21 '26 13:06 LeoLin990405

Codex review: needs maintainer review before merge. Reviewed July 7, 2026, 5:20 AM ET / 09:20 UTC.

Summary The branch adds a disabled-by-default LongCat cookie-based usage provider with settings, browser-cookie import, quota/fuel-pack parsing, icon/docs/widget/registry wiring, and focused tests.

Reproducibility: not applicable. this is a provider feature PR rather than a bug report. The changed behavior is source-reviewable through the new fetcher/settings code and the posted redacted live-output proof.

Review metrics: 2 noteworthy metrics.

  • Provider integration size: 25 files changed, +1262/-4. The branch touches shared provider registration, settings, docs, widgets, icon resources, fetcher code, and tests, so maintainers should review it as a full provider addition.
  • New auth surface: 1 cookie-based provider added. LongCat introduces browser/manual cookie handling and session forwarding that need explicit security-boundary acceptance.

Merge readiness Overall: 🦐 gold shrimp Proof: 🦞 diamond lobster Patch quality: 🐚 platinum hermit Result: needs maintainer review before merge.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Get explicit maintainer sign-off to accept the full-cookie LongCat boundary, or revise the provider around a documented narrower credential.

Risk before merge

  • [P1] Merging accepts a new core auth-provider path that forwards the full imported longcat.chat cookie header because LongCat/Meituan does not document a narrower usage credential.
  • [P1] The console response mapping is pinned to live but undocumented endpoints, so future LongCat web-console changes may break usage display even though focused tests cover the captured shapes.

Maintainer options:

  1. Accept the cookie boundary before merge (recommended)
    A maintainer can explicitly approve the full-cookie LongCat provider with its current disabled-by-default and isolated-transport guardrails.
  2. Block until a narrow credential exists
    Pause or close this PR if core should not forward a whole browser session cookie jar for LongCat usage data.
  3. Request extra user-facing consent copy
    If maintainers accept the boundary but want stronger UX disclosure, ask for a focused settings warning before merge.

Next step before merge

  • [P2] No mechanical repair remains; the next action is human sign-off on the LongCat auth/privacy boundary.

Maintainer decision needed

  • Question: Should CodexBar core accept a disabled-by-default LongCat provider that forwards the full longcat.chat cookie header to LongCat console endpoints because no narrower documented usage credential is available?
  • Rationale: The implementation guardrails are now in place, but deciding whether full browser-session cookie forwarding is acceptable is a security/product boundary choice rather than a mechanical code-review issue.
  • Likely owner: steipete — He is the tagged repository owner and authored the adjacent merged Sakana cookie-provider hardening that this PR mirrors.
  • Options:
    • Accept guarded full-cookie provider (recommended): Approve the current boundary with the existing mitigations: disabled by default, Manual/Off semantics, user-initiated Chrome-only Auto import, no user-current body logging, and isolated cookie-free transport.
    • Require a narrower credential: Ask the contributor to remove or defer the provider until LongCat exposes a documented usage endpoint or named auth token that avoids forwarding the whole cookie jar.
    • Keep as external/custom-provider work: Decline a first-class provider for now and steer this demand toward a future custom-provider or plugin-style surface once that exists.

Security Needs attention: No narrow code exploit was found, but merge needs maintainer acceptance of the new full-cookie auth boundary.

Review details

Best possible solution:

Merge only after a maintainer explicitly accepts the full-cookie boundary for this disabled-by-default provider; otherwise park LongCat until a documented narrower credential or usage endpoint exists.

Do we have a high-confidence way to reproduce the issue?

Not applicable: this is a provider feature PR rather than a bug report. The changed behavior is source-reviewable through the new fetcher/settings code and the posted redacted live-output proof.

Is this the best way to solve the issue?

Unclear until maintainer sign-off: the implementation now matches the hardened cookie-provider pattern and resolves the prior transport issue, but full-cookie forwarding must be accepted or rejected as a product/security boundary.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 46edb383c0ac.

Label changes

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR includes redacted live output from a real app-runtime LongCat Auto refresh showing identity present and quota rendered, with private cookies/account details omitted.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a normal-priority optional provider addition with meaningful auth/security review surface but no urgent current-user regression.
  • merge-risk: 🚨 auth-provider: The PR adds a new provider route that resolves manual/env/browser cookies and uses them for LongCat usage fetching.
  • merge-risk: 🚨 security-boundary: The PR intentionally forwards the full longcat.chat cookie header because LongCat does not document a narrower auth token.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR includes redacted live output from a real app-runtime LongCat Auto refresh showing identity present and quota rendered, with private cookies/account details omitted.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR includes redacted live output from a real app-runtime LongCat Auto refresh showing identity present and quota rendered, with private cookies/account details omitted.
Evidence reviewed

Security concerns:

  • [medium] Full LongCat cookie forwarding needs sign-off — Sources/CodexBarCore/Providers/LongCat/LongCatCookieImporter.swift:22 The importer builds a request Cookie header from every longcat.chat cookie because the auth cookie name is undocumented; even with disabled-by-default and Chrome-only/user-initiated guardrails, that is a sensitive session boundary maintainers must explicitly accept. Confidence: 0.86

What I checked:

Likely related people:

  • steipete: Repository owner was explicitly asked for sign-off, authored the merged Sakana cookie-provider hardening, and current main blame shows the adjacent cookie-free transport pattern under his commits. (role: likely decision owner; confidence: high; commits: 87635bcc755b, a83a83fa4131; files: Sources/CodexBarCore/Providers/Sakana/SakanaUsageFetcher.swift, Sources/CodexBarCore/ProviderHTTPClient.swift)
  • LeoLin990405: The author carried the LongCat branch and was credited in related merged Sakana provider context, making them the best implementation follow-up owner if maintainers request changes. (role: adjacent provider contributor; confidence: medium; commits: 39b5b5af1cb2; files: Sources/CodexBarCore/Providers/LongCat/LongCatUsageFetcher.swift, Sources/CodexBarCore/Providers/LongCat/LongCatCookieImporter.swift, Tests/CodexBarTests/LongCatProviderTests.swift)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (1 earlier review cycle)
  • reviewed 2026-07-03T15:34:31.836Z sha ef5d28e4cb597e5f6e35a1e0b33a2509beaef56a :: found issues before merge. :: [P1] Use a cookie-free default transport

clawsweeper[bot] avatar Jun 21 '26 13:06 clawsweeper[bot]

Thanks for the review — both P2s are addressed in 35076321:

  1. Invalid-session surfacing — user-current now propagates envelope auth failures (try instead of try?); .invalidSession is non-fallback, so expired cookies prompt re-auth instead of an empty snapshot.
  2. Unused today-token path — removed the never-assigned todayTokens/freeQuota fields and the unreachable tertiary window. LongCat's tokenUsage is a quota snapshot with no per-day figure.

On the cookie import using only the first session: that's intentional parity with the existing Kimi/MiniMax cookie providers (single-account balance read); happy to generalize if you'd prefer.

Behavior proof

The field mapping is not guessed — it's locked against live responses captured from a logged-in longcat.chat console session (the public api.longcat.chat key exposes no usage endpoint, hence the cookie path). Captured shapes (values neutralised):

GET /api/lc-platform/v1/tokenUsage →

{ "code": 0, "message": "SUCCESS",
  "data": { "usage": { "totalToken": 500000, "usedToken": 0, "availableToken": 500000 },
            "extData": { "LongCat-Flash-Lite": { "totalToken": 50000000, "usedToken": 0 } } } }

GET /api/lc-platform/v1/pending-fuel-packages → { "code": 0, "data": { "totalQuota": 0, "list": [] } } GET /api/v1/user-current → data.name (the body also carries a session token + phone, so it is never logged).

LongCatProviderTests asserts buildSnapshot against these exact shapes (quota %, fuel-pack sum + expiry, envelope invalid-session). Full swift test is green.

@codex review

LeoLin990405 avatar Jun 23 '26 03:06 LeoLin990405

Re-review follow-up — both findings handled in 4110e2ae / the rebase:

  • Env cookie routing (P2): LongCatCookieHeader now resolves the env value via LongCatSettingsReader.cookieHeader(environment:), so the lower-case longcat_manual_cookie alias + quote-trimming apply on the env path. +regression test.
  • Changelog daily-token wording (P3): dropped during the rebase onto main (entry now reads "console token quota (总额度) and fuel-pack balance (加油包)").

Branch is rebased onto latest main, swift build + swift test green locally.

@codex review

LeoLin990405 avatar Jun 23 '26 04:06 LeoLin990405

Both cookie-source findings fixed in 670a9d25:

  • Off now fully disables web auth (env override gated in resolveCookieOverride).
  • Manual no longer silently browser-imports — browser/keychain fallback is Auto-only.

+2 regression tests. swift build + swift test green locally.

@codex review

LeoLin990405 avatar Jun 23 '26 06:06 LeoLin990405

All Codex review threads have been addressed and resolved. PR body now documents the latest cookie-source guardrails, Chrome-only LongCat auto import default, missing-quota behavior, validation, and the maintainer auth/privacy decision point.

@codex review @clawsweeper re-review

LeoLin990405 avatar Jun 24 '26 06:06 LeoLin990405

🦞🧹 ClawSweeper re-review requested.

I asked ClawSweeper to review this item again. Action: item re-review queued (workflow sweep.yml, event repository_dispatch). Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

clawsweeper[bot] avatar Jun 24 '26 06:06 clawsweeper[bot]

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 5197371d69

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@openclaw-mantis visual task: verify CodexBar renders LongCat quota and fuel-pack values from a real longcat.chat session with private cookies/account details redacted.

LeoLin990405 avatar Jun 24 '26 06:06 LeoLin990405

Redacted live behavior proof

Ran a local live proof against the current PR head (5197371d694e8283de0ee0120ab80c9dfceb19ac) using the LongCat provider path with:

  • runtime: app
  • interaction: userInitiated
  • cookie source: auto
  • import policy: macOS Chrome-only browser cookie import

No cookie values, auth tokens, account names, phone numbers, IPs, raw response bodies, or endpoint URLs are included below.

{
  "commit": "5197371d694e8283de0ee0120ab80c9dfceb19ac",
  "provider": "longcat",
  "runtime": "app",
  "interaction": "userInitiated",
  "cookieSource": "auto",
  "importPolicy": "macOS Chrome-only browser cookie import",
  "strategyAvailable": true,
  "fetchSource": "web",
  "identityPresent": true,
  "primaryRendered": true,
  "primaryUsedPercent": 0,
  "primaryDescription": "0/500000",
  "fuelPackEndpointObserved": true,
  "fuelPackEndpointTotalQuota": 0,
  "fuelPackEndpointPackageCount": 0,
  "fuelPackRendered": false,
  "timestamp": "2026-06-24T06:22:54Z"
}

Notes:

  • Quota rendering is visible through the primary usage window (0/500000, 0%).
  • The fuel-pack endpoint was reached successfully and returned total quota 0 with 0 active packages for this account, so no secondary fuel-pack window is rendered; that matches the current UsageSnapshot behavior.
  • The proof was generated with a temporary local test harness and then removed from the worktree; no proof-only code is part of this PR.

Maintainer sign-off still requested: this PR intentionally forwards the full longcat.chat cookie jar because the LongCat/Meituan auth cookie name is undocumented. Please confirm whether that boundary is acceptable while the provider remains disabled by default and Auto import is Chrome-only/user-initiated.

@clawsweeper re-review

LeoLin990405 avatar Jun 24 '26 06:06 LeoLin990405

Maintainer sign-off requested for the final ClawSweeper gate.

The remaining decision is whether CodexBar core accepts forwarding the full longcat.chat cookie jar for this disabled-by-default provider, given that LongCat/Meituan does not document a narrower usage credential. Current mitigations are:

  • provider disabled by default
  • Auto import is app-runtime + user-initiated only
  • Auto import defaults to Chrome-only on macOS
  • Manual/Off do not silently browser-import
  • user-current bodies are never logged
  • redacted live proof is now posted and ClawSweeper marked proof: sufficient

@steipete could you explicitly confirm whether this full-cookie boundary is acceptable for merge?

LeoLin990405 avatar Jun 24 '26 06:06 LeoLin990405

Rebased onto latest main and resolved the conflicts introduced by the Sakana provider landing in #1774 across the shared provider-registration surfaces (Providers, ProviderDescriptor, UsageStore, CostUsageScanner, widgets, and docs/configuration.md). Both providers now coexist; the documented ID list is regenerated in enum order and CodexParserHash is regenerated.

I also folded in the same hardening pattern #1774 applied to Sakana: a blocked 3xx response (e.g. an expired-cookie login redirect that the shared transport's redirect guard drops) is now classified as .invalidSession instead of a generic HTTP <code> error, so users see "sign in again" rather than "HTTP 302". The existing envelope surfaces invalid session on auth code test already covers LongCat's primary expired-session path (the Meituan envelope returns HTTP 200 with an inner code: 401); the 3xx guard is defense-in-depth.

swift build is clean and the affected suites pass locally — LongCatProviderTests, ConfigurationDocsProviderIDTests, ProviderIconResourcesTests, and CostUsage* (239 tests). The only failures in the full local run were the known wall-clock-timing flaky suites (CodexLoginRunner, Antigravity*Deadline, DeepSeek/CommandCode grace, SubprocessRunner) that slip under local CPU load; CI is the authoritative signal there.

Now that #1774 established that core accepts cookie-source providers, this should be ready for the final maintainer look. Happy to adjust anything to match the Sakana hardening bar.

LeoLin990405 avatar Jun 28 '26 17:06 LeoLin990405

Rebased onto latest main — resolved the conflicts from the Doubao Coding Plan (#1841), Qoder, and CrossModel providers landing, so longcat now coexists with all of them (registration surfaces + docs/configuration.md regenerated in enum order, CodexParserHash regenerated). swift build is clean, focused suites pass (LongCat / ConfigurationDocs / ProviderIcon / CostUsage), and CI is green on the current head.

Maintainer edits are enabled on this branch, so feel free to push any hardening directly if that's easier than a round-trip. Ready when you are — thanks!

LeoLin990405 avatar Jul 03 '26 08:07 LeoLin990405

Addressed the blocking patch-quality finding (isolated transport) and rebased onto latest main.

  • Isolated, cookie-free transport. LongCat fetches now run on their own ephemeral ProviderHTTPClient with httpCookieStorage = nil and httpShouldSetCookies = false (behind the same redirect guard), so the console's Set-Cookie responses can no longer enter the shared provider URLSession cookie jar — auth is carried solely by the explicit request Cookie header. This mirrors the Sakana provider's isolated transport.
  • Rebased onto latest main, resolving conflicts from the ClawRouter/CrossModel/Qoder landings (registration surfaces + docs/configuration.md regenerated in enum order, CodexParserHash regenerated).
  • Earlier follow-ups already in this branch: HTTP status paths (401/403 and blocked 3xx login redirects → .invalidSession) now have scripted-transport tests, and fuel-pack parsing is pinned to the live-verified availableToken/expireTime fields.

swift build is clean and the focused suites pass (LongCat / ConfigurationDocs / ProviderIcon / CostUsage). The remaining item is the product decision on forwarding the full longcat.chat cookie — happy to follow whichever way you prefer (accept the boundary, or gate behind a documented narrower credential).

LeoLin990405 avatar Jul 07 '26 09:07 LeoLin990405

ClawSweeper status: review started.

I am starting a fresh review of this pull request: Add LongCat usage provider This is item 1/1 in the current shard. Shard 0/1.

This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

clawsweeper[bot] avatar Jul 17 '26 02:07 clawsweeper[bot]

Merged as a6b3b3d95aaed9d43e1e12b6fcae69535566ce36 after maintainer fixes and verification.

Verification:

  • Reviewed the full PR diff for security and scope. Network traffic is limited to official https://longcat.chat endpoints. Browser import remains disabled by default, Manual/Off modes are respected, imported cookies are scoped per request host/path/secure/expiry rules, all Chrome profiles are tried on credential failures, and response bodies are not logged.
  • swift test --filter 'LongCat|ProviderConfigEnvironmentTests': 83 tests in 3 suites passed. Coverage includes captured/synthetic quota shapes, fuel packages, Manual/Off/Auto behavior, cookie scoping, multi-profile fallback, malformed required quota responses, and optional fuel failures.
  • make check: passed; locale/docs/parser/package checks passed, SwiftFormat reported 0/1492 files requiring changes, SwiftLint reported 0 violations in 1491 files.
  • Structured autoreview on the final candidate: no accepted/actionable findings.
  • Exact head 60e5f61064957f50f816a4de97b610f9eb20d1a6: all required CI green — Linux x64/arm64, macOS shards (33m02s and 22m30s), lint, aggregate gate, change gate, and GitGuardian.

Live account verification was unavailable to the maintainer; no real-account probe was claimed.

steipete avatar Jul 17 '26 04:07 steipete