Skip to content

Keep Mistral allowances available when browser billing fails - #5205

Open
huaxel wants to merge 11 commits into
steipete:mainfrom
huaxel:mistral/allowance-billing-fallback
Open

huaxel wants to merge 11 commits into
steipete:mainfrom
huaxel:mistral/allowance-billing-fallback

Conversation

@huaxel

@huaxel huaxel commented Nov 28, 2026 •

Copy link
Copy Markdown

Mistral now keeps usable allowances or credits from the same browser session when the billing endpoint returns 404/410, a server error, or an unusable report. Missing spend and token history remain unavailable. Authentication failures, rate limits, cancellation, and alternate-session recovery retain their existing behavior.

The final diff is limited to eight files. The proposed API-key source, new settings and refresh controls, shared account/pipeline changes, and importer diagnostics have been removed. Existing source and cookie policy remain unchanged.

Validation: focused native Swift tests passed, including Mistral recovery and spend publication, provider architecture, and cookie-prompt contracts. make check passed with zero formatting or strict-lint violations. The recovery regression failed against main and passed after the fix using injected HTTP responses; the provider is disabled in the validation machine's configuration, so this does not claim live partial-outage reproduction.

Thanks @huaxel for the recovery implementation and regression scenarios. Original commits remain on this branch.

@clawsweeper

clawsweeper Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-04T23:29:30.217413Z 7981424 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added P2 Normal priority bug or improvement with limited blast radius. impact:auth-provider This issue is about auth, provider routing, model choice, or SecretRef resolution. impact:ux-friction User-facing flow adds avoidable confusion or support burden without fully blocking progress. labels Nov 28, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9d43d11641

ℹ️ 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".

switch context.sourceMode {
case .api: [MistralBudgetFetchStrategy()]
case .web: [MistralWebFetchStrategy()]
case .auto: [MistralBudgetFetchStrategy(), MistralWebFetchStrategy()]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor the configured Mistral source in the app

With "source": "web" and an API key in the shared config, normal app refreshes still enter .auto: MistralProviderImplementation does not implement sourceMode(context:), so ProviderRegistry.resolvedSourceMode receives the protocol default .auto. The new key-first branch then returns allowances only, dropping billed spend, credits, and token history despite the explicit browser selection. Conversely, configured .api still permits cookie fallback. Add an app-side source-mode override that reads the configured Mistral source.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 28, 2026
@clawsweeper

clawsweeper Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge.

What this changes

Preserves Mistral allowances and credits after browser billing failures and adds API-key fetching, source controls, cookie refresh, and allowance icons.

Example: Browser billing returns HTTP 404 while the same session reports Included API usage of 20% and €35 credit.

  • Before: The refresh fails before fetching the available allowances and credit.
  • After: The refresh shows allowances and credit while marking spend and token history unavailable.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Successful API-key proof improves confidence, and the earlier defects are fixed, but important changed paths remain unproved and expanded scope awaits an owner decision.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: A broken browser billing report hides allowances and credits that Mistral can still return, while cookie access can prevent allowance retrieval entirely.
Reason: Browser recovery has clear value, but adding credentials, a source picker, Off semantics, and key-first Auto expands the product contract beyond that repair.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this PR open: current main still loses supplemental Mistral data when billing fails, and the earlier code findings are fixed; the expanded API-key and source-selection scope needs an owner decision.

Reviewed head: 6a18f0a4ddcbe9697142d4979573ec7c813abbb5
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should this PR include API-key allowances, key-first Auto, and source controls, or should those ship separately from browser billing recovery?
  • Recommendation: Separate the new source capability: Keep browser recovery focused and move API-key fetching and its source controls into a separately approved feature.
  • Why: Successful key-first fetching is now observed, but that proves implementation rather than owner approval of changing which data Auto returns; no recorded owner decision settles the expanded scope.

Before merge

  • Add real behavior proof - The contributor now proves successful allowance parsing through the changed CLI and real Mistral transport, plus rejected-key routing and preservation of one existing CLI config; browser partial recovery remains covered by stubbed transports, the inspected images show historical cards, and cookie refresh, graphical icons, and the v0.85.0 app upgrade remain unproved. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.

Findings

None.

Tests

  • Missing end-to-end proof: Provide a production-client trace of billing failure recovering usable browser data, changed-build screenshots or video of cookie refresh and graphical allowance icons, and a v0.85.0-to-head upgrade showing existing settings and sessions intact; redact credentials, IPs, phone numbers, and non-public endpoints.
Agent review details

How this fits together

Mistral's provider strategies turn API-key or browser-session responses into usage snapshots consumed by the CLI, menu bar, provider cards, and spend analytics.

flowchart LR
A[Settings and selected account] --> B[Mistral source routing]
B --> C[API key allowances]
B --> D[Browser billing and supplements]
C --> E[Usage snapshot and diagnostic]
D --> E
E --> F[CLI cards and icons]
E --> G[Spend availability]
Loading

Technical review

Best possible solution:

Preserve same-session supplemental data without fabricating spend, and include API-key fetching and source controls only with the owner's approval.

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

Current-main source deterministically aborts supplemental fetching when billing throws; the new tests model HTTP 404/410/500 and unreadable reports, but this review ran no target code.

Is this the best way to solve the issue?

Same-session partial recovery fits the existing provider owner and preserves accounting semantics; API-key fetching is useful additional capability whose default ordering and controls require an owner decision.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against a26ca57b5186.

Provenance checked

  • Browser allowances and billing separation keeps the original intent (578076a: Expose Included API and Vibe allowances independently while retaining billed API spend and treating supplemental sources as optional.)
  • Automatic menu-bar behavior changes intended behavior with a stated reason (Show Mistral included API and Vibe Code allowances #3710: Automatic retained API cash spend; this PR explicitly documents allowance display when billing history is absent and key-first Auto returns no billing history.)
  • Session rejection and alternate-browser recovery keeps the original intent (c491486: Treat the exact Mistral sign-in redirect as invalid credentials so an expired cached session can recover through another browser session.)
  • Shared diagnostic precedence keeps the original intent (f28ddca: Preserve a successful strategy's own diagnostic over a prior failure note; the new default retains that precedence and Mistral explicitly composes both notes.)
  • Credential ownership keeps the original intent (c3895b8: Keep environment projection and selected-account credential policy provider-owned instead of duplicating provider switches across consumers.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current main still requires billing: Main awaits the billing report before subscription, Vibe, or credit probes, so a billing failure prevents otherwise usable supplemental data from being fetched. (Sources/CodexBarCore/Providers/Mistral/MistralProviderDescriptor.swift:201, a26ca57b5186)
  • Partial results preserve accounting boundaries: The introduced path accepts selected billing failures, retains same-session allowances or credits, records supplemental session rejection for recovery, and marks snapshots without mistralUsage unavailable for spend analytics. (Sources/CodexBarCore/Providers/Mistral/MistralProviderDescriptor.swift:249, 6a18f0a4ddcb)
  • New successful production-path proof: The contributor's latest terminal capture shows the changed CLI returning source api, Included API at 0% left, Monthly Plan at 27% left, and matching reset windows against the real endpoint; this resolves the earlier successful-allowance proof gap. (6a18f0a4ddcb)
  • Earlier findings addressed: App source selection now reads shared config, API mode makes saved sessions passive, Off suppresses implicit app and CLI account selection, and shared diagnostic composition preserves existing winner precedence by default. (Sources/CodexBarCLI/TokenAccountCLI.swift:103, 6a18f0a4ddcb)
  • Scope and remaining proof: The full PR body was read through REST, completing the supplied excerpt with sourceBodySha256 2e5426b865299d7b27f9a3471669b061d0c6b2770c2b7b0eefc724c11cfb35e4; it records the combined-versus-split owner choice, unchanged CLI config checksums, and missing browser recovery, refresh, icon, and full app-upgrade proof. (6a18f0a4ddcb)
  • Prior accounting decision respected: The owner closed fix(mistral): fall back to the Admin tRPC usage procedures #3991 over its billed-spend substitution and other defects; this PR instead leaves missing spend unavailable and does not estimate billed spend from Admin consumption procedures.

Likely related people:

  • Peter Steinberger: Raw commit bc29d89 adds Sources/CodexBarCore/Providers/Mistral/MistralUsageFetcher.swift:118 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: bc29d89ab483; files: Sources/CodexBarCore/Providers/Mistral/MistralUsageFetcher.swift)
  • John: Raw commit 578076a adds Sources/CodexBarCore/Providers/Mistral/MistralProviderDescriptor.swift:292 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 578076a1c45c; files: Sources/CodexBarCore/Providers/Mistral/MistralProviderDescriptor.swift)
  • Ellis Nieuwpoort: Raw commit c491486 adds Sources/CodexBarCore/Providers/Mistral/MistralUsageFetcher.swift:132 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c491486b101f; files: Sources/CodexBarCore/Providers/Mistral/MistralUsageFetcher.swift)
  • Mathieu Santostefano: Raw commit 47a4776 adds Sources/CodexBarCore/Providers/Mistral/MistralCookieImporter.swift:74 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 47a4776e914d; files: Sources/CodexBarCore/Providers/Mistral/MistralCookieImporter.swift)

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • merge-risk: 🚨 auth-provider: The PR introduces API-key authentication and changes Auto routing, saved-session precedence, and cookie-source controls, which determine the credential and data source used for refresh.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Complete the remaining browser recovery, UI, and upgrade evidence identified in the proof assessment.
  • Obtain the owner's decision on the combined API-key and source-control scope.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (6 earlier review cycles)
  • reviewed 2026-11-28T10:04:04.987Z sha 9d43d11 :: needs real behavior proof before merge. :: [P2] Honor the configured Mistral source in normal app refreshes | [P2] Preserve the shared winner-diagnostic precedence | [P3] Give API-only allowance failures a recovery action
  • reviewed 2026-11-28T11:51:22.309Z sha 735d8b4 :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-28T12:26:33.796Z sha 1eaf3a1 :: needs real behavior proof before merge. :: [P2] [P2] Suppress disabled saved sessions during CLI account selection
  • reviewed 2026-11-28T13:08:36.124Z sha 6a18f0a :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-28T13:27:07.747Z sha 6a18f0a :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-28T13:45:21.593Z sha 6a18f0a :: needs real behavior proof before merge. :: none

Reviewed November 28, 2026, 9:11 AM ET / 14:11 UTC (Revision 7).

Keep a successful strategy's own diagnostic authoritative by default and let Mistral opt into reporting both the prior API-key failure and its partial-browser note.
Map the configured provider source to the app fetch context, add a Usage source picker, and point API-only failures at browser cookies.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d85749b0d2

ℹ️ 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".

Comment on lines +13 to +14
requiresManualCookieSource: true,
cookieName: nil),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make saved cookie accounts passive in API-key mode

With a saved Mistral session token in the app, selecting API key and entering a valid key still produces MistralBudgetError.missingKey. SettingsStore.effectiveSelectedTokenAccount(for:) keeps the cookie account active because this support has no passiveSourceModes, so ProviderEnvironmentResolver applies the new account override and removes MISTRAL_API_KEY. The .api pipeline only runs MistralBudgetFetchStrategy, so it cannot recover. Mark saved cookie accounts passive for .api (as Command Code already does) so switching sources works without deleting the saved sessions.

Useful? React with 👍 / 👎.

Normalize unsupported configured Mistral source modes (.cli/.oauth) to .auto in the app, and resolve selected Mistral cookie token accounts to .web even when the provider source is set to .api.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7d0b2a26cb

ℹ️ 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".

Comment on lines +294 to +295
result = UsageSnapshot(primary: nil, secondary: nil, details: details, updatedAt: now)
diagnostic = error.partialBillingDiagnostic

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mark allowance-only snapshots as unavailable for spend analytics

With Mistral included in the spend dashboard, an allowance/credit-only refresh has no mistralUsage, but Mistral's tokenCost.isUsageUnavailable remains the default false. publishProviderDerivedTokenSnapshot therefore publishes a nil cost snapshot as a successful empty result, and SpendDashboardSource.makeRequest puts Mistral in confirmedEmptySourceIDs. This discards previously loaded billing history and counts the source as fully covered despite the missing spend and tokens. The new API-key results have the same problem. Set the descriptor's unavailability predicate for snapshots without mistralUsage so these successful allowance fetches do not certify empty billing history.

Useful? React with 👍 / 👎.

Comment on lines +78 to +80
.resolved(context.snapshot.mistralUsage == nil
? context.snapshot.primary ?? context.snapshot.extraRateWindows?
.first(where: { $0.id == "mistral-monthly-plan" })?.window

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Feed the automatic allowance into graphical Mistral icons

When an API-key refresh supplies an allowance and the user selects Critters or Meter bars, this resolver does not affect the rendered quota: StatusItemController.resolvedMenuBarIconPercents still returns (nil, nil) for Mistral unless the metric is .monthlyPlan, and applyIcon passes those values directly to IconRenderer.makeIcon. Consequently, Automatic displays an unavailable meter even with a valid Included API percentage; only the brand/text rendering benefits from this change. Update the Mistral icon override to use the automatic allowance window when billing history is absent, while retaining the spend-only behavior for browser billing.

Useful? React with 👍 / 👎.

Mark .api as a passive source mode on Mistral's TokenAccountSupport so switching Usage Source to API key works without deleting saved cookie sessions, while preserving automatic .web resolution in .auto mode and explicit CLI account selection.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b60a1a9dfb

ℹ️ 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".

Comment on lines +101 to +102
cookieSource: { context.settings.mistralCookieSource },
browserOnly: true,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Hide browser re-import while a saved session owns the request

If a saved Mistral session exists and Cookie source is switched back to Automatic in Auto/Web mode, this button is visible even though the saved account remains effective. ProviderCookieSettingsResolver consequently forces .manual; browserOnly changes sourceMode but does not bypass that account. The request never imports or stores a browser cookie, so even a successful usage fetch reports Failed when commitRefreshReadSuppression finds no staged replacement, and an expired saved token cannot recover from a valid browser login. Add an effective-account visibility guard or explicitly bypass saved sessions for this action.

Useful? React with 👍 / 👎.

Return no billing history signal when a snapshot has no mistralUsage payload, and let Automatic mode resolve Mistral's quota window for graphical icons when billing history is absent.
A saved session forces the manual cookie source, so the refresh action staged no browser cookie. Also give API-only network failures an actionable next step.
@huaxel

huaxel commented Nov 28, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

Both merge-risk: 🚨 compatibility inputs are addressed at 735d8b499:

  1. Shared diagnostic precedence is restored to its default. ProviderFetchStrategy.combinePriorFailureDiagnostic(_:with:) returns existing ?? priorDiagnostic, which is logically identical to the removed result.diagnostic == nil guard; only Mistral overrides it to report both causes for its Auto key→cookie failover. AntigravityCLIHTTPSFetchStrategyTests (83 tests) passes, including a winner's own diagnostic outranks the prior failure note.
  2. No persisted data model changed. ProviderSourceMode.api already existed on main, so stored source values are not a new schema; existing token accounts and cookie-source settings keep their meaning (a saved session stays passive in API mode and keeps owning browser-mode requests). The diff touches no Config/Codable/schema file.

Also fixed since that review, in addition to the earlier Codex findings:

  • mistral-reimport-cookie is hidden while a saved session owns the request, since the account forces .manual and supplies its own header, so a browser re-import could stage no cookie.
  • API-only network failures now name a next step (retry, or choose Browser cookies).

make check and git diff --check are clean; the focused suites covering each finding pass. The PR body now carries an explicit shared-pipeline and compatibility section.

@clawsweeper

clawsweeper Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. label Nov 28, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 735d8b4995

ℹ️ 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".

Comment on lines +293 to +295
case let .failure(error):
let details = credits.flatMap { Self.partialCreditDetail($0) }.map { [$0] } ?? []
guard budgets != nil || !details.isEmpty else { throw error }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Route supplemental login failures into session recovery

On macOS, when billing returns HTTP 404 and the cached or first-browser session has expired, subscription and credits requests can reject that session with invalidCredentials. The optional helpers swallow those authentication errors, so this guard rethrows the original 404. Both fetch and fetchUsageFromSessions recover only from invalidCredentials, meaning a valid session in a later browser is never tried and normal refreshes keep failing despite that valid login. Preserve supplemental authentication failures when no partial data succeeds so the existing session-recovery path can continue.

AGENTS.md reference: AGENTS.md:L54-L54

Useful? React with 👍 / 👎.

id: "mistral-cookie-source",
context: context,
source: \.mistralCookieSource,
allowsOff: true,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make saved sessions passive when Cookie source is Off

With a saved Mistral session in Auto or Browser cookies mode, selecting the newly exposed Off option does not disable cookies. effectiveSelectedTokenAccount(for:) keeps the account active, and ProviderCookieSettingsResolver rewrites the configured .off to .manual for that account. The account-source resolver also forces .web, so refreshes continue sending the saved cookie while Settings reports that Mistral cookies are disabled; in Auto, the configured API key is also removed from the request environment. Honor .off before selecting and injecting saved cookie accounts.

Useful? React with 👍 / 👎.

Off now retires a saved Mistral session so Settings matches what is sent, and a session rejected on a supplemental allowance probe reaches alternate-session recovery instead of surfacing as the billing error.
@huaxel

huaxel commented Nov 28, 2026

Copy link
Copy Markdown
Author

Fixed both findings from the 735d8b499 review in 1eaf3a103.

P1 — supplemental login failures now reach session recovery. The best-effort allowance/credits probes were swallowing invalidCredentials, so the partial-billing guard rethrew the original 404 and fetch never tried a later browser session. Probes now run through one runOptionalProbe helper that records an authentication failure; when no partial data is usable the fetch throws that rejection instead of the billing error, and fetchUsageFromSessions continues to the next candidate. Partial results still win when they exist (a partial result still publishes when another supplemental probe is rejected).

P2 — Cookie source → Off now retires a saved Mistral session. Two changes, both scoped to Mistral through a new TokenAccountSupport.disabledCookiesSuppressAccount capability (off by default): effectiveSelectedTokenAccount returns nil for .off, and ProviderCookieSettingsResolver refuses to inject the stored header. So Off no longer forces the .web source or removes the API key from Auto, and Settings matches what is actually sent. Documents that in docs/mistral.md. I deliberately did not change the shared default: KimiTokenAccountTests asserts a saved account outranks the cookie source, and that contract still holds.

Verification: swift test --filter 'Mistral|KimiTokenAccountTests|ProviderCookieSettingsResolverTests|ProviderSettingsDescriptorTests|StatusItemAnimationSignatureTests' — 264 + 7 passed; swift test --filter 'TokenAccount|Cookie|SourceMode|SourceAccount' — 469 + 22 + 2 passed; make check clean (SwiftLint 0 violations in 3263 files).

@huaxel

huaxel commented Nov 28, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

New head 1eaf3a103 adds two commits that fix the Codex findings posted against 735d8b499:

  1. P1 — supplemental session rejections reach recovery. The allowance/credits probes now share one runOptionalProbe helper that records an invalidCredentials rejection; when no partial data is usable the fetch throws that instead of the billing 404, so fetchUsageFromSessions continues to the next browser candidate. Covered by a session rejected on a supplemental probe still reaches alternate-session recovery and a partial result still publishes when another supplemental probe is rejected.
  2. P2 — Cookie source → Off retires a saved session. A new TokenAccountSupport.disabledCookiesSuppressAccount capability (default false) lets Mistral opt in, so no stored header is injected and the account stops forcing .web. Scoped deliberately: the Kimi contract that a saved account outranks the cookie source still passes.

make check clean, 264 + 7 and 469 + 22 + 2 focused tests passing.

On the outstanding "add real behavior proof" item: this environment has no Mistral API key, and the earlier session recorded that macOS App Protection denied the ad-hoc checkout build access to the Chrome profile, so the partial-browser fallback cannot be exercised here against a real session. The browser-cookie path, cookie refresh, and graphical rendering all require either a key or live cookie access that I cannot obtain from this machine. What the current tests do prove deterministically is the strategy-level behavior through ProviderHTTPTransportHandler, including the production-code fallback ordering; the fixture boundary is the HTTP client, not the strategy.

Please refresh the verdict on 1eaf3a103; findings 1 and 2 are the substantive ones, and the proof gap is environmental rather than an omitted test.

@clawsweeper

clawsweeper Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

🦞👀
Exact review queued.

Re-review progress:

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1eaf3a103f

ℹ️ 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".

// An explicitly selected cookie account must not use another account's configured key.
env.removeValue(forKey: MistralBudgetFetchStrategy.environmentKey)
},
selectedAccountSourceModeResolver: { base, account, _ in account == nil ? base : .web })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retire disabled cookie accounts in CLI Auto mode

With source: "auto", cookieSource: "off", a saved Mistral session, and a valid API key, codexbar usage still selects the saved account: TokenAccountCLIContext.resolvedAccounts checks passiveSourceModes but not the new disabledCookiesSuppressAccount flag. This resolver consequently forces .web, and the account override removes MISTRAL_API_KEY. The new .off guard in ProviderCookieSettingsResolver then leaves no runnable strategy, or produces the macOS-only-source error on Linux. Thus the CLI fails where the app now succeeds, contradicting docs/mistral.md:31–32 (“Auto goes back to the API key”). Apply the Off suppression to implicit CLI account selection as well.

Useful? React with 👍 / 👎.

Apply the opt-in Off suppression to implicit CLI account selection so a saved Mistral session cannot displace the API key, and align the provenance test with allowance-only snapshots settling as unavailable rather than confirmed empty.
@huaxel

huaxel commented Nov 28, 2026

Copy link
Copy Markdown
Author

Fixed the new P2 in 6a18f0a4d, and found one more real defect while validating the full suite.

P2 — CLI account selection now honors the same Opt-in. TokenAccountCLIContext.resolvedAccounts checked passiveSourceModes only, so with source: auto, cookieSource: off, a saved session and a valid key it still returned the session: the account override removed MISTRAL_API_KEY, forced .web, and left no available strategy while ProviderCookieSettingsResolver kept Off. The opt-in suppression now runs before implicit selection; explicit --account behaviour is unchanged. Covered by Mistral disabled cookies keep a saved session out of implicit CLI selection.

Also fixed: a stale provenance assertion from 693527c44. ./Scripts/test.sh --direct-workers 8 surfaced SpendDashboardTokenProvenanceTests.provider success without cost projection confirms empty publication failing deterministically (1913 selections, 159 first-pass groups, 1 group timed out, this suite failing twice). The cause is this PR own change: tokenCost.isUsageUnavailable now treats an allowance-only Mistral snapshot as unavailable, so it settles as isUnavailable and correctly does not bump the publication revision — but the test still expected a confirmed-empty publication at revision 1. The test now asserts the unavailable settlement (isUnavailable == true, revision 0), which is the behavior the PR intends: a key-only refresh must not certify empty billing history. That failure was invisible to make check, which does not run tests, so thanks for the prompt to run the whole suite again.

Verification on 6a18f0a4d: swift test --filter 'SpendDashboardTokenProvenanceTests|TokenAccountCLISelectionTests|Mistral' — 180 + 7 passed; make check clean.

@huaxel

huaxel commented Nov 28, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

Two more commits are on the branch; the P2 from the 1eaf3a103 review is fixed in 6a18f0a4d.

  • P2 (CLI selection) — TokenAccountCLIContext.resolvedAccounts now applies the same disabledCookiesSuppressAccount opt-in before implicit selection, so source: auto + cookieSource: off + saved session + valid key resolves to the API key instead of a forced .web account override. Explicit --account keeps its precedence. Test: Mistral disabled cookies keep a saved session out of implicit CLI selection.
  • Full-suite regression found and fixed — SpendDashboardTokenProvenanceTests still asserted a confirmed-empty Mistral publication at revision 1 after the spend-unavailability commit made an allowance-only snapshot settle as unavailable. The assertion now matches the intended behavior (revision 0, isUnavailable).

Full suite on 6a18f0a4d: 1913 selections across 171 groups, zero assertion failures. The only non-green signal is a per-group budget overrun: UsageStoreCachedTokenHydrationTests needs 84 s + 79 s for two Pi cost-discovery tests on this machine, so its 12-suite group passed the 180 s budget even though the suite passes standalone in 170 s. make check is clean.

The proof item from the previous review is unchanged in status: this machine has no Mistral API key, and macOS App Protection blocks the checkout build from the Chrome profile, so key-path success and partial-browser recovery cannot be captured live here. The PR body states that limit rather than implying coverage.

@clawsweeper

clawsweeper Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

🦞👀
Exact review queued.

Re-review progress:

@huaxel

huaxel commented Nov 28, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

Added changed-build CLI evidence for the routing defect, including a base/head pair, without touching real settings or Keychain. An isolated CODEXBAR_CONFIG plus CODEXBAR_DISABLE_KEYCHAIN_ACCESS=1 sends the run through the production ProviderHTTPClient to Mistral's real endpoint.

Base 1eaf3a103 — source: auto, cookieSource: off, synthetic saved session, synthetic key:

[{"account":"Saved session","error":{"code":1,"kind":"provider","message":"No available fetch strategy for mistral."},"provider":"mistral","source":"web"}]

The saved session is selected, the source becomes web, the key is dropped, and no strategy is available — the defect as reported.

Head 6a18f0a4d — same configuration:

[{"error":{"code":1,"kind":"provider","message":"Mistral rejected the API key. Check its access or replace it in Settings, or choose Browser cookies as the usage source."},"provider":"mistral","source":"auto"}]

And with source: api:

[{"error":{"code":1,"kind":"provider","message":"Mistral rejected the API key. Check its access or replace it in Settings, or choose Browser cookies as the usage source."},"provider":"mistral","source":"api"}]

The synthetic key draws a real 401 from Mistral, so this proves source routing, the production transport, and the new diagnostic. It does not prove the allowance success path, and I am not claiming it does.

Still unproved live, for stated environmental reasons: API-key allowance success and browser partial-result recovery (need a real key or a browser session this machine lacks), cookie refresh and icon rendering (need a UI capture). Those remain the honest limits of this PR's evidence.

@clawsweeper

clawsweeper Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Nov 28, 2026
@huaxel

huaxel commented Nov 28, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

Added existing-config preservation evidence to the body, using the same isolated-config setup:

  • An existing config (source: web, cookieSource: manual, stored header, one saved session) reads back unchanged through config validate and usage, and the file is byte-identical afterwards (5fd04cc0… before and after). So the new fields do not rewrite or migrate an existing config.
  • config validate reports no errors for that config.

I am explicitly not claiming a full v0.85 upgrade run: launching two app versions against one app-group store has not been exercised, and I will not imply it has.

Remaining unproved items are unchanged and each needs something this machine cannot supply: a real Mistral key (allowance success path), a Chrome session the checkout build can read (browser partial recovery), or a UI capture of the built app (cookie refresh, icon rendering). The body now lists those limits next to the evidence instead of leaving them implicit.

@clawsweeper

clawsweeper Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

🦞👀
Exact review queued.

Re-review progress:

@huaxel

huaxel commented Nov 28, 2026

Copy link
Copy Markdown
Author

@clawsweeper re-review

The API-key allowance success path is now proven live on the changed build — the item that was previously covered only by stubs.

Author-run against the real endpoint with a real key in the environment:

$ CodexBarCLI usage --provider mistral
== Mistral (api) ==
Included API: 0% left [------------]
Resets in 2d 9h
€<redacted> / €<redacted> · €<redacted> left
Monthly Plan: 27% left [===---------]
Resets in 2d 9h
€<redacted> / €<redacted> · €<redacted> left

Currency amounts are redacted; percentages, labels, and the reset window are the parts that matter. This shows both allowances parsed from the undocumented budget endpoint, mapped onto the Included API window plus the Monthly Plan extra window, with matching reset timestamps.

It also settles the ordering question with observation rather than assertion: no --source flag was passed and this config stores no source, so Auto stopped at the API key and reported api without touching browser billing.

Remaining unproved items are narrower now: partial browser recovery (needs a failing billing response alongside a valid session, which I cannot induce), cookie refresh, and changed-build icon rendering. The body lists them explicitly.

@clawsweeper

clawsweeper Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

🦞👀
Exact review queued.

Re-review progress:

@huaxel

huaxel commented Nov 30, 2026

Copy link
Copy Markdown
Author

New verification on 6a18f0a4:

  • In the changed macOS build, the Automatic graphical meter rendered empty at 0% remaining and filled at 100% used, matching the live Included API allowance. Both captures used the API-key source with cookies off. A redacted side-by-side screenshot is available.
  • The official v0.85.0 macOS CLI and the PR CLI both validated and read the same synthetic saved-session config, with identical redacted output and no byte changes to the file. This is CLI config compatibility, not an app-group upgrade test.
  • The full local Swift suite passed (1,913 selections across 171 groups, two recovered on retry). make check and git diff --check also passed.

The changed-build Cookie source → Refresh action reported Failed on this machine. I couldn’t establish why. A successful browser refresh, live partial billing recovery, and a full v0.85.0-to-head macOS app upgrade remain unverified.

Could a maintainer approve the pending CI run and confirm whether you’d prefer this PR as-is or a browser-recovery-only split? The split would narrow the review, but it would still need the partial billing recovery proof.

huaxel and others added 2 commits December 4, 2026 15:07
Preserve same-session allowances and credits on unavailable billing while keeping spend unknown. Retain existing cookie, account, source, cancellation, and authentication recovery behavior.

Co-authored-by: Juan Benjumea <benjumeamoreno@gmail.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

impact:auth-provider This issue is about auth, provider routing, model choice, or SecretRef resolution. impact:ux-friction User-facing flow adds avoidable confusion or support burden without fully blocking progress. merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. P2 Normal priority bug or improvement with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants