Repository navigation
fix(models): share API-key editing and removal - #144420
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. Reviewed September 10, 2026, 7:28 PM ET / 23:28 UTC (Revision 7). ClawSweeper reviewWhat this changesMakes Models settings and CLI commands share API-key selection, storage, removal, and refresh reporting while preserving unrelated credentials and settings. Regression provenancePossible 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 Review scores
Verification
How this fits togetherModels 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]
Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +529, Tests +1272, Docs 0, Config +1, Other +5. Total +1807 across 39 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest 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:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 0434aa633824. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (6 earlier review cycles)
|
|
landpr-approve-admin-merge |
9127075 to
6b8f7d0
Compare
|
landpr-approve-admin-merge |
6b8f7d0 to
70dbdc4
Compare
|
landpr-approve-admin-merge |
70dbdc4 to
8550616
Compare
|
landpr-approve-admin-merge |
8550616 to
dfaf4e4
Compare
|
landpr-approve-admin-merge |
dfaf4e4 to
7c55efc
Compare
|
landpr-approve-admin-merge |
|
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.
|
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]>
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]>
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]>
## 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]>
## 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]>
…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 | | --- | --- | |  |  | - 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]>
## 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)
…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 | | --- | --- | |  |  | - 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]>
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.