Skip to content

fix(models): allow API-key setup while the Gateway runs - #168588

Merged
obviyus merged 36 commits into
mainfrom
fix/models-auth-via-gateway
Oct 11, 2026
Merged

obviyus merged 36 commits into
mainfrom
fix/models-auth-via-gateway

Conversation

@obviyus

@obviyus obviyus commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #168135, #168108, #168471

What Problem This Solves

Fixes API-key setup from the CLI when a running Gateway owns local state.

User Impact

Users can run openclaw models auth paste-api-key --provider <id> without stopping the Gateway. The Gateway saves the key and refreshes its model catalog. Offline behavior is unchanged. An explicit, non-empty --profile-id still requires offline use.

Why This Change Was Made

#168135 correctly stopped CLI processes from writing credentials around a live Gateway. It also kept CLI flows offline where the existing Gateway APIs could not preserve their behavior. Manual API-key setup already uses the same credential writer as models.authSetApiKey, so that subset can use the owner instead of refusing.

This change uses the canonical local-state-owner.ts route, as in #168108 and #168471. It binds the request to the discovered local owner and port, sends expectedOwnerId, requires operator.admin, rechecks ownership before dispatch, and never retries a possibly accepted write locally. API-key input is collected only after owner selection. The RPC checks the expected owner at credential and config writes; calls without that field retain their existing behavior. Owner-bound requests preserve the CLI's agent-selection rules.

Update behavior: an older Gateway that lacks models-auth-set-api-key-owner-v1 is refused before the API-key request; update and restart it, or stop it and retry offline.

No request/response schema, new RPC method, config option, database schema, or paired-device fallback is added.

Command-to-RPC mapping

CLI command or option Existing RPC Result in this change
paste-api-key --provider <id> [--agent <id>] models.authSetApiKey Delegate provider, key, and agent; print saved profile and any application warning.
paste-api-key --profile-id <id> No profile-id field in models.authSetApiKey Refuse this option with offline guidance.
paste-token [--expires-in <duration>] No equivalent API-key write Stay offline: token type and expiry must not become an API key.
login, including API-key plugin methods models.authLogin and wizard.* Stay offline: CLI method/profile/default/force semantics are not an exact manual-key mapping.
login-github-copilot models.authLogin and wizard.* Stay offline; device flow is outside this change.
add / setup-token No exact generic mapping Stay offline; these can run local provider CLI or import flows.
list models.authStatus Stay offline: the status projection lacks the CLI list's state-path, cooldown, disabled-state, and recovery fields.
logout <profileId> [--yes] models.authLogout Deferred; retain current offline behavior.
order get models.authStatus Deferred; retain the existing owner-aware read.
order set <profileIds...> models.authOrderSet Stay offline: the RPC requires the full profile order; the CLI allows partial lists.
order clear models.authOrderSet Deferred; retain offline reset behavior.
activate <profileId> No exact test-and-activate mapping Stay offline.

Evidence

ACP CI comparison: src/gateway/server.chat.acp-completion.test.ts passed all 12 cases when run directly on PR head 4f32198a3a8f5446e1c24b783d624884415553e6 and on clean main at its exact merge parent 4f3eb4f254664cd0ed1a4b31678e9e4957348d20. The CI failure in completes persistence failure after explicit abort once expected [start, end] but received [end]; that case passed on both local runs. This does not establish an inherited failure or a PR-caused failure—it records that neither isolated run reproduced it. No code or test assertion was changed.

Latest review repair: removed only the stale prepareDispatchCurrent test expectation after #168882 retired that callback. Owner binding, capabilities, authentication, assertDispatchCurrent, and no-local-write assertions remain. The requested direct command node scripts/run-vitest.mjs run src/cli/models-cli.state-owner.test.ts passed all 16 tests (24.22 seconds total). No retired production callback was restored.

  • The new CLI regression fails with the original main-branch auth router: 12 existing refusal cases pass, and API-key delegation fails with OWNER_UNAVAILABLE.
  • The initial candidate passed 153 targeted tests across CLI ownership, the real API-key writer, Gateway transport, and the real API-key RPC.
  • Tests cover cancelled input, no local fallback, old-Gateway capability refusal before request dispatch, and rejected owner changes without credential/config writes.
  • Existing unbound API-key RPC requests still pass the real credential-writer test.
  • pnpm build passed.
  • Isolated live profile: piped a real OpenAI key into pnpm openclaw --profile <profile> models auth paste-api-key --provider openai. The Gateway picker changed from zero available OpenAI models to one. A real openclaw agent turn returned AUTH_OWNER_OK, using the saved auth profile. The listener PID stayed the same; no restart was needed.
  • The Gateway token was supplied only at runtime and was not in config. The same CLI path worked when it received that token. Without the token, it refused without a local write and named OPENCLAW_GATEWAY_TOKEN / OPENCLAW_GATEWAY_PASSWORD as the next step.
  • An earlier node scripts/check-changed.mjs --staged run passed the format, ownership, dependency, and other early guards, then stopped at main's UI-e2e test-root budget (722 versus 720). That result predates the empty-input regression below; no UI files are changed here.

Review repair: authority at the final write

  • The captured requester guard now reaches the auth store's existing SQLite worker admission, not only the updater callback. It also reaches config beforeCommit and the config writer's effect-time authority check.
  • Credential observation: revoke after the real updater returns, before commit; the operation rejects, the original stored key remains, and config bytes do not change. The permitted control stores the replacement key.
  • Config observation: revoke after the transform returns; the operation rejects and the source config remains byte-for-byte unchanged. The already saved, unchanged credential remains intact. The permitted control publishes the auth-profile config.
  • The four allowed/revoked controls and 17 auth-store update tests pass. These tests use real credential/config persistence; only the revocation instant is controlled.
  • Fixed the two curly lint errors in the CLI input adapter. Targeted production lint passes for the adapter, API-key writer, and auth-profile upsert owner.
  • After merging main, the changed-file gate passed core typechecking and all 28 core test graphs. It stopped at unrelated unused exports in extensions/codex/src/app-server/managed-binary.ts, tools/solid-lint/index.mjs, and ui/src/test-helpers/solid-application-context.tsx; those files are unchanged by this PR.

Review repair: configured loopback auth-none

  • Owner-bound shared-auth requests now enable the transport's existing bounded auth-none path. A Gateway explicitly configured with gateway.auth.mode: "none" uses the backend client identity without creating or reading device credentials. Remote targets and URL overrides retain the existing refusal rules.
  • A registered paste-api-key regression invokes the real resolveGatewayCallDeviceAuth with the owner route's options. It failed before the fix with GatewayLocalBackendSharedAuthUnavailableError and passes after the fix. All 105 transport tests and 16 CLI ownership tests pass.
  • The latest main was merged after these focused checks. Clean-main export-name collision checking passed at 76a282c7a1c6ca958517ce15f13e17371c14be11; the channel collision was fixed upstream by 13296b17cd0. The same clean main reproduced the three lint errors in the untouched plugin-state observation cache and SQLite comparison test. Remaining baseline runs were stopped at maintainer request while upstream CI repairs were being merged.

Review repair: empty API-key input

  • Empty or whitespace-only stdin now reports: No API key was supplied. Rerun this command and paste a non-empty API key, or pipe one to stdin.
  • Two short tests read real streams and cover both inputs. Both failed with the old Required message and pass after this change.
  • The changed-file gate passed formatting, core typechecking, and all six selected test graphs. It stopped at the unrelated GatewayApprovalEventPublisherV2 unused export in src/gateway/server-instance-runtime.types.ts, which this repair does not modify.

Existing CI failures checked on main

  • On clean main aec6e7a56eb03eaba1a648310876d2d6d4811745, the UI cloud-startup toast-recovery case fails with the same Control UI readiness hook is unavailable error as this branch (two cases pass, one fails).
  • The same clean main also reproduces the FIFO assertions missing QUEUED_STEER_A and ORDINARY_MESSAGE_B. Neither test nor its steer behavior is changed by this PR.
  • The document-steer case also fails on clean main, but earlier: the initial turn does not reach the mock provider (zero requests). On this branch it reaches the later missing-document assertion. The baseline failure prevents an exact comparison of that later assertion; it is not claimed as an identical local reproduction.
  • On the repaired head, the Node shard reports the same FIFO failures. A separate cron shard reports hydrates runtime metadata for a reasoning-capable fallback candidate (expected two calls, received four); its main-branch investigation is separate and no auth change is claimed to fix it.
  • src/cli/plugin-local-state-owner.test.ts has the same result on this branch (5033eb75ade) and clean main (9a165c492058ddf6fc3468cde27b201514c954f1): 33 pass, one fails. The failed case is routes memory search limits and JSON output through the discovered owner; both report The memory runtime does not support CLI search inside OUTCOME_UNKNOWN. The fixture supplies a manager but not the searchForCli callback now required by the Memory Core handler. This is a main-branch fixture mismatch, not an auth routing regression; no test or routing behavior was changed to hide it.

CI 38113017692: pinned per-file comparison

Compared PR head f062e5069509128680db873fa6643d262b034b0b with its exact main parent 9e444e1078169a5bd1117eaf8b5c50cdca2fde15. Each file ran through the repository test runner under pueue.

File PR result Main result Verdict
src/gateway/server-methods/models-auth-api-key.integration.test.ts 1 failed: corrupt config revision key during startup Same Inherited; failure occurs before the auth RPC or acknowledgment
src/gateway/gateway-cli-plugin-routing.test.ts 1 failed: corrupt config revision key Same Inherited
src/gateway/server-methods/sessions-mutations.sticky-model.test.ts 3 failed, 66 passed: two undefined-error assertions and an invalid transcript frame Same Inherited
src/gateway/server.sessions.create-worktree-spawn.test.ts 1 failed, 18 passed: invalid transcript frame Same Inherited
src/gateway/server/ws-connection/connect-device-pairing.test.ts 12 failed: corrupt config revision key Same Inherited
src/gateway/session-message-events.test.ts Setup failed: corrupt config revision key; 30 skipped Same Inherited
src/gateway/session-message-events.exec-completion.test.ts Setup failed: corrupt config revision key; 2 skipped Same Inherited
src/gateway/session-message-events.history-worker.test.ts Setup failed: corrupt config revision key; 2 skipped Same Inherited
src/gateway/sessions-history-http.physical-source.test.ts 4 failed: corrupt config revision key Same Inherited
ui/src/pages/workboard/workboard-native-bundle.e2e.test.ts 2 passed (Chromium and WebKit) Same CI failure not reproduced on either revision

The config-revision owner unit file also passes both tests on both revisions. The Gateway integration failures therefore do not establish an auth-specific configRevisionHash/appliedConfigHash regression: they stop while loading the installation revision key. No corruption check was weakened and no test was changed to bypass startup. Workboard's initial missing dependencies/browser artifact were repaired before the successful comparison runs.

No overlap with protected maintainer changes.

Two-way code change: a revert restores offline-only CLI setup. Keys saved through the Gateway remain saved. The affected paths are local CLI API-key setup and the existing Gateway API-key save handler.

@clawsweeper

clawsweeper Bot commented Oct 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.

@github-actions

github-actions Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: f34ee9415d96bb402f045223954bb890a7b8e945
  • Maintainer: @obviyus
  • Repository role: maintain

These security sensitive changes were made:

  • src/agents/auth-profiles/upsert-with-lock.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/gateway/server-methods/models-auth-status.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server/ws-connection/connect-hello.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes commands Command implementations size: M labels Oct 10, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 10, 2026
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR routes manual CLI API-key setup through the running local Gateway while preserving exclusive offline execution for unsupported options.

Example: Run openclaw models auth paste-api-key --provider openai while the local Gateway is running.

  • Before: The CLI refuses and requires stopping the Gateway.
  • After: The authenticated Gateway saves the key and refreshes model availability without restarting.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused, and supported by shipped-flow observations plus real persistence controls; required CI remains a separate landing gate.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Supplied live CLI observations exercise the Gateway-owned save, refreshed model availability, a successful agent turn, unchanged listener PID, and missing-secret refusal; real-persistence controls cover permitted writes and revocation before credential/config commit, while the inspected update-dialog screenshots add no auth coverage.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Manual CLI API-key setup requires stopping a running Gateway even though its existing credential writer can perform the save.
Reason: Maintainer direction is established, and this narrowly restores the workflow without bypassing ownership or expanding unsupported auth semantics.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-backed PR solves a current-main CLI limitation, and no actionable patch defect remains.

Priority: P2
Reviewed head: f34ee9415d96bb402f045223954bb890a7b8e945

Before merge

None.

Findings

None.

Agent review details

How this fits together

The models CLI selects the local state owner, sends provider credentials through the existing authenticated RPC, and receives the saved profile and any application warning.

flowchart TD
  A[Models CLI] --> B[Local state owner]
  B --> C[Authenticated Gateway RPC]
  B --> D[Exclusive offline command]
  C --> E[Credential and config writer]
  D --> E
  E --> F[Model auth refresh]
Loading

Technical review

Best possible solution:

Keep manual API-key saves with the running Gateway and preserve exclusive offline ownership for unsupported commands.

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

Current-main source deterministically refuses paste-api-key when another Gateway owns the selected state; the supplied baseline regression confirms that refusal, and no target code was executed during this review.

Is this the best way to solve the issue?

The focused delegation is appropriate because it reuses the canonical owner and credential writer, preserves CLI agent selection, and refuses options the existing RPC cannot represent.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 86c2aae466c5.

Provenance checked

  • Offline-only CLI auth routing changes intended behavior with a stated reason (510255d: Prevent CLI credential writes around a live Gateway while preserving CLI-only semantics.)
  • Shared API-key persistence and application keeps the original intent (09e2b15: Unify Models and CLI saves while preserving metadata, defaults, credential kinds, and concurrent bindings.)
  • Local-state owner routing keeps the original intent (1b08795: Bind same-root mutations to the authenticated live owner and retain exclusive offline custody.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 09e2b15 adds src/commands/models/auth-api-key.ts:36 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 09e2b15466e1; files: src/commands/models/auth-api-key.ts)
  • Peter Steinberger: Raw commit 1b08795 adds src/cli/local-state-owner.ts:36 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1b08795ae494; files: src/cli/local-state-owner.ts)

PR surface

Source +143, Tests +251, Docs +24. Total +418 across 15 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 8 158 15 +143
Tests 6 275 24 +251
Docs 1 36 12 +24
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 15 469 51 +418

Review metrics

Metric Value Why it matters
Production versus test growth Production +158/-15; tests and support +275/-24 The added routing and authority plumbing is supported by distinct CLI, transport-capability, and persisted-write contracts.

Labels

Label changes:

  • remove merge-risk: 🚨 compatibility: Current PR review selected no merge-risk labels.

Label justifications:

  • P2: This restores a useful CLI credential-setup workflow with a limited scope and an existing offline workaround.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (37 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-11T14:34:20.018Z sha 2a7dd78 :: needs changes before merge. :: [P2] Remove the obsolete dispatch-preparation expectation
  • reviewed 2026-10-11T15:17:31.517Z sha 1f2f726 :: needs changes before merge. :: [P2] Remove the obsolete dispatch-preparation expectation
  • reviewed 2026-10-11T15:35:07.876Z sha e640dfd :: needs maintainer review before merge. :: none
  • reviewed 2026-10-11T16:05:06.600Z sha 4f32198 :: needs changes before merge. :: none
  • reviewed 2026-10-11T16:21:14.544Z sha 60d0bb0 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-11T17:09:34.425Z sha b61c1f0 :: needs changes before merge. :: none
  • reviewed 2026-10-11T17:45:52.746Z sha b61c1f0 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-11T18:22:28.234Z sha f34ee94 :: needs changes before merge. :: none

Reviewed October 11, 2026, 2:41 PM ET / 18:41 UTC (Revision 38).

@obviyus

obviyus commented Oct 10, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Oct 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: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@clawsweeper clawsweeper Bot added 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 rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Oct 11, 2026
@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

Pinned A/B evidence for the remaining generic-help login-gate timeout:

Source Exact SHA Direct runs
This PR b61c1f05efbb1db980722db07e9feacf922afe0b 2 passes; 25/25 tests each
Clean merged-main baseline ab6c07f595e963ec86b93c11c90ac8d7ebf470b6 2 passes; 25/25 tests each
Latest fetched origin/main 95dcdf93588b82b7c6f929d01089bfece6f933a1 2 failures; 24/25 tests each; identical generic-help .login-gate 30-second timeout

Each run used this command directly, without pueue:

node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner ui/src/e2e/login-gate.e2e.test.ts

The two main baselines used separate Worktrunk worktrees, wt step copy-ignored, and pnpm install --frozen-lockfile; both temporary worktrees have been removed. Runtime: macOS arm64, Node 24.21.0, local Playwright Chromium.

The failure is reproducible independently on main. The test holds the Chat JavaScript response before waiting for the lazy login screen, and can block that screen before reaching its release. The failing focused run captured the connecting splash with startupPending: true despite Gateway phase: stopped and lastErrorCode: AUTH_TOKEN_MISSING. This scenario uses an in-page mock WebSocket and injected auth rejection, not the Gateway server authentication path changed here.

Focused repair: #169248, head 180a19d8af151c40e6b0994949a5463cad45b2b7. It holds route-only Chat CSS instead, preserving the startup-pending assertion and every help assertion. The original startup-race negative control still fails when the fixture's existing startup wait is removed. With the wait restored, the login-gate and initial-connect-splash files pass 38/38 together. No timeout increase, assertion weakening, production change, or change to this PR.

The reported hosted failure remains visible in run 38157352486: checks-ui-e2e (4/9) and its aggregate openclaw/ci-gate are failed; cancelled job count is 0. These local runs do not claim that the hosted shard was rerun or passed.

@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

obviyus added a commit that referenced this pull request Oct 11, 2026
Related: #168588

## What Problem This Solves

Fixes: the generic-help login-gate browser test can time out waiting for the login screen while its own startup barrier is held.

## User Impact

No user-visible change. This repairs a Control UI test fixture without changing Gateway authentication, login behavior, timeouts, or assertions.

## Why This Change Was Made

The startup regression added in 9a98e2e holds the emitted Chat JavaScript chunk before waiting for the lazy login screen. That barrier can also prevent the login screen from becoming available, so the test never reaches the release.

Hold the existing route-only Chat stylesheet set instead. The test still observes `startupPending === true`, starts the no-error fixture before startup completes, and retains every collapsed-help and reveal assertion.

No overlap with designated maintainer changes was found in the changed file's history.

## Evidence

- Unchanged #168588 head `b61c1f05efbb1db980722db07e9feacf922afe0b`: the requested direct login-gate command passed twice (25/25 each).
- Clean main `ab6c07f595e963ec86b93c11c90ac8d7ebf470b6`: passed twice (25/25 each).
- Clean main `95dcdf93588b82b7c6f929d01089bfece6f933a1`: failed twice (24 passed, the same generic-help `.login-gate` 30-second timeout each time).
- Focused old JavaScript-barrier negative control: reproduced the same timeout. Captured state showed `startupPending: true`, a stopped Gateway with `AUTH_TOKEN_MISSING`, and the connecting splash instead of the login screen.
- Focused stylesheet-barrier case: passed.
- Original-race negative control: temporarily removing the existing startup wait still fails with `Missing mounted login gate` using the repaired barrier; the wait was restored before final proof.
- Final direct browser run of `login-gate.e2e.test.ts` and `initial-connect-splash.e2e.test.ts`: **38/38 passed**.

Commands used the repository entry point:

```sh
node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner ui/src/e2e/login-gate.e2e.test.ts
node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner ui/src/e2e/login-gate.e2e.test.ts ui/src/e2e/initial-connect-splash.e2e.test.ts
```

Proof ran on macOS arm64 with Node 24.21.0 and local Playwright Chromium; it does not claim a Linux rerun of the entire hosted shard.

Merge danger: two-way door; reverting restores only the old test barrier. Blast radius is this single browser-test scenario; no production code or persisted state changes.

Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

Pinned comparison for the chat.send connection-identity CI failure in run 38162499215.

Exact file: src/gateway/server.chat.gateway-server-chat-b.test.ts.

Ran this command directly, without pueue or a test-name filter, twice on each revision:

node scripts/run-vitest.mjs run src/gateway/server.chat.gateway-server-chat-b.test.ts
Revision Run 1 Run 2
PR f34ee9415d96bb402f045223954bb890a7b8e945 77 passed, 0 failed; 165.82 s 77 passed, 0 failed; 181.14 s
Clean main at exact merge parent cbe0b272883c68210aee33b67e4bdf66d9106587 77 passed, 0 failed; 180.80 s 77 passed, 0 failed; 165.37 s

The specific case, chat.send persists optional connection identity per turn, passed in all four runs. The CI ArrayContaining assertion did not reproduce in either isolated checkout. No PR-specific difference was observed; this comparison does not classify the CI failure's cause.

No production code, test assertion, or test configuration was changed. No empty commit or CI rerun was made. The temporary tmp/chat-ab checkout and branch were removed after the comparison.

@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Oct 11, 2026
@obviyus
obviyus merged commit 408a1f3 into main Oct 11, 2026
280 of 282 checks passed
@obviyus
obviyus deleted the fix/models-auth-via-gateway branch October 11, 2026 18:49
@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 408a1f3. While a local Gateway owns state, openclaw models auth paste-api-key now sends the key to that Gateway (owner-bound, same authority checks as the Models page) instead of refusing. Old Gateways without the new capability get no request; options the RPC can't carry still refuse with a clear next step. Proof: regression red on main; isolated Gateway paste → OpenAI models 0 → 1 and a real turn with no restart; revocation after preparation leaves credentials and config unchanged; auth-none loopback Gateways work.

obviyus added a commit that referenced this pull request Oct 12, 2026
…168671)

Related: #168588, #168135

## What Problem This Solves

Fixes provider sign-in being refused by `models auth login` and `models auth login-github-copilot` while the local Gateway owns the selected state directory.

## User Impact

Supported OAuth, device-code, and plugin API-key methods use the running local Gateway. The terminal renders the Gateway's URLs, device codes, protected inputs, and model-access choices. Credentials stay with the Gateway; the CLI never writes around it or retries a failed login locally.

Options the existing login RPC cannot represent fail explicitly before sign-in starts. The current default model remains unchanged.

## Why This Change Was Made

The old CLI router treated every interactive login as an offline mutation. The Gateway already owns provider login and wizard sessions, but its start request lacked local-owner binding and the one-shot CLI transport closed the connection immediately after the start response.

Bind login to the discovered owner with an optional `expectedOwnerId` and `models-auth-login-owner-v1`. Retain one authenticated connection for the entire wizard, recheck the local owner before follow-up requests, and cancel/settle that session before releasing terminal resources. A disconnect closes the Gateway-owned login rather than reconnecting or replaying it. OAuth loopback callbacks run on the Gateway host, which is the same machine for this local-owner route.

The Gateway revalidates authority at credential, profile-order, and config publication boundaries. Requests without owner binding retain the Control UI behavior. Declared API-key methods run credential-only for the bound CLI request; this does not change administrator requirements or UI discovery.

| CLI input | Gateway mapping |
| --- | --- |
| `--provider`, `--method` | Select the exact declared plugin login choice; send its `authChoice` to `models.authLogin`. |
| Omitted provider/method | Choose the declared login method in the terminal. |
| `--agent` | Preserve inherited/leaf selection in `agentId`. |
| `--device-code` | Select method `device-code`; conflicting `--method` still refuses. |
| `login-github-copilot` | Select provider `github-copilot`, method `device`. |
| URLs, device codes, manual code, selections | Render wizard steps and send answers through `wizard.next` on the same connection. |
| `--profile-id`, `--force`, `--set-default`, Copilot `--yes` | Refuse before starting: the existing login RPC has no corresponding fields. Offline behavior remains available after stopping the Gateway. |

Methods requiring local provider-CLI import/setup or lacking a supported login declaration remain offline. The wizard result confirms saved/applied outcome; it does not return a per-login profile identifier.

**Update behavior:** no stored-data migration or protocol-version bump. An older Gateway without the method-specific capability receives no login request. Update/restart that Gateway, or stop it and rerun offline. Ambiguous transport outcomes remain `OUTCOME_UNKNOWN`; no local fallback is attempted.

Explicitly configured loopback Gateways with `gateway.auth.mode: "none"` also
support delegated login without a token or device identity. This uses the
existing bounded local-backend resolver, not an arbitrary-URL or remote bypass.

## Evidence

- Review repair at `d0b9c83a53d6e785c1dae0f97ea315718b1e1016`: 208 focused tests passed in 91.6 seconds with one worker. Scoped type-aware lint, production types, and the command/Gateway-method test type shards passed.
- A real `plugins.load.paths` fixture is discovered from the selected read-only config; disabling it or excluding it from the allowlist removes it. The discovery read creates no state database.
- Real Gateway/SQLite/config controls prove: an owner-bound login saves its credential and provider config; a non-admin caller is rejected without starting the provider; revoking the actual requester after asynchronous persistence-lock preparation leaves both credentials and config unchanged. Instrumentation calls the original handler and persistence function; no writer result is mocked.
- Discriminating negative controls fail when the selected config is omitted (provider disappears) or the pre-write authority callback is omitted (the real store receives the synthetic credential after revocation). Both controls were restored before the passing run.
- The unrelated transcript-library CI timeout also reproduces on clean main `4e3818bab0febf3ce265aafab07b0c98b7cf7f16`: two cases pass and the same `Loading meetings…` assertion at line 252 fails. No UI workaround or assertion change is included.

- On the latest input-guidance base, 26 focused tests pass, including real-stream empty/whitespace input checks and registered auth-none login through the real resolver.

- The two new CLI delegation regressions fail against the base CLI with `OWNER_UNAVAILABLE`, then pass with the owner route.
- Focused CLI, Gateway, transport, terminal-wizard, and auth tests pass, including wrong-owner refusal, old-Gateway capability rejection without a request, browser/manual-input races, disconnect cleanup, cancellation, and saved-versus-applied reporting.
- Late-effect negative controls demonstrate that removing config `beforeCommit` or profile-order worker authority allows the forbidden write. The guarded cases preserve the prior state.
- Production TypeScript and the touched command/CLI/Gateway/agent test type shards pass.
- `pnpm build` passed on the auth-behavior revision `b7468f2f035f147351ad0595266c5ace3f90264b` and the import-wiring verification revision `84774791a74683b65cb351ec615a9f1ad6cf5946`. Live commands used the shipped `node openclaw.mjs` launcher against those frozen builds.
- On an isolated local Gateway, `models auth login-github-copilot` rendered `https://github.com/login/device` and a one-time code in the terminal. Repeating this on the final build exercised both lazy imports. Each flow was cancelled without authorizing an account; no Copilot credential was saved, and the Gateway PID remained unchanged.
- `models auth login --provider openai --method api-key`, with a real key supplied only on stdin, changed the isolated Gateway's available OpenAI models from 0 to 16. A real turn returned `AUTH_OWNER_OK` using a saved credential profile. The configured default and listener PID were unchanged; no restart was used.
- At the import-wiring verification revision, 20 focused CLI import/owner tests and the production typecheck passed. The production dead-export scan had no new findings; its remaining `InstalledCodexAppServer` finding also occurred on the repaired #168588 base. No baseline suppressions were added.
- After integrating the updated auth-none base, all 94 focused login tests pass. The new login case drives the registered command through the real auth resolver and verifies backend identity with `deviceIdentity: null`.

No overlap with protected maintainer changes was found on the touched paths.

**Merge danger:** reversible code change; credentials intentionally saved by users remain saved after a revert. The affected surface is system/agent provider login with a running local Gateway and the optional multi-request CLI transport lifetime.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
)

Related: openclaw#168588

## What Problem This Solves

Fixes: the generic-help login-gate browser test can time out waiting for the login screen while its own startup barrier is held.

## User Impact

No user-visible change. This repairs a Control UI test fixture without changing Gateway authentication, login behavior, timeouts, or assertions.

## Why This Change Was Made

The startup regression added in f86c2a9 holds the emitted Chat JavaScript chunk before waiting for the lazy login screen. That barrier can also prevent the login screen from becoming available, so the test never reaches the release.

Hold the existing route-only Chat stylesheet set instead. The test still observes `startupPending === true`, starts the no-error fixture before startup completes, and retains every collapsed-help and reveal assertion.

No overlap with designated maintainer changes was found in the changed file's history.

## Evidence

- Unchanged openclaw#168588 head `b61c1f05efbb1db980722db07e9feacf922afe0b`: the requested direct login-gate command passed twice (25/25 each).
- Clean main `3aa85968da2a24df2797f3a0f82610d19e5fa73f`: passed twice (25/25 each).
- Clean main `de225fcde8e78a9ea928a98381e35d6dccf80b2c`: failed twice (24 passed, the same generic-help `.login-gate` 30-second timeout each time).
- Focused old JavaScript-barrier negative control: reproduced the same timeout. Captured state showed `startupPending: true`, a stopped Gateway with `AUTH_TOKEN_MISSING`, and the connecting splash instead of the login screen.
- Focused stylesheet-barrier case: passed.
- Original-race negative control: temporarily removing the existing startup wait still fails with `Missing mounted login gate` using the repaired barrier; the wait was restored before final proof.
- Final direct browser run of `login-gate.e2e.test.ts` and `initial-connect-splash.e2e.test.ts`: **38/38 passed**.

Commands used the repository entry point:

```sh
node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner ui/src/e2e/login-gate.e2e.test.ts
node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner ui/src/e2e/login-gate.e2e.test.ts ui/src/e2e/initial-connect-splash.e2e.test.ts
```

Proof ran on macOS arm64 with Node 24.21.0 and local Playwright Chromium; it does not claim a Linux rerun of the entire hosted shard.

Merge danger: two-way door; reverting restores only the old test barrier. Blast radius is this single browser-test scenario; no production code or persisted state changes.

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

Related: openclaw#168135, openclaw#168108, openclaw#168471

## What Problem This Solves

Fixes API-key setup from the CLI when a running Gateway owns local state.

## User Impact

Users can run `openclaw models auth paste-api-key --provider <id>` without stopping the Gateway. The Gateway saves the key and refreshes its model catalog. Offline behavior is unchanged. An explicit, non-empty `--profile-id` still requires offline use.

## Why This Change Was Made

openclaw#168135 correctly stopped CLI processes from writing credentials around a live Gateway. It also kept CLI flows offline where the existing Gateway APIs could not preserve their behavior. Manual API-key setup already uses the same credential writer as `models.authSetApiKey`, so that subset can use the owner instead of refusing.

This change uses the canonical `local-state-owner.ts` route, as in openclaw#168108 and openclaw#168471. It binds the request to the discovered local owner and port, sends `expectedOwnerId`, requires `operator.admin`, rechecks ownership before dispatch, and never retries a possibly accepted write locally. API-key input is collected only after owner selection. The RPC checks the expected owner at credential and config writes; calls without that field retain their existing behavior. Owner-bound requests preserve the CLI's agent-selection rules.

Update behavior: an older Gateway that lacks `models-auth-set-api-key-owner-v1` is refused before the API-key request; update and restart it, or stop it and retry offline.

No request/response schema, new RPC method, config option, database schema, or paired-device fallback is added.

### Command-to-RPC mapping

| CLI command or option | Existing RPC | Result in this change |
| --- | --- | --- |
| `paste-api-key --provider <id> [--agent <id>]` | `models.authSetApiKey` | Delegate provider, key, and agent; print saved profile and any application warning. |
| `paste-api-key --profile-id <id>` | No profile-id field in `models.authSetApiKey` | Refuse this option with offline guidance. |
| `paste-token [--expires-in <duration>]` | No equivalent API-key write | Stay offline: token type and expiry must not become an API key. |
| `login`, including API-key plugin methods | `models.authLogin` and `wizard.*` | Stay offline: CLI method/profile/default/force semantics are not an exact manual-key mapping. |
| `login-github-copilot` | `models.authLogin` and `wizard.*` | Stay offline; device flow is outside this change. |
| `add` / `setup-token` | No exact generic mapping | Stay offline; these can run local provider CLI or import flows. |
| `list` | `models.authStatus` | Stay offline: the status projection lacks the CLI list's state-path, cooldown, disabled-state, and recovery fields. |
| `logout <profileId> [--yes]` | `models.authLogout` | Deferred; retain current offline behavior. |
| `order get` | `models.authStatus` | Deferred; retain the existing owner-aware read. |
| `order set <profileIds...>` | `models.authOrderSet` | Stay offline: the RPC requires the full profile order; the CLI allows partial lists. |
| `order clear` | `models.authOrderSet` | Deferred; retain offline reset behavior. |
| `activate <profileId>` | No exact test-and-activate mapping | Stay offline. |

## Evidence


ACP CI comparison: `src/gateway/server.chat.acp-completion.test.ts` passed all 12 cases when run directly on PR head `4f32198a3a8f5446e1c24b783d624884415553e6` and on clean main at its exact merge parent `e1b944d4a80ef3b4e0df75f1e324cb4a5ffc08dd`. The CI failure in `completes persistence failure after explicit abort once` expected `[start, end]` but received `[end]`; that case passed on both local runs. This does not establish an inherited failure or a PR-caused failure—it records that neither isolated run reproduced it. No code or test assertion was changed.


Latest review repair: removed only the stale `prepareDispatchCurrent` test expectation after openclaw#168882 retired that callback. Owner binding, capabilities, authentication, `assertDispatchCurrent`, and no-local-write assertions remain. The requested direct command `node scripts/run-vitest.mjs run src/cli/models-cli.state-owner.test.ts` passed all 16 tests (24.22 seconds total). No retired production callback was restored.

- The new CLI regression fails with the original main-branch auth router: 12 existing refusal cases pass, and API-key delegation fails with `OWNER_UNAVAILABLE`.
- The initial candidate passed 153 targeted tests across CLI ownership, the real API-key writer, Gateway transport, and the real API-key RPC.
- Tests cover cancelled input, no local fallback, old-Gateway capability refusal before request dispatch, and rejected owner changes without credential/config writes.
- Existing unbound API-key RPC requests still pass the real credential-writer test.
- `pnpm build` passed.
- Isolated live profile: piped a real OpenAI key into `pnpm openclaw --profile <profile> models auth paste-api-key --provider openai`. The Gateway picker changed from zero available OpenAI models to one. A real `openclaw agent` turn returned `AUTH_OWNER_OK`, using the saved auth profile. The listener PID stayed the same; no restart was needed.
- The Gateway token was supplied only at runtime and was not in config. The same CLI path worked when it received that token. Without the token, it refused without a local write and named `OPENCLAW_GATEWAY_TOKEN` / `OPENCLAW_GATEWAY_PASSWORD` as the next step.
- An earlier `node scripts/check-changed.mjs --staged` run passed the format, ownership, dependency, and other early guards, then stopped at main's UI-e2e test-root budget (722 versus 720). That result predates the empty-input regression below; no UI files are changed here.

### Review repair: authority at the final write

- The captured requester guard now reaches the auth store's existing SQLite worker admission, not only the updater callback. It also reaches config `beforeCommit` and the config writer's effect-time authority check.
- Credential observation: revoke after the real updater returns, before commit; the operation rejects, the original stored key remains, and config bytes do not change. The permitted control stores the replacement key.
- Config observation: revoke after the transform returns; the operation rejects and the source config remains byte-for-byte unchanged. The already saved, unchanged credential remains intact. The permitted control publishes the auth-profile config.
- The four allowed/revoked controls and 17 auth-store update tests pass. These tests use real credential/config persistence; only the revocation instant is controlled.
- Fixed the two `curly` lint errors in the CLI input adapter. Targeted production lint passes for the adapter, API-key writer, and auth-profile upsert owner.
- After merging main, the changed-file gate passed core typechecking and all 28 core test graphs. It stopped at unrelated unused exports in `extensions/codex/src/app-server/managed-binary.ts`, `tools/solid-lint/index.mjs`, and `ui/src/test-helpers/solid-application-context.tsx`; those files are unchanged by this PR.

### Review repair: configured loopback auth-none

- Owner-bound shared-auth requests now enable the transport's existing bounded auth-none path. A Gateway explicitly configured with `gateway.auth.mode: "none"` uses the backend client identity without creating or reading device credentials. Remote targets and URL overrides retain the existing refusal rules.
- A registered `paste-api-key` regression invokes the real `resolveGatewayCallDeviceAuth` with the owner route's options. It failed before the fix with `GatewayLocalBackendSharedAuthUnavailableError` and passes after the fix. All 105 transport tests and 16 CLI ownership tests pass.
- The latest main was merged after these focused checks. Clean-main export-name collision checking passed at `25b2400af13218f379b306a2e4cc504288f320eb`; the channel collision was fixed upstream by `2f395451b88`. The same clean main reproduced the three lint errors in the untouched plugin-state observation cache and SQLite comparison test. Remaining baseline runs were stopped at maintainer request while upstream CI repairs were being merged.

### Review repair: empty API-key input

- Empty or whitespace-only stdin now reports: `No API key was supplied. Rerun this command and paste a non-empty API key, or pipe one to stdin.`
- Two short tests read real streams and cover both inputs. Both failed with the old `Required` message and pass after this change.
- The changed-file gate passed formatting, core typechecking, and all six selected test graphs. It stopped at the unrelated `GatewayApprovalEventPublisherV2` unused export in `src/gateway/server-instance-runtime.types.ts`, which this repair does not modify.

### Existing CI failures checked on main

- On clean main `e99d1a8c933639bea9961f7731624eb1ef3f3615`, the UI cloud-startup toast-recovery case fails with the same `Control UI readiness hook is unavailable` error as this branch (two cases pass, one fails).
- The same clean main also reproduces the FIFO assertions missing `QUEUED_STEER_A` and `ORDINARY_MESSAGE_B`. Neither test nor its steer behavior is changed by this PR.
- The document-steer case also fails on clean main, but earlier: the initial turn does not reach the mock provider (zero requests). On this branch it reaches the later missing-document assertion. The baseline failure prevents an exact comparison of that later assertion; it is not claimed as an identical local reproduction.
- On the repaired head, [the Node shard](https://github.com/openclaw/openclaw/actions/runs/38082252267/job/114301617040) reports the same FIFO failures. A [separate cron shard](https://github.com/openclaw/openclaw/actions/runs/38082252267/job/114301616913) reports `hydrates runtime metadata for a reasoning-capable fallback candidate` (expected two calls, received four); its main-branch investigation is separate and no auth change is claimed to fix it.
- `src/cli/plugin-local-state-owner.test.ts` has the same result on this branch (`5033eb75ade`) and clean main (`45943833ee81802976d1e7ef0650d668b13b6f5a`): 33 pass, one fails. The failed case is `routes memory search limits and JSON output through the discovered owner`; both report `The memory runtime does not support CLI search` inside `OUTCOME_UNKNOWN`. The fixture supplies a manager but not the `searchForCli` callback now required by the Memory Core handler. This is a main-branch fixture mismatch, not an auth routing regression; no test or routing behavior was changed to hide it.

### CI 38113017692: pinned per-file comparison

Compared PR head `f062e5069509128680db873fa6643d262b034b0b` with its exact main parent `fece4b1cfc8b5778c0e8f69a8c9899f548038819`. Each file ran through the repository test runner under pueue.

| File | PR result | Main result | Verdict |
| --- | --- | --- | --- |
| `src/gateway/server-methods/models-auth-api-key.integration.test.ts` | 1 failed: corrupt config revision key during startup | Same | Inherited; failure occurs before the auth RPC or acknowledgment |
| `src/gateway/gateway-cli-plugin-routing.test.ts` | 1 failed: corrupt config revision key | Same | Inherited |
| `src/gateway/server-methods/sessions-mutations.sticky-model.test.ts` | 3 failed, 66 passed: two undefined-error assertions and an invalid transcript frame | Same | Inherited |
| `src/gateway/server.sessions.create-worktree-spawn.test.ts` | 1 failed, 18 passed: invalid transcript frame | Same | Inherited |
| `src/gateway/server/ws-connection/connect-device-pairing.test.ts` | 12 failed: corrupt config revision key | Same | Inherited |
| `src/gateway/session-message-events.test.ts` | Setup failed: corrupt config revision key; 30 skipped | Same | Inherited |
| `src/gateway/session-message-events.exec-completion.test.ts` | Setup failed: corrupt config revision key; 2 skipped | Same | Inherited |
| `src/gateway/session-message-events.history-worker.test.ts` | Setup failed: corrupt config revision key; 2 skipped | Same | Inherited |
| `src/gateway/sessions-history-http.physical-source.test.ts` | 4 failed: corrupt config revision key | Same | Inherited |
| `ui/src/pages/workboard/workboard-native-bundle.e2e.test.ts` | 2 passed (Chromium and WebKit) | Same | CI failure not reproduced on either revision |

The config-revision owner unit file also passes both tests on both revisions. The Gateway integration failures therefore do not establish an auth-specific `configRevisionHash`/`appliedConfigHash` regression: they stop while loading the installation revision key. No corruption check was weakened and no test was changed to bypass startup. Workboard's initial missing dependencies/browser artifact were repaired before the successful comparison runs.

No overlap with protected maintainer changes.

Two-way code change: a revert restores offline-only CLI setup. Keys saved through the Gateway remain saved. The affected paths are local CLI API-key setup and the existing Gateway API-key save handler.

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

Related: openclaw#168588, openclaw#168135

## What Problem This Solves

Fixes provider sign-in being refused by `models auth login` and `models auth login-github-copilot` while the local Gateway owns the selected state directory.

## User Impact

Supported OAuth, device-code, and plugin API-key methods use the running local Gateway. The terminal renders the Gateway's URLs, device codes, protected inputs, and model-access choices. Credentials stay with the Gateway; the CLI never writes around it or retries a failed login locally.

Options the existing login RPC cannot represent fail explicitly before sign-in starts. The current default model remains unchanged.

## Why This Change Was Made

The old CLI router treated every interactive login as an offline mutation. The Gateway already owns provider login and wizard sessions, but its start request lacked local-owner binding and the one-shot CLI transport closed the connection immediately after the start response.

Bind login to the discovered owner with an optional `expectedOwnerId` and `models-auth-login-owner-v1`. Retain one authenticated connection for the entire wizard, recheck the local owner before follow-up requests, and cancel/settle that session before releasing terminal resources. A disconnect closes the Gateway-owned login rather than reconnecting or replaying it. OAuth loopback callbacks run on the Gateway host, which is the same machine for this local-owner route.

The Gateway revalidates authority at credential, profile-order, and config publication boundaries. Requests without owner binding retain the Control UI behavior. Declared API-key methods run credential-only for the bound CLI request; this does not change administrator requirements or UI discovery.

| CLI input | Gateway mapping |
| --- | --- |
| `--provider`, `--method` | Select the exact declared plugin login choice; send its `authChoice` to `models.authLogin`. |
| Omitted provider/method | Choose the declared login method in the terminal. |
| `--agent` | Preserve inherited/leaf selection in `agentId`. |
| `--device-code` | Select method `device-code`; conflicting `--method` still refuses. |
| `login-github-copilot` | Select provider `github-copilot`, method `device`. |
| URLs, device codes, manual code, selections | Render wizard steps and send answers through `wizard.next` on the same connection. |
| `--profile-id`, `--force`, `--set-default`, Copilot `--yes` | Refuse before starting: the existing login RPC has no corresponding fields. Offline behavior remains available after stopping the Gateway. |

Methods requiring local provider-CLI import/setup or lacking a supported login declaration remain offline. The wizard result confirms saved/applied outcome; it does not return a per-login profile identifier.

**Update behavior:** no stored-data migration or protocol-version bump. An older Gateway without the method-specific capability receives no login request. Update/restart that Gateway, or stop it and rerun offline. Ambiguous transport outcomes remain `OUTCOME_UNKNOWN`; no local fallback is attempted.

Explicitly configured loopback Gateways with `gateway.auth.mode: "none"` also
support delegated login without a token or device identity. This uses the
existing bounded local-backend resolver, not an arbitrary-URL or remote bypass.

## Evidence

- Review repair at `d0b9c83a53d6e785c1dae0f97ea315718b1e1016`: 208 focused tests passed in 91.6 seconds with one worker. Scoped type-aware lint, production types, and the command/Gateway-method test type shards passed.
- A real `plugins.load.paths` fixture is discovered from the selected read-only config; disabling it or excluding it from the allowlist removes it. The discovery read creates no state database.
- Real Gateway/SQLite/config controls prove: an owner-bound login saves its credential and provider config; a non-admin caller is rejected without starting the provider; revoking the actual requester after asynchronous persistence-lock preparation leaves both credentials and config unchanged. Instrumentation calls the original handler and persistence function; no writer result is mocked.
- Discriminating negative controls fail when the selected config is omitted (provider disappears) or the pre-write authority callback is omitted (the real store receives the synthetic credential after revocation). Both controls were restored before the passing run.
- The unrelated transcript-library CI timeout also reproduces on clean main `c5029c5631d37c72df8c96007ccc29bc7db006f9`: two cases pass and the same `Loading meetings…` assertion at line 252 fails. No UI workaround or assertion change is included.

- On the latest input-guidance base, 26 focused tests pass, including real-stream empty/whitespace input checks and registered auth-none login through the real resolver.

- The two new CLI delegation regressions fail against the base CLI with `OWNER_UNAVAILABLE`, then pass with the owner route.
- Focused CLI, Gateway, transport, terminal-wizard, and auth tests pass, including wrong-owner refusal, old-Gateway capability rejection without a request, browser/manual-input races, disconnect cleanup, cancellation, and saved-versus-applied reporting.
- Late-effect negative controls demonstrate that removing config `beforeCommit` or profile-order worker authority allows the forbidden write. The guarded cases preserve the prior state.
- Production TypeScript and the touched command/CLI/Gateway/agent test type shards pass.
- `pnpm build` passed on the auth-behavior revision `b7468f2f035f147351ad0595266c5ace3f90264b` and the import-wiring verification revision `84774791a74683b65cb351ec615a9f1ad6cf5946`. Live commands used the shipped `node openclaw.mjs` launcher against those frozen builds.
- On an isolated local Gateway, `models auth login-github-copilot` rendered `https://github.com/login/device` and a one-time code in the terminal. Repeating this on the final build exercised both lazy imports. Each flow was cancelled without authorizing an account; no Copilot credential was saved, and the Gateway PID remained unchanged.
- `models auth login --provider openai --method api-key`, with a real key supplied only on stdin, changed the isolated Gateway's available OpenAI models from 0 to 16. A real turn returned `AUTH_OWNER_OK` using a saved credential profile. The configured default and listener PID were unchanged; no restart was used.
- At the import-wiring verification revision, 20 focused CLI import/owner tests and the production typecheck passed. The production dead-export scan had no new findings; its remaining `InstalledCodexAppServer` finding also occurred on the repaired openclaw#168588 base. No baseline suppressions were added.
- After integrating the updated auth-none base, all 94 focused login tests pass. The new login case drives the registered command through the real auth resolver and verifies backend identity with `deviceIdentity: null`.

No overlap with protected maintainer changes was found on the touched paths.

**Merge danger:** reversible code change; credentials intentionally saved by users remain saved after a revert. The affected surface is system/agent provider login with a running local Gateway and the optional multi-request CLI transport lifetime.
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: web-ui App: web-ui cli CLI command changes commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime 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. security-sensitive-changed size: M 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.

1 participant