Repository navigation
fix: preserve model login settings and refresh gateway auth - #144181
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: needs maintainer review before merge. Reviewed September 10, 2026, 4:28 PM ET / 20:28 UTC (Revision 8). ClawSweeper reviewWhat this changesPreserve existing and concurrently edited settings during provider login, and make auth changes wait for Gateway publication with guarded support for older Gateways. Merge readiness✅ Ready for maintainer review This remains useful work that current main does not replace. The prior logout blocker is resolved, the recorded proof covers the relevant auth boundaries, and no new blocking defect was found. Priority: P2 Review scores
Verification
How this fits togetherProvider login writes credentials and configuration used by OpenClaw’s agents. The Gateway publishes prepared authentication state so subsequent model requests see those changes. flowchart LR
A[Provider login or auth change] --> B[Credential store]
A --> C[Conflict-aware settings update]
B --> D[Administrator refresh request]
C --> D
D --> E[Prepared auth publication]
E --> F[Agent model requests]
D --> G[Older Gateway fallback and guidance]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +203, Tests +509, Docs +2, Other +19. Total +733 across 31 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep credential persistence and conflict-aware config updates with their existing owners, and use one acknowledged Gateway publication path for auth mutations. Do we have a high-confidence way to reproduce the issue? Yes: the registered provider-login path and concurrent-config fixtures expose the source-level failure, supported by the recorded baseline CLI run; this review did not execute a fresh reproduction. Is this the best way to solve the issue? Yes: the patch reuses the config writer and prepared-runtime publication owner, preserves defaults, and confines older-Gateway fallback to a precise compatibility response. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 5d3cc203b67d. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (7 earlier review cycles)
|
e4239c1 to
e3a5458
Compare
e3a5458 to
735f661
Compare
Yigtwxx
left a comment
There was a problem hiding this comment.
Reviewed this revision (735f661) independently against origin/main — I read the changed paths and their callers rather than re-running the CLI evidence in the body. Four notes, the first one a compatibility question I would want answered before this lands.
1. refreshRunningGatewayAuthState loses its cross-version path
src/commands/models/auth-refresh.ts switches the CLI from models.authStatus { refresh: true } to the new models.authRefresh. The descriptor table shows what that costs:
- main:
["models.authStatus", "models-auth-status", "operator.read", "<=2026.7"] - here:
["models.authRefresh", "models-auth-status", "operator.admin", "2026.9", CONTROL_PLANE_WRITE]
The body notes the protocol artifacts are regenerated "without a protocol version bump", so a client cannot separate the two by version either. When the CLI is newer than the running Gateway — the ordinary state right after openclaw update and before a Gateway restart, and the normal case for a remote/SSH-tunnelled Gateway — the request comes back as unknown method: models.authRefresh, errorShape(ErrorCodes.INVALID_REQUEST, ...) at src/gateway/server-methods.ts:522. Neither catch arm in refreshRunningGatewayAuthState matches it (it is a client request error, not GatewayLocalBackendSharedAuthUnavailableError, and not a transport closed/ECONNREFUSED), so every models auth login, logout, paste-token, paste-api-key and order against such a Gateway ends in Warning: Model auth changes were saved, but the running Gateway could not refresh them. Run openclaw gateway restart and the live Gateway is never refreshed. On main that same call worked against any Gateway back to <=2026.7.
The repo already has the idiom for this: canFallbackToImplicitLocalGateway treats an INVALID_REQUEST whose message is unknown method: <legacyMethod> as a legacy-server signal (src/cli/gateway-rpc.ts:103), and the same shape appears at src/commands/audit.ts:152, src/cli/cron-cli/list-jobs.ts:31, src/agents/tools/sessions-resolution.ts:108 and src/node-host/connection.ts:40. models.authStatus { refresh: true } still refreshes on this branch (refreshModelAuthStatusRuntimeState is untouched), so one retry on that specific error would preserve the old behaviour for older Gateways while new ones keep the acknowledged path.
Worth noting the required scope also narrows from operator.read to operator.admin, so a read-scoped operator token that used to get a refresh now gets the restart warning instead.
2. "Concurrent unrelated settings survive sign-in" holds for object keys, not array keys
persistProviderAuthResult now derives createMergePatch(params.config, applyProviderAuthConfigPatch(params.config, ...)) and replays it with applyMergePatch(next, configPatch). That call passes no options, so mergeObjectArraysById is off and plain RFC-7396 array semantics apply: any array-valued key the derived patch touches is replaced wholesale with the value computed from the pre-login snapshot. For a user on an array-shaped roster — agents.list, which applyProviderAuthConfigPatch can rewrite through the roster?.kind === "list" branch in src/plugins/provider-auth-choice-helpers.ts — an entry added during a long OAuth is still dropped, exactly as it was by the old whole-config write.
The repo's own config writer opts in for this reason: src/gateway/server-methods/config.ts:1056 passes mergeObjectArraysById: true. Either passing that option here, or narrowing the guarantee in the body to object-valued settings, would make the claim match the code.
3. models.authOrderSet quietly changes how it locates the owner, and when it responds
main called prepareModelRuntimeSnapshot({ agentId, agentDir: preparedSnapshot.agentDir, workspaceDir: preparedSnapshot.workspaceDir, config: preparedSnapshot.config }). The shared refreshModelAuthStateAfterMutation passes no workspaceDir and takes config from context.getRuntimeConfig(). ownerKey includes workspaceDir, so with it undefined the exact key no longer matches a configured owner published with a workspace, and resolution falls through to the configured-workspace fallback in resolvePublishedOwner, which returns a candidate only when exactly one matches (src/agents/prepared-model-runtime.owner.ts:295-331, selected by projectPublishedModelRuntimeOwner, src/agents/prepared-model-runtime.published-owner.ts:49-54). That is likely fine for the single-configured-owner case, but it is a silent change in owner lookup that the body does not mention; if it is deliberate, a line of comment would help the next reader.
Separately, the handler now awaits refreshActiveProviderAuthRuntimeSnapshot() inside the helper before respond, where main ran it fire-and-forget after responding. authOrderSet latency now includes a full runtime auth snapshot refresh.
4. Follow-up (not blocking this PR): the Gateway setup path still has both defects this PR fixes
openclaw.setup.prepare.start does what the CLI used to do: readSetupConfigFileSnapshot() at src/gateway/server-methods/system-agent.ts:260, then a provider login that can run for minutes, then persistAuthProfiles() at :300, then writeWizardConfigFile(prepared.config, { baseSnapshot, baseHash }) at :301. That call passes no mergeBase, and writeWizardConfigFile replays a delta only when mergeBase is set — otherwise transform: (current) => ({ nextConfig: config }) (src/wizard/setup.shared.ts:112-115), a whole-file write built from the pre-login snapshot.
The baseHash/baseSnapshot CAS with maxAttempts: 1 (setup.shared.ts:102) turns the overwrite into a hard failure rather than silent data loss, but the user-visible result is the second defect from your own body: the credential is already persisted, and the caller surfaces a raw config changed since last load conflict with no equivalent of your Credentials saved, but provider settings could not be applied. Passing mergeBase: baseConfig there is what the other wizard writers already do (src/commands/configure.wizard.ts:645, src/wizard/setup.ts:94).
Checked and clean
To save the next reader the walk: src/gateway/model-account-connect.ts applies no config patch at all (the comment above connectUserModelAccount is accurate), and both the src/flows/model-picker.ts wizard chain and the src/system-agent/setup-inference-plan.ts chain persist through merge patches applied to a freshly-read config under the mutation lock — the latter even conflict-checks with mergePatchConflicts (src/system-agent/setup-inference-persist.ts:196). Item 4 is the one remaining caller with the old shape.
|
Applied the final review decisions in
All 396 current-owner targeted tests pass after the required rebase. Main’s removal of the retired setup owner is preserved. Eight final CLI scenarios pass; older-Gateway login/order/logout compatibility and its guard controls also pass. |
117f47d to
2215907
Compare
|
landpr-approve-admin-merge |
|
Owner-approved admin merge completed at
Known limits remain disclosed in the PR body: shared-main removal locking and the unsuccessful targeted-profile fault attempt. Shared login results and chat presentation follow separately. Exact-head review artifact (privacy-filtered){
"engine": "clawsweeper-local-review",
"version": 4,
"head": "2215907e8c28dc4f8e121141a93e85d9e468cf23",
"status": "complete",
"correctness": "patch is correct",
"findings": [],
"security": {
"status": "cleared",
"summary": "Administrator admission, local-state matching, credential isolation, and logout cancellation remain intact; no introduced security or supply-chain defect was found.",
"concerns": []
},
"proof": {
"status": "sufficient",
"summary": "Retained compiled CLI and Gateway proof exercises settings preservation, acknowledged auth publication, read-only denial, guarded legacy fallback, and provider-request cancellation despite publication failure. Build identities remain f6044cbd and 117f47d4; the latest absent-parent correction adds focused failing-before/passing-after coverage on the same traced CLI writer path.",
"evidenceKind": "logs",
"needsContributorAction": false
},
"rating": {
"proofTier": "A",
"patchTier": "B",
"overallTier": "B",
"summary": "A useful owner-level repair with strong product evidence, explicit coverage limits, and no remaining blocking finding.",
"nextSteps": []
},
"ownerReviewApproval": "https://github.com/openclaw/openclaw/pull/144181#issuecomment-5624900359",
"retainedGateSha256": "33e43d771479bd2b08eef255c8c010a3ea870e14a16ee11a8183ba067ef2157a"
} |
Related: #136257 Follows: #144181 ## What Problem This Solves Users running `/login codex` in private chat could receive “login complete” after credentials were saved even when the Gateway rejected the auth refresh or could not be reached. A failed provider-settings write after credential storage instead appeared as an ordinary login failure. ## Why This Change Was Made The login owner now carries its existing refresh outcome through fresh and imported login results. A lightweight typed error preserves the saved-credential fact when applying provider settings fails, including the original CLI message and cause. The existing shared login runtime validates the result and owns completion and failure wording for generic chat and native Telegram. Both callers retain their admission, cancellation, device-code delivery, session-adoption and terminal-delivery owners. A failed session switch remains visible alongside a failed refresh. ## User Impact - Successful refresh keeps the existing retry guidance. - Rejected or unreachable refresh says credentials were saved and gives recovery guidance. - A failed provider-settings write is distinguished from a failure before credentials were saved. - This adds no configuration key, protocol change, permission change, provider menu or live OAuth behavior. ## Evidence - Baseline `54c3655e`: five producer regressions and two refresh-presentation cases in each chat surface fail before the fix. - 106 focused tests pass: producer 55, generic chat 26, native Telegram 22, owner pairing callback 1, shipped CLI integration 2. The final rebase preserves the contribution; the callback and CLI cases also pass on `b6f7b82836dc`. - Formatting, focused lint, assertion and size ratchets, normal commit hooks, the final build and built Telegram startup check pass on Testbox. - Real Telegram Test Server baseline: `/login codex` receives an actual rejected refresh, then incorrectly says “login complete.” Five independent real-Telegram recordings pass on the final built head, each with ordered before/after credential readback, zero inference, and verified cleanup: | Outcome | Observed result | Sent message ID | | --- | --- | --- | | Refresh acknowledged | Completion follows the actual Gateway acknowledgment; credential remains saved. | 13852737536 | | Refresh rejected | Saved-credential notice and recovery guidance follow the actual rejection. | 13856931840 | | Gateway unreachable | Saved-credential notice explains the missing Gateway application. | 13861126144 | | Provider settings rejected | Credential remains saved; invalid settings are rejected; the reply preserves both facts. | 13865320448 | | Failure before save | Ordinary failure reply; credential store remains empty. | 13869514752 | The channel fixture uses a synthetic provider credential through the normal login producer and the real native Telegram command. It does not claim live vendor OAuth or inference. Full event files retain sent message IDs, timestamps and ordering; identity and private-path redactions are recorded with hashes. Earlier heartbeat-contaminated and unordered-snapshot recordings remain disclosed as failed or limited evidence. Co-authored-by: Ayaan Zaidi <[email protected]>
## Problem Models sign-in also runs model setup, which can activate a provider's starter model. Bare `/login` starts OpenAI device authentication before the user chooses a provider. ## Solution Add credential-only provider login in Models and one shared provider menu for chat. Plugins declare optional login choices in their manifests. Core resolves provider and method choices and produces existing command buttons or copyable commands. Bare `/login` always asks for a provider, even when only one is available. API-key and local setup methods remain available through explicit provider commands. `/login codex` retains its device-code flow. The credential-only flow uses the shared persistence and auth-refresh owner from merged #144181. It preserves the selected model, restrictions, concurrent settings and existing account pins. Models publishes the saved credential through the current Gateway context. Cancellation locks at the real persistent-effect boundary; confirmed saves remain visible through later errors. Caller authority is checked at credential and session commits, and disconnected clients cannot finish pending login. Qualified choices reject stale or ambiguous plugin owners. Leaving Models closes its wizard input through the existing close operation and waits for admission to settle. This uses optional `closeInput` on `wizard.cancel`; ordinary cancellation still refuses to interrupt a protected save. Separate pending requests keep page disposal independent of an outstanding Cancel response. The final conflict resolution also preserves the shared refresh outcomes from merged #144436: rejected or unreachable refresh reports saved credentials with recovery guidance. One shared error module carries saved-credential and settings-write failure facts, and the provider-neutral runtime owns completion/failure wording for both chat paths. Channels render core-owned command actions. Provider-neutral recovery replaces the old OpenAI-specific recovery path. OpenAI, MiniMax and xAI declare their supported credential-only choices; methods requiring starter discovery retain setup. ## Impact - No new configuration keys or database schema. - Optional metadata preserves setup for plugins that omit it. - Connecting a provider does not activate its default model. - Chat selection rechecks current owner permission and availability. ## Evidence Original baseline: `d35cefd9b7013e2a2fced8cf16b631a6ee476d45`. Integrated base after #144181: `7d2296e3339d1a9689ee020b102ba7c9a765e229`. The later required conflict resolution integrates #144436 at `39b671dc74158f088adde3b4415de4547a0c902b`. - Real Telegram Test Server baseline: bare `/login` issued a device code before selection. Candidate: provider buttons, second method menu, synthetic device code, saved result and rejection of a stale qualified selection. Telegram transport and user actions are real; provider credentials are synthetic. - Real Gateway baseline: `models.authLogin` was unknown. Candidate: saved fixture credential with the same default model and restrictions. - Independent public-client checks cover singleton webchat selection, wrong-connection denial, unavailable choices, disconnect rejection and positive connected-owner completion. An existing CLI setup flow with omitted metadata still saves credentials and honors explicit `--set-default`. - Integrated public-client cancellation proof: cancelling before save leaves no credential; cancelling after profile visibility while a provider note is pending returns running, and acknowledging the note produces the saved terminal result. A public settings edit during login survives; the saved profile appears without restarting the Gateway. - Browser captures show Connect, explicit provider selection, the sign-in URL/code and saved result with the selected model unchanged. Captures were inspected. - Current integrated focused Vitest: 243 passing tests across the auth producer and choice resolution, shared login runtime, core chat, native Telegram, Gateway wizard ownership, Models UI and the CLI sibling. Earlier retained checks cover method ordering, setup, MiniMax/xAI and provider recovery. The Telegram fixture cleanup preserves all test names, parameter rows and assertions; its 25 cases pass after cleanup. - Page-disposal regression: the original Gateway kept waiting after a saved note, and the original Models page left the wizard unsettled on removal. The correction passes 33 Gateway and 49 UI tests, including disposal during a pending Cancel and a second login on the same connection. Fresh real-Gateway proof rejects a peer disposal, preserves the saved credential, returns truthful closure status, and immediately admits the same owner’s next login. - Focused lint, assertion safety, runtime build and whitespace checks pass. Full typechecking and full CI run on GitHub. This extracts Auth C+E from #136257 and replaces closed #142943. Auth A was merged before integration; its implementation was not copied into this branch. ## Deletion and rewrite ledger `src/auto-reply/codex-login-recovery.ts` moved to `src/auto-reply/provider-login-recovery.ts`. Its `buildCodexLoginRecovery`, `CodexLoginRecoveryEvidence`, and `CodexLoginRecovery` symbols moved to `buildProviderLoginRecovery` (`:23`), `ProviderLoginRecoveryEvidence` (`:5`), and `ProviderLoginRecovery` (`:11`). The fixed OpenAI/Codex recovery action is replaced by the shared provider menu. No recovery test definition was deleted; the nine renamed or parameterized definitions are mapped below against head `73cfa4b319b9640a6711b2dc8e871d9ff4aea035`. | Removed test name | Disposition | New test name and location | | --- | --- | --- | | `adds Codex login recovery to raw forwarded refresh failures` | **behavior moved** | `adds provider login recovery to raw forwarded refresh failures` — `src/auto-reply/reply/agent-runner-execution-auth-failures.test.ts:51` | | `keeps Codex login recovery actionable on Control UI turns` | **behavior moved** | `keeps provider login recovery actionable on Control UI turns` — `src/auto-reply/reply/agent-runner-execution-auth-failures.test.ts:72` | | `preserves Codex login recovery in known failure payloads` | **behavior moved** | `preserves provider login recovery in known failure payloads` — `src/auto-reply/reply/agent-runner-execution-auth-failures.test.ts:118` | | `keeps disabled OpenAI OAuth profiles actionable on later turns` | **behavior moved**; original OpenAI row retained, xAI and MiniMax rows added | `keeps disabled %s OAuth profiles actionable on later turns` — `src/auto-reply/reply/agent-runner-execution-auth-failures.test.ts:228` | | `does not offer Codex login for $label` | **behavior moved**; API-key and transient OAuth negative rows retained, provider-name-only negative row added | `does not offer provider login for $label` — `src/auto-reply/reply/agent-runner-execution-auth-failures.test.ts:277` | | `keeps non-OpenAI OAuth refresh failures on provider-specific terminal guidance` | **behavior moved and expanded**; terminal guidance retained, shared login action added | `adds provider login while retaining non-OpenAI terminal guidance` — `src/auto-reply/reply/agent-runner-execution-auth-failures.test.ts:289` | | `turns returned OpenAI refresh failures into Codex login recovery` | **behavior moved**; original OpenAI row retained, xAI and MiniMax rows added | `turns returned %s refresh failures into provider login recovery` — `src/agents/embedded-agent-runner/run/payloads.errors.test.ts:121` | | `adds Codex login recovery to OpenAI OAuth refresh failures` | **behavior moved** | `adds provider login recovery to OpenAI OAuth refresh failures` — `src/cron/service.failure-alert.test.ts:845` | | `does not offer Codex login for non-OAuth authentication failures` | **behavior moved** | `does not offer provider login for non-OAuth authentication failures` — `src/cron/service.failure-alert.test.ts:884` | The obsolete provider restriction in `buildCodexLoginRecovery` is intentionally removed: typed non-OpenAI OAuth failures now receive the shared action while keeping their provider-specific terminal repair command. The old `/login codex` recovery presentation becomes `/login`; explicit `/login codex` remains supported. Typed OAuth evidence, negative authentication cases, private profile handling, and complete recovery-presentation assertions remain covered. Co-authored-by: Ayaan Zaidi <[email protected]>
Related: #136257 Supersedes #142851. Builds on #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]>
…144568) ## What Problem This Solves Fixes an issue where users preparing a provider through Gateway setup received a raw config-changed error after saving credentials if another config edit occurred during login. The unrelated edit survived, but the provider settings were not applied and the error did not explain that the credential was already saved. ## Why This Change Was Made CLI login and Gateway preparation now share one config writer. It applies only the provider's changes to the latest authored config, merges model rows by ID, rejects conflicting or invalid edits, and uses the existing saved-credential/settings-failure error. Pending plugin-install records remain with their existing commit owner. The setup path no longer binds publication to the snapshot taken before login. Strict snapshot checks remain for migration promotion and verified setup operations that require them. Credential persistence, cancellation, and default-model policy retain their existing owners. ## User Impact Unrelated edits made while provider setup waits for input survive, and setup can complete. If settings cannot be applied, setup explains that credentials were saved and retains the config owner's recovery guidance. ## Evidence - Reproduced on main `a321595f496e5a95d2bd0ffe81f7a080b4fcdfc8` through the shipped Gateway client: start preparation, edit an unrelated setting while the provider key prompt waits, then complete. Before: raw config-changed error with credential saved. After: setup completes with the edit and credential retained. - Real config-directory permission failure: before, config-only error despite a saved credential; after, explicit saved-credential/settings-failure message. Used isolated state and synthetic credentials. - 45 targeted Gateway setup tests and 55 CLI auth tests pass. The three original new regressions fail on main. Added protection for a config that becomes invalid during login. - Focused lint, formatting, line-count and assertion checks pass. Full type checks run in GitHub CI. Related: #144181, #144436. No changes to the credential replacement paths under #144524. Co-authored-by: Ayaan Zaidi <[email protected]>
…#144181) Related: openclaw#136257 ## Problem Provider login could overwrite settings changed during sign-in and could hide that credentials were already saved when settings application failed. CLI auth changes used a read-only status refresh that did not acknowledge publication to the Gateway's prepared auth state. ## Solution Login saves credentials through the existing owner and replays only its configuration changes against the writer's current source. Independent additions also merge when their parent object was absent at login start; overlapping edits still report a conflict. Model identities are normalized through the existing config owner. ID-keyed model rows merge as upserts: unchanged fields and concurrent entries survive, while overlapping changes report a settings conflict separately from the saved credential. The administrator-only `models.authRefresh` method uses the existing Gateway publication owner and waits for prepared auth state. It reloads shared-store ownership after external writes and rekeys configured owners before queuing publication. Login, logout, profile order, and local-store notifications share that owner. Generated protocol artifacts and the dependent Workboard manifest are updated without a protocol version bump. When an older Gateway returns `INVALID_REQUEST` with `unknown method: models.authRefresh`, the CLI makes one guarded legacy `models.authStatus { refresh: true }` request and still prints restart guidance. Legacy status refresh is not reported as acknowledged publication. ## Impact - Full-provider logout cancels matching active runs immediately after credential removal, even when later auth refresh fails. Targeted logout and unrelated runs remain unchanged. - Unset and existing defaults are preserved unless `--set-default` is requested. - Concurrent model IDs and independent fields survive sign-in; partial rows retain existing settings. - Read-only status access stays unchanged. The read-to-admin scope narrowing is intentional for the new mutation; permission errors do not trigger the compatibility path. - Order acknowledgement includes auth publication. A committed order still returns a warning if refresh fails. - Omitted workspace is supported by configured-owner lookup; refresh uses current configuration rather than stale request facts. ## Evidence - 398 current-owner targeted tests pass across retained and refreshed owner/sibling proof, including CLI login/logout/order, config replay, ID normalization, partial model rows, fallback classification, runtime notifications, scoped/overlapping publication, and public method admission. - Baseline real CLI proof shows a concurrent logging edit being overwritten before the repair. Credential readback confirms persistence even when settings are rejected. - Fresh eight-scenario CLI acceptance on `f6044cbdd60a` passes default controls, ordinary ID upserts, concurrent new IDs, independent field edits, and saved-credential reporting for genuine conflicts. The prior failed partial-row run is retained in the evidence history. - Real Gateway proof shows acknowledged publication, visible credentials/model availability, overlapping agent refreshes, read-only denial with status access retained, local-agent logout, and remote-store separation. - Fresh real-Gateway proof with older-method response controls on `f6044cbdd60a` passes login, order, and local logout: exactly one legacy status request follows the typed unknown-method response, restart guidance remains, and no publication success is claimed. Wrong method/code, permission failures, and mismatched state do not use the fallback. The same pass verifies the updated prepared-catalog behavior from main. - Live logout fault proof on `117f47d41b4a` starts two real provider HTTP requests through `chat.send`, then makes provider auth preparation fail during publication. Full-provider logout still closes the matching request and emits `auth-revoked`; the unrelated request stays active and completes. The response remains `UNAVAILABLE`. The registered-handler regression is red before the fix and green afterward. - The absent-parent regression fails on `117f47d41b4a` and passes after the one-condition conflict-check correction. The existing registered-provider login test verifies both provider entries, credentials, and the original default; 52 selected login/config tests pass. No further live fixture experiments were run. - Formatting, syntax lint, assertion safety, max-lines limits, protocol generation/validation, and relevant generated-output checks pass. Full CI runs on GitHub. Fixtures use synthetic credentials; no live vendor OAuth or model inference is claimed. Existing limitation: shared-main CLI logout reports an auth-store lock failure on both the pinned baseline and candidate before refresh. Agent-local logout and its refresh are verified; this PR does not change the shared-profile remover. An additional targeted-profile fault attempt stopped at credential removal before reaching publication; it is retained as a limitation. Existing targeted-logout preservation tests pass. The separate setup lifecycle is owned by openclaw#144195. Shared login results and chat/Telegram completion presentation follow in the next extraction PR. Co-authored-by: Ayaan Zaidi <[email protected]>
) Related: openclaw#136257 Follows: openclaw#144181 ## What Problem This Solves Users running `/login codex` in private chat could receive “login complete” after credentials were saved even when the Gateway rejected the auth refresh or could not be reached. A failed provider-settings write after credential storage instead appeared as an ordinary login failure. ## Why This Change Was Made The login owner now carries its existing refresh outcome through fresh and imported login results. A lightweight typed error preserves the saved-credential fact when applying provider settings fails, including the original CLI message and cause. The existing shared login runtime validates the result and owns completion and failure wording for generic chat and native Telegram. Both callers retain their admission, cancellation, device-code delivery, session-adoption and terminal-delivery owners. A failed session switch remains visible alongside a failed refresh. ## User Impact - Successful refresh keeps the existing retry guidance. - Rejected or unreachable refresh says credentials were saved and gives recovery guidance. - A failed provider-settings write is distinguished from a failure before credentials were saved. - This adds no configuration key, protocol change, permission change, provider menu or live OAuth behavior. ## Evidence - Baseline `19250eca`: five producer regressions and two refresh-presentation cases in each chat surface fail before the fix. - 106 focused tests pass: producer 55, generic chat 26, native Telegram 22, owner pairing callback 1, shipped CLI integration 2. The final rebase preserves the contribution; the callback and CLI cases also pass on `b6f7b82836dc`. - Formatting, focused lint, assertion and size ratchets, normal commit hooks, the final build and built Telegram startup check pass on Testbox. - Real Telegram Test Server baseline: `/login codex` receives an actual rejected refresh, then incorrectly says “login complete.” Five independent real-Telegram recordings pass on the final built head, each with ordered before/after credential readback, zero inference, and verified cleanup: | Outcome | Observed result | Sent message ID | | --- | --- | --- | | Refresh acknowledged | Completion follows the actual Gateway acknowledgment; credential remains saved. | 13852737536 | | Refresh rejected | Saved-credential notice and recovery guidance follow the actual rejection. | 13856931840 | | Gateway unreachable | Saved-credential notice explains the missing Gateway application. | 13861126144 | | Provider settings rejected | Credential remains saved; invalid settings are rejected; the reply preserves both facts. | 13865320448 | | Failure before save | Ordinary failure reply; credential store remains empty. | 13869514752 | The channel fixture uses a synthetic provider credential through the normal login producer and the real native Telegram command. It does not claim live vendor OAuth or inference. Full event files retain sent message IDs, timestamps and ordering; identity and private-path redactions are recorded with hashes. Earlier heartbeat-contaminated and unordered-snapshot recordings remain disclosed as failed or limited evidence. Co-authored-by: Ayaan Zaidi <[email protected]>
…#144329) ## Problem Models sign-in also runs model setup, which can activate a provider's starter model. Bare `/login` starts OpenAI device authentication before the user chooses a provider. ## Solution Add credential-only provider login in Models and one shared provider menu for chat. Plugins declare optional login choices in their manifests. Core resolves provider and method choices and produces existing command buttons or copyable commands. Bare `/login` always asks for a provider, even when only one is available. API-key and local setup methods remain available through explicit provider commands. `/login codex` retains its device-code flow. The credential-only flow uses the shared persistence and auth-refresh owner from merged openclaw#144181. It preserves the selected model, restrictions, concurrent settings and existing account pins. Models publishes the saved credential through the current Gateway context. Cancellation locks at the real persistent-effect boundary; confirmed saves remain visible through later errors. Caller authority is checked at credential and session commits, and disconnected clients cannot finish pending login. Qualified choices reject stale or ambiguous plugin owners. Leaving Models closes its wizard input through the existing close operation and waits for admission to settle. This uses optional `closeInput` on `wizard.cancel`; ordinary cancellation still refuses to interrupt a protected save. Separate pending requests keep page disposal independent of an outstanding Cancel response. The final conflict resolution also preserves the shared refresh outcomes from merged openclaw#144436: rejected or unreachable refresh reports saved credentials with recovery guidance. One shared error module carries saved-credential and settings-write failure facts, and the provider-neutral runtime owns completion/failure wording for both chat paths. Channels render core-owned command actions. Provider-neutral recovery replaces the old OpenAI-specific recovery path. OpenAI, MiniMax and xAI declare their supported credential-only choices; methods requiring starter discovery retain setup. ## Impact - No new configuration keys or database schema. - Optional metadata preserves setup for plugins that omit it. - Connecting a provider does not activate its default model. - Chat selection rechecks current owner permission and availability. ## Evidence Original baseline: `f1881c4f376edf3229e669c189cbd2f4a453a3ea`. Integrated base after openclaw#144181: `872107b561da08e74f1402e03d724136fc521ae6`. The later required conflict resolution integrates openclaw#144436 at `1f2227f786967da4b4bd3662501df6ea0003d2c3`. - Real Telegram Test Server baseline: bare `/login` issued a device code before selection. Candidate: provider buttons, second method menu, synthetic device code, saved result and rejection of a stale qualified selection. Telegram transport and user actions are real; provider credentials are synthetic. - Real Gateway baseline: `models.authLogin` was unknown. Candidate: saved fixture credential with the same default model and restrictions. - Independent public-client checks cover singleton webchat selection, wrong-connection denial, unavailable choices, disconnect rejection and positive connected-owner completion. An existing CLI setup flow with omitted metadata still saves credentials and honors explicit `--set-default`. - Integrated public-client cancellation proof: cancelling before save leaves no credential; cancelling after profile visibility while a provider note is pending returns running, and acknowledging the note produces the saved terminal result. A public settings edit during login survives; the saved profile appears without restarting the Gateway. - Browser captures show Connect, explicit provider selection, the sign-in URL/code and saved result with the selected model unchanged. Captures were inspected. - Current integrated focused Vitest: 243 passing tests across the auth producer and choice resolution, shared login runtime, core chat, native Telegram, Gateway wizard ownership, Models UI and the CLI sibling. Earlier retained checks cover method ordering, setup, MiniMax/xAI and provider recovery. The Telegram fixture cleanup preserves all test names, parameter rows and assertions; its 25 cases pass after cleanup. - Page-disposal regression: the original Gateway kept waiting after a saved note, and the original Models page left the wizard unsettled on removal. The correction passes 33 Gateway and 49 UI tests, including disposal during a pending Cancel and a second login on the same connection. Fresh real-Gateway proof rejects a peer disposal, preserves the saved credential, returns truthful closure status, and immediately admits the same owner’s next login. - Focused lint, assertion safety, runtime build and whitespace checks pass. Full typechecking and full CI run on GitHub. This extracts Auth C+E from openclaw#136257 and replaces closed openclaw#142943. Auth A was merged before integration; its implementation was not copied into this branch. ## Deletion and rewrite ledger `src/auto-reply/codex-login-recovery.ts` moved to `src/auto-reply/provider-login-recovery.ts`. Its `buildCodexLoginRecovery`, `CodexLoginRecoveryEvidence`, and `CodexLoginRecovery` symbols moved to `buildProviderLoginRecovery` (`:23`), `ProviderLoginRecoveryEvidence` (`:5`), and `ProviderLoginRecovery` (`:11`). The fixed OpenAI/Codex recovery action is replaced by the shared provider menu. No recovery test definition was deleted; the nine renamed or parameterized definitions are mapped below against head `73cfa4b319b9640a6711b2dc8e871d9ff4aea035`. | Removed test name | Disposition | New test name and location | | --- | --- | --- | | `adds Codex login recovery to raw forwarded refresh failures` | **behavior moved** | `adds provider login recovery to raw forwarded refresh failures` — `src/auto-reply/reply/agent-runner-execution-auth-failures.test.ts:51` | | `keeps Codex login recovery actionable on Control UI turns` | **behavior moved** | `keeps provider login recovery actionable on Control UI turns` — `src/auto-reply/reply/agent-runner-execution-auth-failures.test.ts:72` | | `preserves Codex login recovery in known failure payloads` | **behavior moved** | `preserves provider login recovery in known failure payloads` — `src/auto-reply/reply/agent-runner-execution-auth-failures.test.ts:118` | | `keeps disabled OpenAI OAuth profiles actionable on later turns` | **behavior moved**; original OpenAI row retained, xAI and MiniMax rows added | `keeps disabled %s OAuth profiles actionable on later turns` — `src/auto-reply/reply/agent-runner-execution-auth-failures.test.ts:228` | | `does not offer Codex login for $label` | **behavior moved**; API-key and transient OAuth negative rows retained, provider-name-only negative row added | `does not offer provider login for $label` — `src/auto-reply/reply/agent-runner-execution-auth-failures.test.ts:277` | | `keeps non-OpenAI OAuth refresh failures on provider-specific terminal guidance` | **behavior moved and expanded**; terminal guidance retained, shared login action added | `adds provider login while retaining non-OpenAI terminal guidance` — `src/auto-reply/reply/agent-runner-execution-auth-failures.test.ts:289` | | `turns returned OpenAI refresh failures into Codex login recovery` | **behavior moved**; original OpenAI row retained, xAI and MiniMax rows added | `turns returned %s refresh failures into provider login recovery` — `src/agents/embedded-agent-runner/run/payloads.errors.test.ts:121` | | `adds Codex login recovery to OpenAI OAuth refresh failures` | **behavior moved** | `adds provider login recovery to OpenAI OAuth refresh failures` — `src/cron/service.failure-alert.test.ts:845` | | `does not offer Codex login for non-OAuth authentication failures` | **behavior moved** | `does not offer provider login for non-OAuth authentication failures` — `src/cron/service.failure-alert.test.ts:884` | The obsolete provider restriction in `buildCodexLoginRecovery` is intentionally removed: typed non-OpenAI OAuth failures now receive the shared action while keeping their provider-specific terminal repair command. The old `/login codex` recovery presentation becomes `/login`; explicit `/login codex` remains supported. Typed OAuth evidence, negative authentication cases, private profile handling, and complete recovery-presentation assertions remain covered. Co-authored-by: Ayaan Zaidi <[email protected]>
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]>
…penclaw#144568) ## What Problem This Solves Fixes an issue where users preparing a provider through Gateway setup received a raw config-changed error after saving credentials if another config edit occurred during login. The unrelated edit survived, but the provider settings were not applied and the error did not explain that the credential was already saved. ## Why This Change Was Made CLI login and Gateway preparation now share one config writer. It applies only the provider's changes to the latest authored config, merges model rows by ID, rejects conflicting or invalid edits, and uses the existing saved-credential/settings-failure error. Pending plugin-install records remain with their existing commit owner. The setup path no longer binds publication to the snapshot taken before login. Strict snapshot checks remain for migration promotion and verified setup operations that require them. Credential persistence, cancellation, and default-model policy retain their existing owners. ## User Impact Unrelated edits made while provider setup waits for input survive, and setup can complete. If settings cannot be applied, setup explains that credentials were saved and retains the config owner's recovery guidance. ## Evidence - Reproduced on main `c073aed1cfd1ae78c62b1920e76456b595e26950` through the shipped Gateway client: start preparation, edit an unrelated setting while the provider key prompt waits, then complete. Before: raw config-changed error with credential saved. After: setup completes with the edit and credential retained. - Real config-directory permission failure: before, config-only error despite a saved credential; after, explicit saved-credential/settings-failure message. Used isolated state and synthetic credentials. - 45 targeted Gateway setup tests and 55 CLI auth tests pass. The three original new regressions fail on main. Added protection for a config that becomes invalid during login. - Focused lint, formatting, line-count and assertion checks pass. Full type checks run in GitHub CI. Related: openclaw#144181, openclaw#144436. No changes to the credential replacement paths under openclaw#144524. Co-authored-by: Ayaan Zaidi <[email protected]>
Related: #136257, #144195.
What Problem This Solves
Fixes an issue where provider login overwrote settings changed during sign-in or hid saved credentials when applying settings failed. Authentication changes also lacked acknowledged Gateway publication.
Why This Change Was Made
Login merges its changes against current configuration, including model-ID upserts, while reporting overlapping conflicts separately from credential persistence. The administrator-only authentication refresh method waits for prepared state. Login, logout, profile order and local notifications share that publication operation.
User Impact
Concurrent settings and defaults survive login. Full-provider logout cancels matching runs after credential removal even if refresh fails. Older Gateways receive one guarded status refresh plus restart guidance; this is not reported as completed publication.
Consumers: command-line login, logout and ordering use acknowledged authentication refresh.
Evidence
Focused tests and real command-line/Gateway checks covered merges, publication, permissions, compatibility and logout during refresh failure. Shared-main logout still failed at credential removal on both compared versions; agent-local logout passed. Synthetic credentials were used.