Skip to content

fix: preserve model login settings and refresh gateway auth - #144181

Merged
obviyus merged 1 commit into
mainfrom
feat/models-login-persistence
Sep 10, 2026
Merged

obviyus merged 1 commit into
mainfrom
feat/models-login-persistence

Conversation

@obviyus

@obviyus obviyus commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

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.

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

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: android App: android app: web-ui App: web-ui gateway Gateway runtime commands Command implementations agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 10, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 10, 2026
@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 10, 2026, 4:28 PM ET / 20:28 UTC (Revision 8).

ClawSweeper review

What this changes

Preserve 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
Reviewed head: 2215907e8c28dc4f8e121141a93e85d9e468cf23

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-based repair with relevant real-path proof, useful regression coverage, and no remaining blocking finding.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Recorded real CLI and Gateway observations cover settings preservation, publication acknowledgement, denied read-only refresh, and guarded legacy fallback; the retained chat.send HTTP fault proof shows revoked-request cancellation before failed publication while an unrelated request completes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded real CLI and Gateway observations cover settings preservation, publication acknowledgement, denied read-only refresh, and guarded legacy fallback; the retained chat.send HTTP fault proof shows revoked-request cancellation before failed publication while an unrelated request completes.
Evidence reviewed 9 items Introduced changes and merge identity: Reviewed the merge-base-to-head changes. The test merge records exactly the supplied main parent followed by the pinned PR head; unrelated main-branch changes were excluded from attribution.
Login preserves current configuration: Login derives a canonical configuration delta, checks overlapping edits, and applies it through the existing source-config writer. Registered-provider tests cover concurrent providers, model IDs, independent fields, unset defaults, and credential persistence after settings rejection.
Prior logout finding resolved: Full-provider logout aborts matching runs immediately after successful removal and before awaiting refresh. The handler blob at the previously reviewed revision and current head is identical: ab68cbe27b9e73c7acf5d5de2930cfd75d65a90a. The recorded live fault proof therefore remains relevant to this handler.
Findings None None.
Security None None.

How this fits together

Provider 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]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +203, Tests +509, Docs +2, Other +19. Total +733 across 31 files.

View PR surface stats
Area Files Added Removed Net
Source 16 317 114 +203
Tests 12 783 274 +509
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 2 19 0 +19
Total 31 1121 388 +733

Review metrics

Metric Value Why it matters
Refresh protocol 1 administrator-only method; 0 new user configuration options The mutation gains explicit publication acknowledgement while preserving the existing status API.
Production and test growth Production TypeScript +203 lines; tests +509 lines Production growth supplies conflict-aware replay and shared refresh coordination, with focused regression coverage.

Technical review

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

Labels

Label justifications:

  • P2: This repairs bounded provider-login configuration and Gateway auth-refresh behavior.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded real CLI and Gateway observations cover settings preservation, publication acknowledgement, denied read-only refresh, and guarded legacy fallback; the retained chat.send HTTP fault proof shows revoked-request cancellation before failed publication while an unrelated request completes.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded real CLI and Gateway observations cover settings preservation, publication acknowledgement, denied read-only refresh, and guarded legacy fallback; the retained chat.send HTTP fault proof shows revoked-request cancellation before failed publication while an unrelated request completes.

Evidence

What I checked:

  • Introduced changes and merge identity: Reviewed the merge-base-to-head changes. The test merge records exactly the supplied main parent followed by the pinned PR head; unrelated main-branch changes were excluded from attribution. (01cc7bbbcbba)
  • Login preserves current configuration: Login derives a canonical configuration delta, checks overlapping edits, and applies it through the existing source-config writer. Registered-provider tests cover concurrent providers, model IDs, independent fields, unset defaults, and credential persistence after settings rejection. (src/commands/models/auth.ts:433, 2215907e8c28)
  • Prior logout finding resolved: Full-provider logout aborts matching runs immediately after successful removal and before awaiting refresh. The handler blob at the previously reviewed revision and current head is identical: ab68cbe27b9e73c7acf5d5de2930cfd75d65a90a. The recorded live fault proof therefore remains relevant to this handler. (src/gateway/server-methods/models-auth-status.ts:532, 2215907e8c28)
  • Compatibility and authorization: The new method requires operator.admin. CLI fallback requires the exact typed unknown-method response, retains the local shared-auth guard, and still reports restart guidance. Permission failures cannot enter fallback; existing read-only status remains available. This addresses the substantive compatibility feedback in the human review. (src/commands/models/auth-refresh.ts:36, 2215907e8c28)
  • Recorded production behavior proof: The supplied complete PR body records real CLI default/config preservation scenarios, real Gateway publication and read-only denial, guarded older-method responses, and two provider HTTP requests through chat.send under injected publication failure. The revoked request closes with auth-revoked while the unrelated request completes. Proof uses synthetic credentials; shared-main logout contention and the unsuccessful targeted-profile fault attempt are explicitly disclosed. Captured context sourceRevision: 5e021a66f62ddaeecffb5cf6c5c93a18c4a59b9b26ca94032f6374d3387e3015. (117f47d41b4a)
  • Current main still uses status refresh: Fetched main still calls models.authStatus and does not acknowledge prepared auth publication. The merged setup repair at fix: retain setup credentials after a failed connection check #144195 addresses a separate lifecycle; feat(models): add credential-only sign-in and a provider login menu #144329 explicitly depends on this work. (src/commands/models/auth-refresh.ts:21, 5d3cc203b67d)

Likely related people:

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

Rating scale

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

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (7 earlier review cycles)
  • reviewed 2026-09-10T16:26:41.059Z sha 651da9de06d706bcb7d14573ebb3ce5e035f8105 :: blocked before merge. :: none
  • reviewed 2026-09-10T16:44:28.566Z sha e4239c1 :: blocked before merge. :: none
  • reviewed 2026-09-10T17:04:49.537Z sha e3a5458b8c2759cf9c96a1a9fffe76289168937d :: blocked before merge. :: none
  • reviewed 2026-09-10T17:35:21.864Z sha 735f661680e1b004b9c04877f84bd87fdecf87d6 :: blocked before merge. :: none
  • reviewed 2026-09-10T18:57:44.056Z sha 79550acd6a6110cb41f0c58f87d985720e6be4a7 :: needs real behavior proof before merge. :: [P2] Cancel provider runs even when auth publication fails
  • reviewed 2026-09-10T19:53:33.671Z sha f6044cb :: needs real behavior proof before merge. :: [P2] Cancel provider runs even when auth publication fails
  • reviewed 2026-09-10T20:17:20.420Z sha 117f47d41b4af9c9e806e411f471d0ea13594bb4 :: needs maintainer review before merge. :: none

@obviyus
obviyus force-pushed the feat/models-login-persistence branch 3 times, most recently from e4239c1 to e3a5458 Compare September 10, 2026 16:56
@obviyus
obviyus force-pushed the feat/models-login-persistence branch from e3a5458 to 735f661 Compare September 10, 2026 17:27
@openclaw-barnacle openclaw-barnacle Bot added the cli CLI command changes label Sep 10, 2026

@Yigtwxx Yigtwxx left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@obviyus

obviyus commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator Author

Applied the final review decisions in f6044cbdd60a6235b29d9e671cfa6a12f0f0b34d:

  1. The CLI now falls back once to models.authStatus { refresh: true } for the typed INVALID_REQUEST / unknown method: models.authRefresh response. The shared-state guard stays in place and restart guidance is still printed. The new mutation remains admin-only; scope denial does not trigger fallback. Regression and real Gateway wire proof cover the positive and negative cases.
  2. Login replay now uses mergeObjectArraysById: true. It derives changed fields per canonical model ID so partial rows preserve existing fields and concurrent entries. Real CLI proof confirms successful concurrent ID/field merges. Overlapping changes still preserve current config and report the saved credential separately from settings failure.
  3. Configured-owner lookup supports omitted workspace. Refresh uses current config and waits for publication before order acknowledgement; a failed refresh retains the committed order with a warning.
  4. The separate setup path remains outside this PR and is owned by fix: retain setup credentials after a failed connection check #144195.

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.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 10, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 10, 2026
@obviyus
obviyus force-pushed the feat/models-login-persistence branch from 117f47d to 2215907 Compare September 10, 2026 20:19
@obviyus

obviyus commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

landpr-approve-admin-merge
pr: 144181
head: 2215907
scope: owner-review

@obviyus
obviyus merged commit 54c3655 into main Sep 10, 2026
187 checks passed
@obviyus
obviyus deleted the feat/models-login-persistence branch September 10, 2026 20:47
@obviyus

obviyus commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

Owner-approved admin merge completed at 54c3655e12a66f24cf0189b32323ec21d17b3635 from head 2215907e8c28dc4f8e121141a93e85d9e468cf23.

  • The procedural security-owner involvement hold was waived under the explicit owner approval. Fresh exact-head ClawSweeper review found no remaining code or security defect and rated the proof sufficient.
  • Proof: 398 targeted tests; real CLI settings/default preservation and older-Gateway fallback; real Gateway publication, scope admission, and revoked-request cancellation despite publication failure. The absent-parent regression failed before the correction and passed afterward.
  • All exact-head checks passed, including Android. No unrelated-red exception was needed.
  • The merge retains Co-authored-by: Ayaan Zaidi <[email protected]>.

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"
}

obviyus added a commit that referenced this pull request Sep 10, 2026
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]>
obviyus added a commit that referenced this pull request Sep 10, 2026
## 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]>
obviyus added a commit that referenced this pull request Sep 10, 2026
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]>
obviyus added a commit that referenced this pull request Sep 11, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 11, 2026
…#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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 11, 2026
)

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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 11, 2026
…#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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 11, 2026
Related: openclaw#136257
Supersedes openclaw#142851. Builds on openclaw#144181.

## What Problem This Solves

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

## Why This Change Was Made

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

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

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

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

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

## User Impact

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

## Evidence

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

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 11, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: android App: android app: web-ui App: web-ui cli CLI command changes commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. plugin: workboard proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants