Repository navigation
fix(models): clear stale auth cooldowns after early limit resets - #107671
Glucksberg wants to merge 6 commits into
Conversation
|
Codex review: needs real behavior proof before merge. What this changesAdds an agent-scoped command to clear saved authentication failure windows and advertises it in model and Doctor diagnostics. Example: An operator restores Anthropic credit while anthropic:work remains billing-disabled.
Review scores
ProductKind: Feature · Worth it: Needs a maintainer decision · Fix scope: Partial Merge readiness⛔ Blocked before merge - 8 items remain Keep this PR open: manual recovery still has value, but the three previously reported implementation findings remain unresolved. Priority: P2 Decision needed
Before merge
Findings
Provenance
Tests
Agent review detailsHow this fits togetherModel authentication stores credentials and usage health in shared or agent-local SQLite stores; CLI diagnostics read those records, while credential selection uses them to admit requests or choose fallbacks. flowchart TD
A[Model and Doctor diagnostics] --> B[Operator recovery command]
B --> C[State ownership selection]
C --> D[Auth health store]
D --> E[Gateway auth refresh]
E --> F[Provider request]
Technical reviewBest possible solution: Provide one state-owner-routed reset that targets the displayed health record and preserves credentials, selection settings, and unrelated usage. Do we have a high-confidence way to reproduce the issue? Current source preserves active billing disables after external recovery, and supported shared/local credential ownership demonstrates the wrong-store reset path; no target code was executed. Is this the best way to solve the issue? Explicit recovery complements existing automatic subscription recovery, but it must use the existing state owner and address health-record ownership rather than infer it solely from credential ownership. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against e7f054619274. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +185, Tests +392, Docs +3. Total +580 across 19 files. Added test files: 3. View PR surface stats
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes: No label changes. Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (67 earlier review cycles; latest 8 shown)
Reviewed October 27, 2026, 9:13 PM ET / October 28, 2026, 01:13 UTC (Revision 68). |
822cbf3 to
5b6430f
Compare
5b6430f to
1f4f070
Compare
1f4f070 to
7b9bb6a
Compare
7b9bb6a to
3ec6ff8
Compare
224f128 to
1039d9c
Compare
1039d9c to
27dd961
Compare
81a778b to
b063486
Compare
b063486 to
0f35673
Compare
|
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 804b5aa5bf
ℹ️ 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".
| const cfg = await loadModelsConfig({ commandName: "models auth clear-cooldown", runtime }); | ||
| const { agentId, agentDir } = resolveModelsTargetAgent(cfg, opts.agent, { kind: "mutation" }); | ||
| const store = ensureAuthProfileStore(agentDir); | ||
| if (!Object.hasOwn(store.profiles, profileId)) { |
There was a problem hiding this comment.
Accept cooldown records for inline API keys
When a literal or secret-backed models.providers.<id>.apiKey receives a billing failure, markInlineProviderApiKeyFailure persists it only as usageStats["inline-api-key:<provider>"]; listUnavailableAuthProfiles enumerates that key and the new billing hint instructs the operator to pass it to this command. There is intentionally no matching store.profiles row, so this check always throws not found and the advertised early-recovery path cannot work for configured inline keys. Either reset these usage-only records here or avoid emitting this command for them.
AGENTS.md reference: AGENTS.md:L69-L69
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a5c7d4e3ffa. clear-cooldown now accepts an inline-api-key:<provider> id when the store has a health record for it, and the owner-routed reset persists it. A real-store test in auth-profiles.markauthprofilefailure.test.ts records an inline billing failure, clears it, and rereads the persisted store.
| return "Top up credits (provider billing) or switch provider."; | ||
| } | ||
| const command = formatCliCommand( | ||
| `openclaw models auth clear-cooldown ${quoteShellArg(profileId)}`, |
There was a problem hiding this comment.
Include the selected agent in cooldown recovery commands
When more than one agent is configured, a billing hint produced by models auth list --agent child (or scoped status/Doctor output) omits the target agent. Running the printed command enters the mutation branch of resolveModelsTargetAgent, which calls resolveSoleAgentId and rejects the ambiguous roster, so the recovery action fails before clearing anything. Pass the target agent into the hint and append a quoted --agent option.
AGENTS.md reference: AGENTS.md:L69-L69
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a5c7d4e3ffa. buildAuthProfileUnusableHint takes the store's agentId and appends a quoted --agent option to the billing command. models auth list, models status (through auth-unavailability.ts), and doctor pass it. Covered in doctor-auth.profile-health.test.ts and auth-unavailability.test.ts.
| vi.mock("./store-runtime.js", async (importOriginal) => ({ | ||
| ...(await importOriginal<typeof import("./store-runtime.js")>()), |
There was a problem hiding this comment.
Replace the broad store-runtime partial mock
This focused test only needs updateAuthProfileStoreWithLock, but importOriginal() executes the entire store-runtime.js graph first, including the native plugin-loader composition, which adds unrelated initialization cost and coupling to a one-function unit test. Replace it with an explicit mock factory that exposes only the binding under test, as required for import-bound agent tests.
AGENTS.md reference: src/agents/AGENTS.md:L33-L35
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a5c7d4e3ffa. The test now uses an explicit factory that exposes only updateAuthProfileStoreWithLock, with a mock-isolation reason, instead of an importOriginal partial mock of store-runtime.js.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0f6409cb35
ℹ️ 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".
| ), | ||
| ) | ||
| .toSorted((a, b) => a.remainingMs - b.remainingMs); | ||
| const unusableProfiles = listUnusableAuthProfilesWithHints(store, workspaceAgentId); |
There was a problem hiding this comment.
Keep override-store recovery on the inspected store
When models status runs without --agent under OPENCLAW_AGENT_DIR or PI_CODING_AGENT_DIR and the override has a local billing cooldown, status reads auth state from agentDirOverride (list.status-command.ts:253-255) but this call embeds workspaceAgentId in the recovery command. Running that command enters mutation mode, which maps the ID back to its configured directory (shared.ts:252-254), so it does not clear the inspected store; if the same profile ID exists there, it can instead clear unrelated state and report success. Keep the recovery target bound to the inspected directory, or do not emit an executable command for override-only stores.
AGENTS.md reference: AGENTS.md:L44-L44
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ba7b9103fb4. Mutation target resolution ignores the env dir override (resolveEffectiveAgentDir reads only config), so no --agent value reaches an override store. When models status reads the store from OPENCLAW_AGENT_DIR / PI_CODING_AGENT_DIR, it now passes agentId: null and the billing hint omits the command: "Top up credits (provider billing) or switch provider." Covered in auth-unavailability.test.ts.
| const existing = targets.get(databasePath); | ||
| if (existing) { | ||
| // The agent that owns the shared store addresses it in recovery commands. | ||
| existing.agentId ??= agentId; |
There was a problem hiding this comment.
Assign an agent to shared state-db recovery hints
When shared auth ownership is state-db and multiple agents are configured, resolveSharedAuthStorePath() is the state database while every path computed here is <agentDir>/openclaw-agent.sqlite, so existing is never found and the Shared target keeps agentId undefined. Doctor then prints a billing clear-cooldown command without --agent, and mutation target resolution rejects the ambiguous roster before clearing anything. Fresh evidence beyond the earlier review comment is the state-db path split in path-resolve.ts:157-161 versus sqlite.ts:122-125; assign a valid configured agent to the Shared target even when no database path matches.
AGENTS.md reference: AGENTS.md:L69-L69
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ba7b9103fb4. In the state-db layout no agent database is the shared store, so the Shared target now also takes the agent whose dir is resolveSharedMainAuthAgentDir(). Owner routing sends that agent's write for a shared profile to the shared store. A new doctor test mocks a state-db shared path with two agents and expects --agent 'main'; it fails without the fix.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ba7b9103fb
ℹ️ 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".
| agentDir?: string; | ||
| }): Promise<boolean> { | ||
| const { store, profileId, agentDir } = params; | ||
| const updated = await updateOwnedAuthProfileUsage(store, profileId, { |
There was a problem hiding this comment.
Clear the store that supplied the cooldown
When an agent has an agent-local billing usage row for an inherited shared credential, the effective store reports that local disable, but this call routes by credential ownership and writes the shared store because the credential itself is inherited. The local row still wins after reload, so models auth clear-cooldown ... --agent <child> reports success while the profile remains disabled and may reset a different shared row. Unlike the earlier override-directory case, fresh evidence here is the supported local-row shape exercised in src/commands/doctor-auth.shared-health.test.ts:63-87; recovery needs the owner of the displayed usage row rather than the credential owner.
AGENTS.md reference: AGENTS.md:L44-L44
Useful? React with 👍 / 👎.
| for (const agentId of listAgentIds(cfg)) { | ||
| const agentDir = resolveAgentDir(cfg, agentId); | ||
| const databasePath = resolveAuthProfileDatabasePath(agentDir); | ||
| // The agent that owns the shared store addresses it in recovery commands. In the | ||
| // state-db layout no agent database is the shared store, so match the shared-main dir. | ||
| const ownsShared = targets.get(databasePath) === shared || agentDir === sharedMainAgentDir; |
There was a problem hiding this comment.
Select a reachable agent when no shared-main owner exists
Under state-db ownership with an explicit multi-agent roster whose IDs do not resolve to the legacy shared-main directory (for example {coder, reviewer} or main with a custom agentDir), both checks here are false and shared.agentId remains undefined. Doctor consequently prints clear-cooldown without --agent, and the mutation branch of resolveModelsTargetAgent rejects the ambiguous roster before writing. Fresh evidence beyond the earlier review comment is that explicit rosters need not contain any agent mapped to .../agents/main/agent; provide a reachable target for this shared store or omit the executable command.
AGENTS.md reference: AGENTS.md:L69-L69
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 509ead90b5
ℹ️ 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".
| .argument("<profileId>", "Auth profile id from models auth list") | ||
| .option("--agent <id>", "Agent id (default: configured default agent)") | ||
| .action(async (profileId: string, _opts, command) => { | ||
| await withModelsRuntime(async ({ defaultRuntime, resolveModelAgentOption }) => { |
There was a problem hiding this comment.
Route cooldown clears through the state owner
When a Gateway or another OpenClaw process owns the state database, registering this mutation with withModelsRuntime bypasses the runAuthModelCommand/runWithLocalStateOwner path used by the neighboring models auth commands. The handler then writes the auth SQLite store directly before calling models.authRefresh; that refresh cannot retroactively provide exclusive custody, so the write races the live owner and bypasses its cache/publication contract. Route this action through the auth mutation owner wrapper or a Gateway-owned RPC before loading the handler.
AGENTS.md reference: AGENTS.md:L68-L68
Useful? React with 👍 / 👎.
| const ownerWrite = await updateOwnedAuthProfileUsage(store, profileId, { | ||
| agentDir, | ||
| updater: reset, | ||
| }); |
There was a problem hiding this comment.
Reset the store that supplied the shared cooldown
When Doctor reports a shared-store billing row under state-db, its recovery target can be an agent with a distinct same-ID local credential; in that supported shape updateOwnedAuthProfileUsage resolves the local credential owner here, and the later hasLocalRow check also inspects only that agent database. The shared row Doctor displayed is therefore untouched, but both writes are non-null and clear-cooldown reports success. Fresh evidence beyond the earlier health-row comment is that the final dual-reset implementation still never addresses the shared source in this local-override case (the ownership split is exercised by doctor-auth.shared-health.test.ts:140,163-168); carry the displayed usage-row owner into the reset.
AGENTS.md reference: AGENTS.md:L51-L51
Useful? React with 👍 / 👎.
Operators who resolve a provider billing or usage condition before its recorded reset time stay locked out of the saved profile until the stored window expires, with no supported way to clear it. Add `openclaw models auth clear-cooldown <profileId>`: one owner-routed locked write that resets the persisted cooldown, block, disable, and failure counters without touching credentials or auth order, then reuses the shared gateway auth refresh like the sibling `models auth` write commands. The `models auth list` / doctor billing hint now names that command, so the recovery path is discoverable where the dead end is reported. Move the owner-routed usage write (updateOwnedAuthProfileUsage) from the grandfathered oversized usage.ts into usage-owner-write.ts unchanged and put the reset there; usage.ts shrinks by 29 lines instead of growing past its line-cap ratchet. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The root command JSON-output audit requires every built-in command to either support --json or be listed with a reason. clear-cooldown is a pure side-effect write like its models auth activate/logout siblings. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…agent hints Billing hints name `models auth clear-cooldown`, but two cases could not run the printed command: - Inline `models.providers.<id>.apiKey` failures persist only as `usageStats["inline-api-key:<provider>"]` with no profile row, so the command rejected the id as not found. It now accepts an inline-key id that has a health record; the owner-routed reset already persists it. - With several agents, the mutation path requires `--agent`, but hints from `models auth list`, `models status`, and doctor omitted it. The hint now carries the store's agent. The status row mapping moved into `auth-unavailability.ts` so the grandfathered status command does not grow. The owner-write unit test now mocks only the locked writer instead of a broad `importOriginal` partial mock of the store runtime. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The status billing case pushed list.status.test.ts past its line-cap ratchet. Cover the agent-scoped hint in auth-unavailability.test.ts, next to the helper that now builds it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- `models status` under OPENCLAW_AGENT_DIR / PI_CODING_AGENT_DIR reads the override store, but `clear-cooldown` mutates the configured agent dir. Printing `--agent <id>` there would clear a different store, so the hint omits the command for override-only stores. - In the state-db layout the shared store matches no agent database, so doctor printed the shared hint without `--agent`. The shared target now takes the agent that owns the shared-main dir. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… doctor hints reachable clear-cooldown only wrote the credential owner's store, so a health row kept in the agent's own database (a child's local override of an inherited credential, or an inline-key failure) survived, won again after reload, and the command still reported success. After the owner-routed reset, also reset the agent's own row when one exists; an agent without a row gets no database created. Doctor printed the command without --agent when no configured agent owned the shared state-db store, which the mutation path rejects for several agents. Fall back to a configured agent: all of them reach the shared profile through owner routing.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 764d9885c4
ℹ️ 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".
| vi.mock("../../agents/auth-profiles.js", async (importOriginal) => ({ | ||
| ...(await importOriginal<typeof import("../../agents/auth-profiles.js")>()), |
There was a problem hiding this comment.
Replace the broad auth-profile partial mock
This focused command test only needs ensureAuthProfileStore and clearAuthProfileCooldown, but importOriginal() evaluates the entire auth-profiles.js barrel (including store-runtime.js and its native plugin-loader composition) during module setup. That defeats the lazy-loading boundary and violates the root rule that new tests avoid broad barrel imports; use an explicit factory exposing only those two bindings.
AGENTS.md reference: AGENTS.md:L88-L88
Useful? React with 👍 / 👎.
|
Thanks @Glucksberg for surfacing the early-recovery lockout. A focused, credited replacement landed in #189427 (ef60dd0): authenticated quota checks now honor an earlier provider reset while preserving other profiles' health and credential checks. Markus is credited as co-author. Closing this in favor of the merged replacement; thank you for the recovery report and investigation. |
Related: #70903
What Problem This Solves
Operators who resolve a provider billing or usage condition before its recorded reset time stay locked out of the saved auth profile until the stored window expires. There is no supported way to clear it, and the
models auth list/ doctor billing hint is a dead end.Why This Change Was Made
openclaw models auth clear-cooldown <profileId>: one owner-routed, locked write that resets the persisted cooldown, block, disable, and failure counters. It does not touch credentials or auth order. After the write it runs the same shared Gateway auth refresh (models.authRefresh) as the siblingmodels authwrite commands, so no manual Gateway restart is needed.models auth list/models status/ doctor billing hint now names this command, including--agent <id>for the store it came from, because the mutation path rejects an ambiguous agent roster.models.providers.<id>.apiKeyfailures have a health record (inline-api-key:<provider>) but no profile row. The command accepts that id when the record exists, so the hint shown for inline keys also works.usage.tsis a grandfathered oversized file, so the line-cap ratchet rejects any growth there.updateOwnedAuthProfileUsagemoved unchanged intousage-owner-write.ts, next to the new reset. The dropped-bookkeeping log comes frommain'sstate-observation.ts.usage.tsshrinks by 29 lines (751 → 722). The move adds no test seam: the dropped-write test mocks thestore-runtime.jsmodule boundary, asmaindoes since refactor(testing): deslop test-only production seams #164320.It does not add polling, shorten provider backoffs, change fallback policy, or remove credentials.
User Impact
Operators can re-evaluate a recovered provider with one command, without editing SQLite or repeating OAuth. If the failure still applies, the next request restores the cooldown normally.
Evidence
Head
509ead90b58, rebased ontomainat2f620b970a0. The last commit addresses the two open P2 findings onba7b9103fb4:coder/reviewerno agent owns the shared store, so doctor printed the command without--agent. The Shared target now falls back to a configured agent; owner routing reaches the shared profile from any of them. A doctor test covers it and fails without the fallback.Results on this head:
node scripts/run-vitest.mjspassed onusage-owner-write,usage.inherited-owner,auth-profiles.markauthprofilefailure,usage,auth-clear-cooldown,auth-unavailability,doctor-auth.profile-health,doctor-auth.shared-health,models-cli, androot-command-descriptions.pnpm tsgo:coreand thetsgotest configscore.test.agents-root,agents-other,agents-tools,commands, andcommands-doctorpassed.check:line-cap-ratchet --base upstream/mainandcheck:test-mock-exports --base upstream/mainreported OK;oxlint,oxfmt --check, andgit diff --checkwere clean.check:max-lines-ratchetcurrently fails onmainitself (ui/src/pages/agents/agents-page-state.tsis listed as stale); this PR does not touch it.Remaining merge evidence
models auth clear-cooldown <profileId>-> Gateway auth refresh -> recovered provider request.🤖 Generated with Claude Code