Skip to content

fix(models): share API-key editing and removal - #144420

Merged
obviyus merged 2 commits into
mainfrom
feat/models-shared-api-keys
Sep 10, 2026
Merged

obviyus merged 2 commits into
mainfrom
feat/models-shared-api-keys

Conversation

@obviyus

@obviyus obviyus commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Models saved API keys differently from the CLI, and CLI logout refused profiles referenced by provider configuration.

Why This Change Was Made

Both interfaces now share credential selection, persistence, removal, and auth refresh. The removal owner clears captured references, preserves concurrent replacements, and restores only references for surviving credentials after partial failures. Committed saves retain recovery guidance.

User Impact

Models and CLI edits produce the same stored result while preserving defaults, metadata, reference-backed keys, explicit backups, and local overrides.

Evidence

Real browser/Gateway and CLI checks verified save/remove parity, auth refresh, and selected-model preservation. Public CLI race checks retained a concurrent replacement and rejected reference-backed conversion. Focused owner, CLI, Gateway, plugin-interface, portability, and UI tests cover partial removal, restoration, warnings, and retry. Browser checks verified permission enforcement and active-run preservation. The internal refresh exception was covered by tests but not injected into a live Gateway.

Related: #136257. Supersedes #142851. Builds on #144181.

@obviyus
obviyus requested a review from a team as a code owner September 10, 2026 21:11
@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: android App: android app: web-ui App: web-ui gateway Gateway runtime commands Command implementations agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 10, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 10, 2026
@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 10, 2026, 7:28 PM ET / 23:28 UTC (Revision 7).

ClawSweeper review

What this changes

Makes Models settings and CLI commands share API-key selection, storage, removal, and refresh reporting while preserving unrelated credentials and settings.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 3 items remain

This PR remains necessary, and the earlier findings are addressed. One remaining inline-key removal race can discard a concurrent credential update.

Priority: P2
Reviewed head: ac6e3a16e87931af600b81a67e56bb67dbcc6603

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful shared-owner repair with substantial recorded proof, held back by one concrete concurrent-removal defect.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Recorded real Gateway/browser and public CLI runs exercise the shared save/remove owner with durable-state parity, preserved settings, administrator denial, and stored-profile races. That proof remains valid; it does not cover the newly identified inline-key race or live internal-refresh exceptions.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded real Gateway/browser and public CLI runs exercise the shared save/remove owner with durable-state parity, preserved settings, administrator denial, and stored-profile races. That proof remains valid; it does not cover the newly identified inline-key race or live internal-refresh exceptions.
Evidence reviewed 9 items Current main still needs the change: Fetched main retains the configured-profile logout refusal and the UI builder that stores API keys directly in provider configuration. The shared editing/removal cutover is therefore still distinct work.
Latest release retains the separate UI path: The supplied latest release contains buildProviderApiKeyPatch, which writes the key directly into provider configuration.
Inline removal lacks a captured-value guard: API-key-only cleanup classifies and removes literal keys from the config writer’s current snapshot without comparing them with the request’s captured configuration. An empty profile selection bypasses all credential-generation checks, so a newer inline key can be deleted successfully.
Findings 1 actionable finding [P1] Preserve a concurrently replaced inline key during removal
Security None None.

How this fits together

Models settings and CLI authentication commands manage credentials used by model providers. Their shared mutation owner updates configuration and credential stores, then refreshes the Gateway’s prepared authentication state.

flowchart TD
  A[Models settings] --> C[Administrator Gateway request]
  B[CLI auth commands] --> D[Shared credential operations]
  C --> D
  D --> E[Configuration references]
  D --> F[Credential stores]
  E --> G[Gateway auth refresh]
  F --> G
  G --> H[Updated provider state and recovery messages]
Loading

Before merge

  • Preserve a concurrently replaced inline key during removal (P1) - When models.authLogout starts with credentialType: "api_key", an inline provider key, and no stored profiles, another config writer can replace that key before beforeRemove acquires the config writer. This loop deletes the current literal without comparing it with the captured binding, and the empty profile set lets removal report success. The previous UI config.patch path carried a base hash. Capture the inline binding and reject a changed value before cleanup, with a concurrent-replacement regression. This is a late finding: the file is byte-identical to the preceding reviewed revision.
  • Resolve merge risk (P1) - The recorded live scenarios do not cover a config-only inline-key replacement while API-key removal waits for the writer; that newer credential can currently be lost.
  • Complete next step (P2) - Guard inline-key removal against concurrent config replacement and verify that the newer key survives.

Findings

  • [P1] Preserve a concurrently replaced inline key during removal — src/commands/models/auth-logout.ts:133-140
Agent review details

Security

None.

PR surface

Source +529, Tests +1272, Docs 0, Config +1, Other +5. Total +1807 across 39 files.

View PR surface stats
Area Files Added Removed Net
Source 19 857 328 +529
Tests 16 1478 206 +1272
Docs 1 2 2 0
Config 1 1 0 +1
Generated 0 0 0 0
Other 2 5 0 +5
Total 39 2343 536 +1807

Review metrics

Metric Value Why it matters
Production versus test growth production/generated +534 lines; tests/support +1,272 lines Production growth supports shared credential selection, conditional writes, recovery, and UI cutover.
Gateway contract additions 1 administrator RPC and 1 optional logout selector These route existing Models actions through the shared credential owner without adding a user configuration option.

Root-cause cluster

Relationship: canonical
Canonical: #144420
Summary: This is the active focused extraction for shared API-key editing and removal.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Guard inline-key removal (recommended)
    Capture the selected inline binding and reject a changed value under the config writer, with a regression covering concurrent replacement.

Technical review

Best possible solution:

Keep the shared mutation owner and condition inline-key deletion on the captured binding still matching under the configuration writer.

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

Yes, from source: start API-key-only removal with an inline key and no stored profiles, replace that literal before the config mutator runs, and cleanup deletes the replacement. This review did not execute the scenario.

Is this the best way to solve the issue?

The shared owner is the right direction, but the repair is incomplete: literal configuration keys need the same captured-generation protection as stored profiles.

Full review comments:

  • [P1] Preserve a concurrently replaced inline key during removal — src/commands/models/auth-logout.ts:133-140
    When models.authLogout starts with credentialType: "api_key", an inline provider key, and no stored profiles, another config writer can replace that key before beforeRemove acquires the config writer. This loop deletes the current literal without comparing it with the captured binding, and the empty profile set lets removal report success. The previous UI config.patch path carried a base hash. Capture the inline binding and reject a changed value before cleanup, with a concurrent-replacement regression. This is a late finding: the file is byte-identical to the preceding reviewed revision.
    Confidence: 0.94
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.91

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded Models/CLI credential-management repair rather than an established widespread outage.
  • merge-risk: 🚨 auth-provider: The introduced removal path can delete a concurrently replaced inline provider key.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): Recorded real Gateway/browser and public CLI runs exercise the shared save/remove owner with durable-state parity, preserved settings, administrator denial, and stored-profile races. That proof remains valid; it does not cover the newly identified inline-key race or live internal-refresh exceptions.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded real Gateway/browser and public CLI runs exercise the shared save/remove owner with durable-state parity, preserved settings, administrator denial, and stored-profile races. That proof remains valid; it does not cover the newly identified inline-key race or live internal-refresh exceptions.

Evidence

What I checked:

  • Current main still needs the change: Fetched main retains the configured-profile logout refusal and the UI builder that stores API keys directly in provider configuration. The shared editing/removal cutover is therefore still distinct work. (src/commands/models/auth-logout.ts:78, 0434aa633824)
  • Latest release retains the separate UI path: The supplied latest release contains buildProviderApiKeyPatch, which writes the key directly into provider configuration. (ui/src/pages/model-providers/mutations.ts:3, 1391f7cd2d40)
  • Inline removal lacks a captured-value guard: API-key-only cleanup classifies and removes literal keys from the config writer’s current snapshot without comparing them with the request’s captured configuration. An empty profile selection bypasses all credential-generation checks, so a newer inline key can be deleted successfully. (src/commands/models/auth-logout.ts:137, ac6e3a16e879)
  • The UI cutover removes the previous conflict protection: The old config.patch path sends baseHash. The new external mutation sends models.authLogout with credentialType and no captured binding; its dispatch guard checks connection and permissions, not concurrent configuration values. (ui/src/pages/model-providers/config-mutation.ts:133, ac6e3a16e879)
  • Re-review continuity: Read the exact earlier auth-logout.ts through GitHub’s contents API and compared its decoded bytes with the checkout: byte-identical, blob 11003fff43f83b31b324fa995c9ddee6fe9997da. The inline-removal concern was already visible in the preceding completed review and is marked late. (src/commands/models/auth-logout.ts:137, 9d134d89bfa4)
  • Earlier blockers are repaired: Current code rejects reference-backed replacement under the write lock, checks concurrent save bindings, rereads surviving credentials after incomplete removal, and restores only cleanup-owned references. Tests cover replacement generations, partial deletion, retained token bindings, and retry. (src/commands/models/auth-api-key.test.ts:399, ac6e3a16e879)

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • vincentkoc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • jesse-merhi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Protect a newer inline provider key from pending removal and add a regression through the shared removal owner.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (6 earlier review cycles)
  • reviewed 2026-09-10T21:18:51.556Z sha 2352369 :: blocked before merge. :: [P1] [P1] Protect reference-backed profiles in every replacement path | [P1] [P1] Reject a changed provider binding before restoring the old profile | [P1] [P1] Preserve config references when a removal generation changes
  • reviewed 2026-09-10T21:46:21.561Z sha 6b8f7d00b91850e99cec8bf5fc30131783c8d6a5 :: blocked before merge. :: [P1] [P1] Protect reference-backed profiles in every replacement path | [P1] [P1] Preserve config references when a removal generation changes
  • reviewed 2026-09-10T22:10:25.824Z sha 70dbdc4443be3f3b42e0f2d58ecf881d786087fe :: blocked before merge. :: [P2] [P2] Restore surviving references when store removal throws | [P2] [P2] Exclude committed deletions from configuration rollback
  • reviewed 2026-09-10T22:32:06.481Z sha dfaf4e4 :: blocked before merge. :: [P2] [P2] Restore surviving references when store removal throws | [P2] [P2] Exclude committed deletions from configuration rollback
  • reviewed 2026-09-10T22:46:04.249Z sha 7c55efc076eb2a779ddd0616caeac3d6691e6bee :: blocked before merge. :: [P1] [P1] Preserve untargeted profile bindings during removal recovery
  • reviewed 2026-09-10T23:13:47.031Z sha 9d134d89bfa41c4654d07ad37acf88e45e6fe897 :: needs maintainer review before merge. :: none

@obviyus

obviyus commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

landpr-approve-admin-merge
pr: 144420
head: 9127075
scope: owner-review

@obviyus
obviyus force-pushed the feat/models-shared-api-keys branch from 9127075 to 6b8f7d0 Compare September 10, 2026 21:38
@obviyus

obviyus commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

landpr-approve-admin-merge
pr: 144420
head: 6b8f7d00b91850e99cec8bf5fc30131783c8d6a5
scope: owner-review

@obviyus
obviyus force-pushed the feat/models-shared-api-keys branch from 6b8f7d0 to 70dbdc4 Compare September 10, 2026 22:00
@obviyus

obviyus commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

landpr-approve-admin-merge
pr: 144420
head: 70dbdc4443be3f3b42e0f2d58ecf881d786087fe
scope: owner-review

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 10, 2026
@obviyus
obviyus force-pushed the feat/models-shared-api-keys branch from 70dbdc4 to 8550616 Compare September 10, 2026 22:17
@obviyus

obviyus commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

landpr-approve-admin-merge
pr: 144420
head: 85506165916e8166f5d1ae73e87de7a54e651565
scope: owner-review

@obviyus
obviyus force-pushed the feat/models-shared-api-keys branch from 8550616 to dfaf4e4 Compare September 10, 2026 22:24
@obviyus

obviyus commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

landpr-approve-admin-merge
pr: 144420
head: dfaf4e4
scope: owner-review

@obviyus
obviyus force-pushed the feat/models-shared-api-keys branch from dfaf4e4 to 7c55efc Compare September 10, 2026 22:38
@obviyus

obviyus commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

landpr-approve-admin-merge
pr: 144420
head: 7c55efc076eb2a779ddd0616caeac3d6691e6bee
scope: owner-review

@clawsweeper clawsweeper Bot added the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Sep 10, 2026
@obviyus
obviyus merged commit 09e2b15 into main Sep 10, 2026
206 checks passed
@obviyus
obviyus deleted the feat/models-shared-api-keys branch September 10, 2026 23:42
@obviyus

obviyus commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

Merged with the owner-approved admin exception for the procedural CODEOWNERS hold.

Proof: A real Gateway, Models page, and public CLI saved and removed synthetic API keys with identical durable state. The concurrent CLI binding test preserved the newer binding and returned the saved-key recovery message.

  • Bug: Models and the CLI used separate credential writers, and removal could refuse or restore stale provider references.
  • Fix: Both surfaces now use the shared credential writer, remover, and Gateway refresh owner.
  • Review artifact: Exact-head ClawSweeper gate for ac6e3a16e87931af600b81a67e56bb67dbcc6603; zero code findings, zero security concerns, sufficient proof; SHA-256 5c8ca30d6f7151e07994e2634f849b72a1d36f87a609edd9ac744f9a0d53ffb0.
  • CI: Exact-head run 34541709954 passed. No unrelated-red exception was needed.
Before After
Models and CLI keys could persist or remove differently. Models and CLI keys share one owner and produce the same saved or removed state.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 11, 2026
Related: openclaw#136257
Supersedes openclaw#142851. Builds on openclaw#144181.

## What Problem This Solves

Fixes an issue where API keys saved on the Models page followed a different persistence path from CLI keys, and CLI logout refused to remove profiles referenced by provider configuration.

## Why This Change Was Made

Models and CLI key operations now share credential selection, persistence, and removal. Removal clears references for the same captured credential plan that the store deletes; concurrent replacements are preserved. Both paths use the Gateway auth-refresh owner and retain recovery guidance after a committed write.

If another client changes the provider binding while the CLI key prompt is open, the saved key does not replace the newer binding. The CLI reports the committed key and tells the user to reopen Models. Internal write controls stay outside the public plugin interface.

Reference-backed profiles cannot be converted to inline keys by replacement. If a concurrent credential generation rejects removal after config cleanup, the remover restores only cleanup-owned config values that no later writer changed.

If removal throws or commits only some owner stores, the removal owner reads the targeted stores again. It restores references only for credentials that still exist and keeps successful deletions removed.

Recovery replays only the captured config delta for targeted survivors. A retained token or external-secret profile keeps its provider binding.

## User Impact

- Edit or remove saved API keys through Models or the CLI with the same stored result.
- Keep model defaults, connection settings, account metadata, credential copy restrictions, tokens, and reference-backed keys intact.
- Explicit CLI profile selection still supports named backups without changing the active connection.
- Agent-local overrides remain intact; a conflicting shared-key replacement reports how to resolve the override.

## Evidence

- Baseline CLI: removing a configured profile failed with the provider-reference refusal.
- Baseline browser: Models reported “Secret saved,” while the key remained inline in provider configuration and the profile store stayed empty.
- Real Gateway/browser and CLI proof: save and removal produce identical credential/configuration state; both refresh auth successfully and preserve the selected model.
- Targeted owner, CLI, Gateway, UI, portability, and plugin-interface tests cover persistence, reference cleanup, concurrent credential replacement, retained credential kinds, explicit backups, administrator scope, and committed-write warnings.
- Independent real-browser acceptance passed UI/CLI state parity, metadata and credential-kind preservation, administrator-scope enforcement, config-write failure recovery, and active-run preservation during targeted removal. Full-provider logout closed the matching real local-provider streams.
- Final rebased candidate: 230 targeted owner, CLI, and Gateway tests passed. The rebuilt Gateway/UI passed the real-browser and CLI save/remove parity test. UI and portability checks passed on the integrated candidate, whose Auth B production files match the final candidate.
- Corrective focused checks: 80 tests passed for the binding race, public plugin boundary, CLI test types, and UI end-to-end inventory. Protocol generation passed.
- Real CLI race proof: a second CLI changed the provider from `fixture:manual` to `fixture:secondary` while key entry waited. The first CLI then preserved `fixture:secondary`, returned the saved-key recovery message, and exited 1.
- Final review-fix checks: 151 owner and Gateway tests passed. They cover configured and default reference-backed profiles plus API-key-only and full-provider removal races that preserve credential, profile metadata, order, and provider binding.
- Final public CLI proof: reference-backed replacement rejected without state change, then logout and save succeeded. A same-ID concurrent replacement completed while logout waited on the config lock; the rejected logout preserved credential and config, then retry and save succeeded.
- Rebased-head checks: 291 focused owner, CLI, Gateway, SDK, and UI-inventory tests plus 50 Models-page tests passed. Protocol generation, full build, the public CLI campaign, and real Models-page UI/CLI parity passed again after the Models login work landed.
- Incomplete-removal checks: 154 owner and Gateway tests passed. They cover thrown store errors, incomplete removal, partial multi-store deletion, surviving-reference restoration, and successful retry.
- Untargeted-binding checks: 155 owner and Gateway tests passed. Failed API-key-only removal preserves the retained token binding, and retry removes only the targeted key.
- Proof limit: the running Gateway's internal refresh exception was not live-injected. Gateway tests cover the failure branches and UI tests cover the resulting warning; remote-target and absent-local-Gateway CLI outcomes were observed separately.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Sep 11, 2026
Related: #144420

## What Problem This Solves

Fixes an issue where removing an API key on Models could delete a replacement another client had just saved. The pending removal returned success even though it removed the newer key. The same Gateway method backs the web control.

## Why This Change Was Made

The shared credential-removal owner now compares the admitted provider bindings with the source snapshot held by the config writer before any cleanup. It rejects changed literals, profile bindings, and secret references, including a new environment reference that resolves to identical bytes. Cleanup uses that same source snapshot and preserves externally managed keys. Unrelated provider edits and aliases without keys do not block removal. The same owner waits for the existing config-application receipt after store work. If application is not confirmed, Gateway and CLI return restart guidance; disabled reload remains disabled.

This corrects the unguarded inline cleanup introduced in #144420 (`09e2b15466e1eddd581248bed0be867a0b248c7e`). Stored-profile generation checks remain in their existing store owner. No schema, migration, config option, or protocol field changes.

## User Impact

A concurrent save wins. For a changed inline binding, removal reports: “The key changed while removing it. Nothing was removed. Reload Models and retry removal.” Ordinary removal still succeeds, and environment-backed keys remain managed by their source. With normal reload, status is current before acknowledgment. With reload disabled, users receive a restart warning.

## Evidence

- Pinned main `3b2dbc82f1bab7d42872413411e8c6fe345eb7ec`: real Gateway `models.authLogout`, held at the config lock, then public CLI `config set` saved B in 1.696 seconds. Readback showed B before removal resumed. Removal then returned success and deleted B (probe exit 1).
- The same real Gateway/CLI probe with the owner fix preserves B and returns the changed-key error. An additional external-process probe exposed and corrected same-value environment-reference replacement.
- Five registered Gateway/CLI cases pass, 40 existing auth cases pass, 17 focused provenance cases pass, and 115 existing status-adapter cases pass. The original three regression cases fail on the original owner and pass on the candidate. Complete private transcripts retain commands, source identities, results, and scheduling controls.

- Independent validation passes all eight runtime clauses (source blindness is self-attested) on `523fdbf7c33a0a3d080827eb7edd47fc33c9e740`: literal/reference races, status refresh/restart, observed reload acknowledgment, keyless alias, and real CLI stored-profile race. Config saves completed in 1.49–1.74 seconds. Subsequent revisions correct test typing and move rollback tests through registered dispatch; production files are identical to that validated head.
- Sixteen sanitized config-corpus fixtures started a real Gateway with fake credentials and no inference. The legacy-roster fixture is rejected before startup on both the pinned base and candidate because its provider API value is the retired `openai` spelling (wrapper exit 1; inner CLI exit 78). On the candidate, the documented `doctor --fix --non-interactive` repair exits 0 and the repaired fixture starts successfully. Original and repaired inputs and full failures are retained. One successful fixture uses the supported Tailscale-off launch override because external publishing is outside the isolated test environment.

- Real web Models page: clicking Remove key during a concurrent CLI save renders the changed-key error; persisted B remains. The browser race save completed in 2.695 seconds. A fresh click with reload disabled deletes the saved key and renders restart guidance. Both sanitized screenshots were visually inspected; fixture processes were stopped after capture.

## Consumers

- `removeModelAuthCredentials` serves registered Gateway `models.authLogout` (`src/gateway/server-methods/models-auth-status.ts`) and CLI `models auth logout` (`src/cli/models-cli.ts`, `src/commands/models/auth-logout.ts`). Models API-key controls and saved-profile controls call that Gateway method (`ui/src/pages/model-providers/config-mutation.ts`, `profile-actions-controller.ts`). Native request types and logout result fields remain unchanged.
- The inline value is `models.providers.*.apiKey`. Writers include registered CLI `config set`, Gateway config mutations, `models.authSetApiKey`, CLI manual-key login, and setup/config writers. All removal decisions run under the common config writer regardless of the replacement writer.
- Stored generation targets remain private to `src/agents/auth-profiles/profiles.ts`; `createAuthProfileRemovalTarget`, `authProfileRemovalTargetMatches`, surviving-profile reads, OAuth locking, peer cleanup, and pre-delete comparison are unchanged. Doctor's `doctor-health-contribution-runners.config.ts` and login/setup callers of `removeProviderAuthProfilesWithLock` (model auth, LM Studio, llama.cpp, and provider-auth SDK adapters) retain their existing paths.
- `resolveProviderConfigSecretInput` gains an optional authoritative source snapshot; omitted arguments retain current behavior. Direct readers: `src/cli/capability-cli/model.account-secrets.provenance.test.ts` (direct resolver test), `doctor-model-catalog-credentials.ts`, `commands/models/list.auth-overview.ts`, `commands/models/auth-api-key.ts`, `agents/runtime-plan/prepare-auth.ts`, `agents/model-auth-availability.ts`, `gateway/server-methods/models-auth-status-api-keys.ts`, and local `getCustomProviderApiKey`, `resolveUsableCustomProviderApiKey`, `resolveProviderEntryApiKeyProfileReference`, `isConfigBackedInlineProviderApiKey`, `hasSecretRefProviderApiKey`, and `resolveRuntimeProviderConfigApiKeyAuth` in `agents/model-auth-provider-config.ts`.
- `resolveProviderEntryApiKeyProfileReference` carries that optional snapshot to the resolver. Existing readers remain unchanged: `commands/models/list.probe.ts`, `commands/models/auth-api-key.ts`, `agents/tools/model-config.helpers.ts`, `plugins/provider-auth-availability-core.ts`, `agents/runtime-plan/prepare-auth.ts`, `agents/model-auth-availability.ts`, `agents/model-auth-provider.ts`, `agents/model-auth-label.ts`, Gateway `models-auth-status-config.ts` and `models-auth-status-api-keys.ts`, its local binding reader, and the `agents/model-auth.ts` barrel. No direct calls in extensions, UI, native apps, or schemas require migration.
- The remover now returns an optional warning; its Gateway and CLI callers consume it. Existing UI API-key and saved-profile controls already display the warning field. `startGatewayWithClient` forwards the existing optional server recovery callback so the integration test uses the full reload lifecycle; callers omitting it are unchanged. No public symbol or field is removed. The authored binding is checked at the final writer and asserted in persisted readback after the Gateway response.

- Existing `startGatewayWithClient` callers (under `src/gateway/`) are `test-helpers.acquisition.test.ts`, `session-delivery-clock-jump.integration.test.ts`, `server.incognito-transcript-reconcile.test.ts`, `test-helpers.server-env.test.ts`, `server.chat-first-turn-binding.test.ts`, `gateway-allowlist-store-read-failure.e2e.test.ts`, `gateway.compaction-hot-reload.e2e.test.ts`, `link-understanding.product.test.ts`, `server.startup-recovery-webchat.test.ts`, `gateway.test.ts`, `server-rpc-restart-owner.test.ts`, `gateway-workshop-learning.e2e.test.ts`, `gateway-agent-skill-refresh.e2e.test.ts`, and `server-methods/{models-auth-refresh.integration,models-auth-refresh.catalog.integration,chat.abort-live-proof,chat.reset-visible-yield}.test.ts`. They omit the optional recovery callback and retain their current behavior. The new removal integration test supplies it.

## Contention

The existing per-config-path queue and cross-process file lock (`src/config/write-lock.ts`) serialize config writers. The added comparison is synchronous and holds no new lock. Credential-store transactions and later OAuth locks remain unchanged; the inline-only case has no OAuth lock keys. Runtime preparation and awaiting the application receipt stay outside config/store locks. The originating Gateway request continuation lets the existing reload owner exclude that request from its own drain. The real external CLI save completes while removal is pending; final clean-commit timing is recorded with the proof.

## Invalidation

The admitted binding map lasts for one request and creates no cache. A rejected removal performs no mutation. Successful replacement writers retain ownership of config reload and credential publication. Successful removal awaits observed config application, or reports unconfirmed application with restart guidance, then retains existing Gateway/CLI auth refresh, shared-store ownership reload, usage-cache clearing, credential snapshot invalidation, and prepared-runtime refresh. Config reload, explicit auth refresh, and restart remain the existing refresh paths; status is checked from settled state in runtime proof.

Startup/refresh scope unification, Telegram, and new-account flows are outside this removal repair. Browser proof covers the existing Models error and restart-guidance consumers.

## Tests

- New `models-auth-removal.integration.test.ts`: registered Gateway `models.authLogout` and registered CLI `config set`, with the real config lock, store, and remover. Covers changed literal, changed secret reference, equal-byte environment reference, unrelated-provider save, preservation of an existing environment-backed alias, and fresh status after hybrid reload. Disabled reload requires a warning. The real recovery callback is supplied and asserted unused.
- `auth-logout.test.ts`: existing command-level cases retain their assertions and receive the config writer's `runtimeConfig` callback context. The incomplete/throw rollback rows now enter registered CLI `models auth logout` through Commander. Partial multi-store removal and API-key-only failure/retry enter the normal Gateway registry through `handleGatewayRequest` for `models.authLogout`. These tests inject store failures and use an in-memory config writer; the real selection, removal, and restoration owners execute. They are registered-dispatch tests, not live database/WebSocket proof. The separate real Gateway suite covers refresh/status.
- `auth-api-key.test.ts`: existing key editing/removal sibling cases retained and run.
- `model-auth.test.ts`: existing provider snapshot and custom-key provenance cases verify unchanged resolver defaults.

- Previous-release state: published `[email protected]` saved the key through its CLI. The candidate Gateway started on that state, removed the key, and reported no key after restart. No state routing or schema changes.

## Deletion ledger

No test or state assertion is deleted or weakened. The config double supplies the real callback context. The formerly helper-only “restores surviving config when store removal…” rows move to registered CLI dispatch; “restores only surviving references after partial multi-store removal” and “preserves an untargeted token binding through failed API-key removal and retry” move to registered Gateway dispatch in the same test file. Partial removal and retry now update the fake store to match the production boundary; Gateway selects the actual API-key profile instead of a hard-coded selection. The existing removal and restoration owners remain unchanged.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 12, 2026
Related: openclaw#144420

## What Problem This Solves

Fixes an issue where removing an API key on Models could delete a replacement another client had just saved. The pending removal returned success even though it removed the newer key. The same Gateway method backs the web control.

## Why This Change Was Made

The shared credential-removal owner now compares the admitted provider bindings with the source snapshot held by the config writer before any cleanup. It rejects changed literals, profile bindings, and secret references, including a new environment reference that resolves to identical bytes. Cleanup uses that same source snapshot and preserves externally managed keys. Unrelated provider edits and aliases without keys do not block removal. The same owner waits for the existing config-application receipt after store work. If application is not confirmed, Gateway and CLI return restart guidance; disabled reload remains disabled.

This corrects the unguarded inline cleanup introduced in openclaw#144420 (`f6c20d2a5acf6b4859d387e5914107d146d78055`). Stored-profile generation checks remain in their existing store owner. No schema, migration, config option, or protocol field changes.

## User Impact

A concurrent save wins. For a changed inline binding, removal reports: “The key changed while removing it. Nothing was removed. Reload Models and retry removal.” Ordinary removal still succeeds, and environment-backed keys remain managed by their source. With normal reload, status is current before acknowledgment. With reload disabled, users receive a restart warning.

## Evidence

- Pinned main `fed8935cfa6e85f9361cd7005421058a9a749a69`: real Gateway `models.authLogout`, held at the config lock, then public CLI `config set` saved B in 1.696 seconds. Readback showed B before removal resumed. Removal then returned success and deleted B (probe exit 1).
- The same real Gateway/CLI probe with the owner fix preserves B and returns the changed-key error. An additional external-process probe exposed and corrected same-value environment-reference replacement.
- Five registered Gateway/CLI cases pass, 40 existing auth cases pass, 17 focused provenance cases pass, and 115 existing status-adapter cases pass. The original three regression cases fail on the original owner and pass on the candidate. Complete private transcripts retain commands, source identities, results, and scheduling controls.

- Independent validation passes all eight runtime clauses (source blindness is self-attested) on `523fdbf7c33a0a3d080827eb7edd47fc33c9e740`: literal/reference races, status refresh/restart, observed reload acknowledgment, keyless alias, and real CLI stored-profile race. Config saves completed in 1.49–1.74 seconds. Subsequent revisions correct test typing and move rollback tests through registered dispatch; production files are identical to that validated head.
- Sixteen sanitized config-corpus fixtures started a real Gateway with fake credentials and no inference. The legacy-roster fixture is rejected before startup on both the pinned base and candidate because its provider API value is the retired `openai` spelling (wrapper exit 1; inner CLI exit 78). On the candidate, the documented `doctor --fix --non-interactive` repair exits 0 and the repaired fixture starts successfully. Original and repaired inputs and full failures are retained. One successful fixture uses the supported Tailscale-off launch override because external publishing is outside the isolated test environment.

- Real web Models page: clicking Remove key during a concurrent CLI save renders the changed-key error; persisted B remains. The browser race save completed in 2.695 seconds. A fresh click with reload disabled deletes the saved key and renders restart guidance. Both sanitized screenshots were visually inspected; fixture processes were stopped after capture.

## Consumers

- `removeModelAuthCredentials` serves registered Gateway `models.authLogout` (`src/gateway/server-methods/models-auth-status.ts`) and CLI `models auth logout` (`src/cli/models-cli.ts`, `src/commands/models/auth-logout.ts`). Models API-key controls and saved-profile controls call that Gateway method (`ui/src/pages/model-providers/config-mutation.ts`, `profile-actions-controller.ts`). Native request types and logout result fields remain unchanged.
- The inline value is `models.providers.*.apiKey`. Writers include registered CLI `config set`, Gateway config mutations, `models.authSetApiKey`, CLI manual-key login, and setup/config writers. All removal decisions run under the common config writer regardless of the replacement writer.
- Stored generation targets remain private to `src/agents/auth-profiles/profiles.ts`; `createAuthProfileRemovalTarget`, `authProfileRemovalTargetMatches`, surviving-profile reads, OAuth locking, peer cleanup, and pre-delete comparison are unchanged. Doctor's `doctor-health-contribution-runners.config.ts` and login/setup callers of `removeProviderAuthProfilesWithLock` (model auth, LM Studio, llama.cpp, and provider-auth SDK adapters) retain their existing paths.
- `resolveProviderConfigSecretInput` gains an optional authoritative source snapshot; omitted arguments retain current behavior. Direct readers: `src/cli/capability-cli/model.account-secrets.provenance.test.ts` (direct resolver test), `doctor-model-catalog-credentials.ts`, `commands/models/list.auth-overview.ts`, `commands/models/auth-api-key.ts`, `agents/runtime-plan/prepare-auth.ts`, `agents/model-auth-availability.ts`, `gateway/server-methods/models-auth-status-api-keys.ts`, and local `getCustomProviderApiKey`, `resolveUsableCustomProviderApiKey`, `resolveProviderEntryApiKeyProfileReference`, `isConfigBackedInlineProviderApiKey`, `hasSecretRefProviderApiKey`, and `resolveRuntimeProviderConfigApiKeyAuth` in `agents/model-auth-provider-config.ts`.
- `resolveProviderEntryApiKeyProfileReference` carries that optional snapshot to the resolver. Existing readers remain unchanged: `commands/models/list.probe.ts`, `commands/models/auth-api-key.ts`, `agents/tools/model-config.helpers.ts`, `plugins/provider-auth-availability-core.ts`, `agents/runtime-plan/prepare-auth.ts`, `agents/model-auth-availability.ts`, `agents/model-auth-provider.ts`, `agents/model-auth-label.ts`, Gateway `models-auth-status-config.ts` and `models-auth-status-api-keys.ts`, its local binding reader, and the `agents/model-auth.ts` barrel. No direct calls in extensions, UI, native apps, or schemas require migration.
- The remover now returns an optional warning; its Gateway and CLI callers consume it. Existing UI API-key and saved-profile controls already display the warning field. `startGatewayWithClient` forwards the existing optional server recovery callback so the integration test uses the full reload lifecycle; callers omitting it are unchanged. No public symbol or field is removed. The authored binding is checked at the final writer and asserted in persisted readback after the Gateway response.

- Existing `startGatewayWithClient` callers (under `src/gateway/`) are `test-helpers.acquisition.test.ts`, `session-delivery-clock-jump.integration.test.ts`, `server.incognito-transcript-reconcile.test.ts`, `test-helpers.server-env.test.ts`, `server.chat-first-turn-binding.test.ts`, `gateway-allowlist-store-read-failure.e2e.test.ts`, `gateway.compaction-hot-reload.e2e.test.ts`, `link-understanding.product.test.ts`, `server.startup-recovery-webchat.test.ts`, `gateway.test.ts`, `server-rpc-restart-owner.test.ts`, `gateway-workshop-learning.e2e.test.ts`, `gateway-agent-skill-refresh.e2e.test.ts`, and `server-methods/{models-auth-refresh.integration,models-auth-refresh.catalog.integration,chat.abort-live-proof,chat.reset-visible-yield}.test.ts`. They omit the optional recovery callback and retain their current behavior. The new removal integration test supplies it.

## Contention

The existing per-config-path queue and cross-process file lock (`src/config/write-lock.ts`) serialize config writers. The added comparison is synchronous and holds no new lock. Credential-store transactions and later OAuth locks remain unchanged; the inline-only case has no OAuth lock keys. Runtime preparation and awaiting the application receipt stay outside config/store locks. The originating Gateway request continuation lets the existing reload owner exclude that request from its own drain. The real external CLI save completes while removal is pending; final clean-commit timing is recorded with the proof.

## Invalidation

The admitted binding map lasts for one request and creates no cache. A rejected removal performs no mutation. Successful replacement writers retain ownership of config reload and credential publication. Successful removal awaits observed config application, or reports unconfirmed application with restart guidance, then retains existing Gateway/CLI auth refresh, shared-store ownership reload, usage-cache clearing, credential snapshot invalidation, and prepared-runtime refresh. Config reload, explicit auth refresh, and restart remain the existing refresh paths; status is checked from settled state in runtime proof.

Startup/refresh scope unification, Telegram, and new-account flows are outside this removal repair. Browser proof covers the existing Models error and restart-guidance consumers.

## Tests

- New `models-auth-removal.integration.test.ts`: registered Gateway `models.authLogout` and registered CLI `config set`, with the real config lock, store, and remover. Covers changed literal, changed secret reference, equal-byte environment reference, unrelated-provider save, preservation of an existing environment-backed alias, and fresh status after hybrid reload. Disabled reload requires a warning. The real recovery callback is supplied and asserted unused.
- `auth-logout.test.ts`: existing command-level cases retain their assertions and receive the config writer's `runtimeConfig` callback context. The incomplete/throw rollback rows now enter registered CLI `models auth logout` through Commander. Partial multi-store removal and API-key-only failure/retry enter the normal Gateway registry through `handleGatewayRequest` for `models.authLogout`. These tests inject store failures and use an in-memory config writer; the real selection, removal, and restoration owners execute. They are registered-dispatch tests, not live database/WebSocket proof. The separate real Gateway suite covers refresh/status.
- `auth-api-key.test.ts`: existing key editing/removal sibling cases retained and run.
- `model-auth.test.ts`: existing provider snapshot and custom-key provenance cases verify unchanged resolver defaults.

- Previous-release state: published `[email protected]` saved the key through its CLI. The candidate Gateway started on that state, removed the key, and reported no key after restart. No state routing or schema changes.

## Deletion ledger

No test or state assertion is deleted or weakened. The config double supplies the real callback context. The formerly helper-only “restores surviving config when store removal…” rows move to registered CLI dispatch; “restores only surviving references after partial multi-store removal” and “preserves an untargeted token binding through failed API-key removal and retry” move to registered Gateway dispatch in the same test file. Partial removal and retry now update the fake store to match the production boundary; Gateway selects the actual API-key profile instead of a hard-coded selection. The existing removal and restoration owners remain unchanged.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 10, 2026
## What Problem This Solves

Fixes model discovery after an API key is saved in Models or with `models auth paste-api-key`: discovery could send the saved profile ID as the bearer token instead of the key.

## User Impact

API-key sign-in can immediately populate the provider's model catalog without a Gateway restart or manual refresh. Existing literal keys, SecretRefs, and saved profile bindings keep their formats; no migration or re-entry of credentials is required.

## Why This Change Was Made

Profile IDs in provider `apiKey` fields are intentional references, supported by runtime authentication since [f7a1d3f](f7a1d3f) and written by the shared UI/CLI credential owner in #144420. Discovery bypassed that reference classification. Both discovery callbacks now use the existing profile-binding classifier, preserving provider/base-URL compatibility, credential eligibility, inactive-setup isolation, environment precedence, and literal-key behavior.

No overlap with Pash/Sarah changes.

## Evidence

- The pinned-main negative control ran the same registered subprocess regression and failed: discovery sent the saved profile identifier instead of the key, and the vLLM endpoint returned HTTP 401.
- 56 focused auth-provenance and catalog-order tests passed, including pinned profiles, incompatible profile configuration, expired/inactive credentials, literal values, SecretRefs, and environment precedence. Scoped lint, formatting, and the diff whitespace check passed.
- A registered subprocess regression passed through the real Gateway `models.authSetApiKey` RPC, saved profile-ID binding, passive catalog reads, and authenticated vLLM/SGLang HTTP stubs.
- Live API-key sign-in on isolated vLLM, SGLang, and OpenRouter Gateways each exposed all three stub models on passive `models.list` polls approximately 2 seconds after sign-in acknowledgment, without refresh or restart. Each provider's discovery and real chat requests carried the correct bearer key.
- OpenRouter retained its native-host ownership check: a configured local CONNECT proxy and temporary TLS trust routed its allowed hostname to the isolated stub. No provider manifest or host-security policy was changed.
- [Additional real Gateway-to-HTTP proof](#168617 (comment)): an incompatible provider binding sent no HTTP request; logout during a held discovery prevented subsequent use of the old secret; replacement discovery used only the new key, and the delayed old result was absent from the settled catalog. The linked proof includes sanitized output, the existing generation invalidation/publication chain, and the limit that already-sent HTTP bytes cannot be recalled.

Merge risk: two-way door; reverting restores the previous reader behavior without changing stored state. Blast radius is provider discovery/catalog credential selection; the credential writer and chat authentication owner are unchanged.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
## What Problem This Solves

Fixes model discovery after an API key is saved in Models or with `models auth paste-api-key`: discovery could send the saved profile ID as the bearer token instead of the key.

## User Impact

API-key sign-in can immediately populate the provider's model catalog without a Gateway restart or manual refresh. Existing literal keys, SecretRefs, and saved profile bindings keep their formats; no migration or re-entry of credentials is required.

## Why This Change Was Made

Profile IDs in provider `apiKey` fields are intentional references, supported by runtime authentication since [93e9e79](openclaw@93e9e79) and written by the shared UI/CLI credential owner in openclaw#144420. Discovery bypassed that reference classification. Both discovery callbacks now use the existing profile-binding classifier, preserving provider/base-URL compatibility, credential eligibility, inactive-setup isolation, environment precedence, and literal-key behavior.

No overlap with Pash/Sarah changes.

## Evidence

- The pinned-main negative control ran the same registered subprocess regression and failed: discovery sent the saved profile identifier instead of the key, and the vLLM endpoint returned HTTP 401.
- 56 focused auth-provenance and catalog-order tests passed, including pinned profiles, incompatible profile configuration, expired/inactive credentials, literal values, SecretRefs, and environment precedence. Scoped lint, formatting, and the diff whitespace check passed.
- A registered subprocess regression passed through the real Gateway `models.authSetApiKey` RPC, saved profile-ID binding, passive catalog reads, and authenticated vLLM/SGLang HTTP stubs.
- Live API-key sign-in on isolated vLLM, SGLang, and OpenRouter Gateways each exposed all three stub models on passive `models.list` polls approximately 2 seconds after sign-in acknowledgment, without refresh or restart. Each provider's discovery and real chat requests carried the correct bearer key.
- OpenRouter retained its native-host ownership check: a configured local CONNECT proxy and temporary TLS trust routed its allowed hostname to the isolated stub. No provider manifest or host-security policy was changed.
- [Additional real Gateway-to-HTTP proof](openclaw#168617 (comment)): an incompatible provider binding sent no HTTP request; logout during a held discovery prevented subsequent use of the old secret; replacement discovery used only the new key, and the delayed old result was absent from the settled catalog. The linked proof includes sanitized output, the existing generation invalidation/publication chain, and the limit that already-sent HTTP bytes cannot be recalled.

Merge risk: two-way door; reverting restores the previous reader behavior without changing stored state. Blast radius is provider discovery/catalog credential selection; the credential writer and chat authentication owner are unchanged.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 12, 2026
…9528)

Related: #151354. Carries forward the saved-profile repair from #160452, which conflicts with current main.

## What Problem This Solves

Fixes: after a provider key hits a rate limit, saving a replacement in Settings → Models reports success but the next request is still blocked by the old key's cooldown.

## User Impact

User impact: operators can use a replacement API key immediately without restarting the Gateway or waiting for the old key's cooldown. Other accounts, profile order, and usage history stay unchanged.

## Why This Change Was Made

Clear only the replaced profile's failure state in the same locked credential write. Models and `models auth paste-api-key` already share this writer; generic writes remain health-preserving unless explicitly asked to reset.

Why it was this way: #124014 deliberately restricted failure-state resets to successful credential replacement rather than clearing every account before login; #144420 later shared manual key editing through the generic writer without opting into that reset. This applies the existing scoped-reset contract to manual keys while keeping its sibling-account and usage-history protections.

No overlap with Pash/Sarah changes.

## Evidence

Built isolated Gateways with a loopback OpenAI-compatible stub and dummy keys. Both runs use the actual Models page's **Set API key** action, then the already-connected Gateway transport for the next agent request:

| Step | Current main (`cbba7e2e2ef4`) | This change (`6dfd10508f8a`) |
| --- | --- | --- |
| Save key A; request returns HTTP 429 | Rate-limit failure and persisted cooldown | Same |
| Save key B in Models | “Secret saved.” | “Secret saved.” |
| Immediately request again | `Auth profile "rotation:manual" is temporarily unavailable`; zero provider calls | Stub receives key B and replies “Key B works immediately after rotation.” |

The screenshots show the saved-key state. The request results above come from Gateway responses and the stub's recorded requests, not from an inferred screenshot result.

| Before | After |
| --- | --- |
| ![Before: replacement saved but model remains unavailable](https://github.com/user-attachments/assets/59947379-f7ee-497c-9d5f-8b7e11212895) | ![After: replacement saved and model is available](https://github.com/user-attachments/assets/e4ec28d3-222e-4881-8fe2-27e99ccf617e) |

- Extended the existing configured/explicit/ordered key-replacement regression: all three cases fail on main because the old cooldown and failure count survive; all pass with the fix. It also preserves a sibling's failure state and the replaced profile's `lastUsed`.
- Focused command, locked SQLite writer, and Gateway auth suites: **152 tests passed across four files**. Formatting and `git diff --check` passed.
- Final bounded Codex review found no actionable defects.

Scope: saved API-key replacement only. The second issue report about stale stored credentials taking precedence over a directly edited config key remains separate; this does not change credential precedence, doctor migration, or logging.

Merge danger: two-way door for future saves; reverting restores the old save behavior, but cannot reconstruct cooldown counters already cleared. Blast radius is the one saved API-key profile explicitly replaced through Models or the shared CLI writer. No schema, permission, storage-location, or credential-disclosure changes.

Co-authored-by: Masato Hoshino <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa pushed a commit that referenced this pull request Oct 12, 2026
## What Problem This Solves

Fixes model discovery after an API key is saved in Models or with `models auth paste-api-key`: discovery could send the saved profile ID as the bearer token instead of the key.

## User Impact

API-key sign-in can immediately populate the provider's model catalog without a Gateway restart or manual refresh. Existing literal keys, SecretRefs, and saved profile bindings keep their formats; no migration or re-entry of credentials is required.

## Why This Change Was Made

Profile IDs in provider `apiKey` fields are intentional references, supported by runtime authentication since [f7a1d3f](f7a1d3f) and written by the shared UI/CLI credential owner in #144420. Discovery bypassed that reference classification. Both discovery callbacks now use the existing profile-binding classifier, preserving provider/base-URL compatibility, credential eligibility, inactive-setup isolation, environment precedence, and literal-key behavior.

No overlap with Pash/Sarah changes.

## Evidence

- The pinned-main negative control ran the same registered subprocess regression and failed: discovery sent the saved profile identifier instead of the key, and the vLLM endpoint returned HTTP 401.
- 56 focused auth-provenance and catalog-order tests passed, including pinned profiles, incompatible profile configuration, expired/inactive credentials, literal values, SecretRefs, and environment precedence. Scoped lint, formatting, and the diff whitespace check passed.
- A registered subprocess regression passed through the real Gateway `models.authSetApiKey` RPC, saved profile-ID binding, passive catalog reads, and authenticated vLLM/SGLang HTTP stubs.
- Live API-key sign-in on isolated vLLM, SGLang, and OpenRouter Gateways each exposed all three stub models on passive `models.list` polls approximately 2 seconds after sign-in acknowledgment, without refresh or restart. Each provider's discovery and real chat requests carried the correct bearer key.
- OpenRouter retained its native-host ownership check: a configured local CONNECT proxy and temporary TLS trust routed its allowed hostname to the isolated stub. No provider manifest or host-security policy was changed.
- [Additional real Gateway-to-HTTP proof](#168617 (comment)): an incompatible provider binding sent no HTTP request; logout during a held discovery prevented subsequent use of the old secret; replacement discovery used only the new key, and the delayed old result was absent from the settled catalog. The linked proof includes sanitized output, the existing generation invalidation/publication chain, and the limit that already-sent HTTP bytes cannot be recalled.

Merge risk: two-way door; reverting restores the previous reader behavior without changing stored state. Blast radius is provider discovery/catalog credential selection; the credential writer and chat authentication owner are unchanged.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 31c8052)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…nclaw#169528)

Related: openclaw#151354. Carries forward the saved-profile repair from openclaw#160452, which conflicts with current main.

## What Problem This Solves

Fixes: after a provider key hits a rate limit, saving a replacement in Settings → Models reports success but the next request is still blocked by the old key's cooldown.

## User Impact

User impact: operators can use a replacement API key immediately without restarting the Gateway or waiting for the old key's cooldown. Other accounts, profile order, and usage history stay unchanged.

## Why This Change Was Made

Clear only the replaced profile's failure state in the same locked credential write. Models and `models auth paste-api-key` already share this writer; generic writes remain health-preserving unless explicitly asked to reset.

Why it was this way: openclaw#124014 deliberately restricted failure-state resets to successful credential replacement rather than clearing every account before login; openclaw#144420 later shared manual key editing through the generic writer without opting into that reset. This applies the existing scoped-reset contract to manual keys while keeping its sibling-account and usage-history protections.

No overlap with Pash/Sarah changes.

## Evidence

Built isolated Gateways with a loopback OpenAI-compatible stub and dummy keys. Both runs use the actual Models page's **Set API key** action, then the already-connected Gateway transport for the next agent request:

| Step | Current main (`b372edb6424e`) | This change (`6dfd10508f8a`) |
| --- | --- | --- |
| Save key A; request returns HTTP 429 | Rate-limit failure and persisted cooldown | Same |
| Save key B in Models | “Secret saved.” | “Secret saved.” |
| Immediately request again | `Auth profile "rotation:manual" is temporarily unavailable`; zero provider calls | Stub receives key B and replies “Key B works immediately after rotation.” |

The screenshots show the saved-key state. The request results above come from Gateway responses and the stub's recorded requests, not from an inferred screenshot result.

| Before | After |
| --- | --- |
| ![Before: replacement saved but model remains unavailable](https://github.com/user-attachments/assets/59947379-f7ee-497c-9d5f-8b7e11212895) | ![After: replacement saved and model is available](https://github.com/user-attachments/assets/e4ec28d3-222e-4881-8fe2-27e99ccf617e) |

- Extended the existing configured/explicit/ordered key-replacement regression: all three cases fail on main because the old cooldown and failure count survive; all pass with the fix. It also preserves a sibling's failure state and the replaced profile's `lastUsed`.
- Focused command, locked SQLite writer, and Gateway auth suites: **152 tests passed across four files**. Formatting and `git diff --check` passed.
- Final bounded Codex review found no actionable defects.

Scope: saved API-key replacement only. The second issue report about stale stored credentials taking precedence over a directly edited config key remains separate; this does not change credential precedence, doctor migration, or logging.

Merge danger: two-way door for future saves; reverting restores the old save behavior, but cannot reconstruct cooldown counters already cleared. Blast radius is the one saved API-key profile explicitly replaced through Models or the shared CLI writer. No schema, permission, storage-location, or credential-disclosure changes.

Co-authored-by: Masato Hoshino <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: android App: android app: web-ui App: web-ui commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant