Repository navigation
Conversation
Native onboarding stored an operator device token, reused the same identity on every retry, and had no path back when that token stopped verifying. The Gateway answered the operator connect with AUTH_DEVICE_TOKEN_MISMATCH and setup surfaced only a generic "Could not connect" error. None of the four recovery actions (Open Terminal, Restart Gateway, Restart AI, Cancel Setup) cleared the rejected credential, so setup could not complete again. The staged setup connection now keys off the typed GatewayErrorKind the client raises before the terminal error status. On an authoritative DeviceTokenMismatch, where a device token was actually sent and pairing is allowed, it retires exactly that credential once and reconnects with the shared setup token, letting the unchanged device identity re-pair. - DeviceIdentity.TryClearDeviceTokenForRoleIfMatches compares and clears under the identity file lock, so a token another connection refreshed in the meantime is never discarded. The keypair and device id are preserved. - NativeGatewaySetupSession budgets one recovery per staged session and re-verifies gateway ownership and the setup credential before clearing anything, so a token is never retired because an unverified listener rejected it. - Recovery never runs on the finalization path (allowPairing: false). GatewayConnectionManager already recovered from this error kind; onboarding did not. This closes that asymmetry. No UI changes. Co-authored-by: Copilot <[email protected]>
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed October 7, 2026, 4:20 PM ET / 20:20 UTC (Revision 7). ClawSweeper reviewWhat this changesNative Gateway onboarding clears an exactly matching rejected operator device token once, rechecks Gateway authority, and retries pairing with the setup credential while preserving the device identity. Merge readiness✅ Ready for maintainer review This PR remains necessary: current main and the latest release lack onboarding recovery for a rejected stored device token. The reviewed patch has sufficient affected-device proof, passing exact-head Windows validation, and no identified blocking defect. Priority: P0 Review scores
Verification
How this fits togetherCompanion's native onboarding opens an authenticated operator connection to its packaged Gateway before configuring AI. The staged setup session verifies the Gateway and credentials, manages pairing, and supplies the connection used by the setup screens. flowchart TD
A[Native onboarding] --> B[Stored device credential]
B --> C[Verified Gateway connection]
C --> D{Device token rejected?}
D -->|No| G[Continue AI setup]
D -->|Yes| E[Recheck ownership and setup credential]
E --> F[Clear matching token once and retry pairing]
F --> C
Before mergeNone. Agent review detailsSecurityNone. Review metrics
Technical reviewBest possible solution: Keep automatic recovery inside the staged native setup owner, preserving valid credentials and requiring current Gateway authority before retrying pairing. Do we have a high-confidence way to reproduce the issue? Yes. Current-main source shows a rejected stored device token repeatedly reaches the generic setup failure, and the supplied failing regression plus affected-device before/after captures corroborate that path; this review did not execute it. Is this the best way to solve the issue? Yes. Recovery belongs in the existing staged native connection/session owners, and exact-token comparison plus recovery-time authority checks narrowly address the failure without changing valid-token behavior. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 5e3fb40bcc89. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (6 earlier review cycles)
|
Close the review ask that recovery must be fail-closed at the moment it runs, not only at connect time. - Recovery_IsRefusedAndRetiresNothingWhenGatewayOwnershipFailsVerification: an endpoint that fails ownership verification must not cause the stored device token to be cleared. - Recovery_IsRefusedAndRetiresNothingWhenSetupCredentialChanged: a changed isolated port/token must abort recovery before any credential is sent. - Recovery_IsBudgetedOncePerStagedSession: recovery is consumed at most once per staged session, so a hostile peer cannot drive repeated token clears. Mutation-checked: removing the AuthorizeCoreAsync call from RecoverRejectedOperatorTokenAsync fails the ownership test. Co-authored-by: Copilot <[email protected]>
The native-onboarding recovery controls called RecoverRejectedOperatorTokenAsync directly, so they never proved that a real rejected connection reaches recovery or that fallback transmission and pairing stay closed on the production path. Both controls now drive NativeGatewaySetupConnection.ConnectAsync. A new FixtureGatewayServer.DeviceTokenRejected hook changes the endpoint authority after the gateway rejects the stored device token, so staged authorization still succeeds and recovery is genuinely entered before it fails closed. New SharedCredentialConnects and DeviceTokenRejections counters let the tests assert that no shared credential was transmitted and no pairing was approved. Mutation checked: deleting the recovery-time authority re-verification fails both controls. Co-authored-by: Copilot <[email protected]>


What Problem This Solves
Fixes: native onboarding stops with a generic "Could not connect" error when the Gateway no longer honors the operator device token Companion stored during an earlier attempt.
User Impact
User impact: onboarding now retires the rejected credential and re-pairs automatically with the shared setup token, instead of leaving the user stuck on a setup run that can never succeed again. There is no UI change.
Why This Change Was Made
Onboarding stored an operator device token, reused the same
GatewayIdand identity directory on every retry, and had no path back once that token stopped verifying. The Gateway answered the operator connect withAUTH_DEVICE_TOKEN_MISMATCH, whichNativeGatewaySetupConnectioncollapsed into one generic failure. Nothing in the flow could clear the credential: draft deletion only happens on a package-family or contract mismatch, and all four on-screen recovery actions (Open Terminal, Restart Gateway, Restart AI, Cancel Setup) reconnect with the same stale token or dispose the session without deleting the draft.The staged setup connection now keys off the typed
GatewayErrorKindthe client raises before the terminal error status, rather than error text, soAUTH_TOKEN_MISMATCHstill reads as a shared-auth failure. On an authoritativeDeviceTokenMismatch, where a device token was actually sent and pairing is allowed, it retires exactly that credential once and reconnects with the shared setup token, letting the unchanged device identity re-pair.Guardrails:
DeviceIdentity.TryClearDeviceTokenForRoleIfMatchescompares and clears under the existing identity file lock, so a token another connection refreshed in the meantime is never discarded. The Ed25519 keypair, device id, and unrelated role tokens are preserved.NativeGatewaySetupSessionbudgets one recovery per staged session and re-runsAuthorizeCoreAsyncplus the pairing-configuration checks before clearing anything, so a token is never retired because an unverified listener rejected it.allowPairing: false).GatewayConnectionManageralready recovered from this exact error kind viaTryScheduleOperatorTokenRecoveryAsync; onboarding never got the equivalent. This closes that asymmetry.This is independent of the isolated-session replacement work in openclaw/openclaw-windows-packaging#157 and #1649. Those restore a missing Gateway config after Windows replaces a stale session; this one handles a Gateway that is already configured, running, and listening but rejects the device pairing credential. No files overlap.
Evidence
Head:
e2e68340Regression proof, with the two
src/OpenClaw.SetupEnginechanges stashed and the tests left in place:That is the reported symptom, reproduced. With the fix applied the same test passes, and the negative control
AcceptedOperatorDeviceToken_IsPreservedAcrossSetupConnectpasses both with and without the fix.FixtureGatewayServergained the minimum needed to express this: anAcceptedDeviceTokenproperty, so a connect carrying any other device token is answered withAUTH_DEVICE_TOKEN_MISMATCH. A connect presenting a device token is judged on that credential alone, matching howSelectConnectCredentialsends it.NativeGatewaySetupUxContractTestspreviously pinned the literalallowPairing && attempt == 0. It now pins the stronger invariants: pairing and recovery are each budgeted once, recovery requires the typedDeviceTokenMismatch, and the retry loop still precedes client construction.Negative controls
Three tests pin that recovery is fail-closed at the moment it runs, not only at connect time. Addressing review feedback, the two authority controls now drive the production
NativeGatewaySetupConnection.ConnectAsyncpath end to end rather than callingRecoverRejectedOperatorTokenAsyncdirectly:Recovery_IsRefusedThroughConnectWhenGatewayOwnershipFailsVerification: the endpoint stops verifying as the managed Gateway after it rejects the stored token.Recovery_IsRefusedThroughConnectWhenSetupCredentialChanged: the isolated port or setup token rotates after the rejection.Recovery_IsBudgetedOncePerStagedSession: recovery is consumed at most once, so a hostile peer cannot drive repeated token clears.The first two use a new
FixtureGatewayServer.DeviceTokenRejectedhook that fires server-side immediately beforeAUTH_DEVICE_TOKEN_MISMATCHis returned. Changing the authority at that instant means staged authorization still succeeds, a real rejected connection occurs, and recovery is genuinely entered before it fails closed. Each asserts, on the real connect path:DeviceTokenRejections == 1: the gateway actually rejected the stored token.SharedCredentialConnects == 0: no fallback credential was transmitted.fixture.Host.ApprovedIdis null: no pairing was approved.Mutation-checked: deleting the recovery-time
AuthorizeCoreAsync/RequireIsolatedPairingConfigurationAsync/RequirePairingConfigurationre-verification fails both controls, so they test the guard rather than passing incidentally.Change Type
Scope
winnodeRequired proof pools
none: no named pool covers native (MSIX isolated-session) Gateway pairing recovery.windows-wsl-gateway-e2eis the closest, but this diff is reachable only throughNativeGatewaySetupConnectionon the native path and is never exercised by WSL setup. Affected-device before/after screenshots and exact-head production-path recovery controls are included below under Real behavior proof; independent internal live-trace limits are explicitly tracked there.Validation
Independent hosted Windows validation at
e2e68340c829562be3cc296fb24dfae782c84d75: Build and Test run 37556482198 completed successfully, including all six product lanes and CI Gate. Core/CLI, Tray/setup/integration, UI/accessibility, setup/connect E2E, revocation recovery E2E, and network recovery E2E are green../build.ps1: all 5 projects succeeded.dotnet test ./tests/OpenClaw.Shared.Tests/OpenClaw.Shared.Tests.csproj --no-restore: 4232 passed, 0 failed, 35 skipped.dotnet test ./tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj --no-restore: 3893 passed, 0 failed.dotnet test ./tests/OpenClaw.SetupEngine.Tests/OpenClaw.SetupEngine.Tests.csproj --no-restore: 2285 passed, 0 failed, 1 skipped.dotnet test ./tests/OpenClaw.Connection.Tests/OpenClaw.Connection.Tests.csproj: 1560 passed, 0 failed, 1 skipped.Notes on the run:
OPENCLAW_REPO_ROOTmust be set or three unrelatedProviderArtworkSourceContractTestsfail with "Set OPENCLAW_REPO_ROOT for linked-worktree source contracts". OnePublishedVerifierEnforcesRecoveryAndModelPhaseTokens(blockModel: True)timeout appeared under full-suite load and passed on rerun; it is a pre-existing timing flake unrelated to this diff.Real behavior proof
Production-path regression proof
e2e68340c829562be3cc296fb24dfae782c84d75.OPENCLAW_REPO_ROOT=/tmp/openclaw-node-pr1651-rfr dotnet test tests/OpenClaw.SetupEngine.Tests/OpenClaw.SetupEngine.Tests.csproj --filter FullyQualifiedName~NativeGatewaySetupConnectionTests --logger 'console;verbosity=minimal': 32 passed, 0 failed, 0 skipped.OPENCLAW_RUN_INTEGRATION=1 dotnet test tests/OpenClaw.Shared.Tests/OpenClaw.Shared.Tests.csproj --no-build --filter 'FullyQualifiedName~DeviceIdentityIntegrationTests|FullyQualifiedName~DeviceIdentityUnitTests': 30 passed, 0 failed, 0 skipped, including the exact-token clear regression.5e3fb40bcc8936a44015de18fac2f5b35a4fb2acon the same macOS host. They are not counted as passing validation; Windows hosted validation is tracked separately.NativeGatewaySetupConnection.ConnectAsyncwith the real Gateway WebSocket client. A rejected stored operator token is retired, the client reconnects with the shared setup credential, and the setup transport connects.Affected-device live proof
Natalie reported building this branch locally on the machine experiencing the failure, then supplied side-by-side before/after captures. The hosted PR head remained
e2e68340when this evidence was inspected. This is contributor-reported branch-build provenance, not an independently captured executable hash.Both links returned HTTP 200 image/png and were visually inspected by the maintainer on October 7. The changed setup state and completed setup are visible, not merely an adjacent screen.
The October 7 diagnostic bundle independently shows four healthy native Gateway starts and seven operator handshakes rejected with
authProvided=device-token,hasDeviceIdentity=true, andauthReason=device_token_mismatch. The package is Store Gateway2026.9.701.0, packaginge707def0bc063bdfd06e6dbc2257c23182a75ce9, payload OpenClaw2026.9.5atec9c1a13db8938e5a3eaa51fca2e981cde2395a9, and the client advertises Companion2026.9.8. This is distinct from the missing-config/session-replacement defects addressed by Windows Node #1649 and packaging #157.Not verified / blocked
No independent live trace records the internal recovery branch on Natalie's machine, and her screenshots do not embed an executable SHA. The visible affected-device before/after result is contributor-supplied; exact-head internal recovery and authority controls are covered by production-path tests. Historical dev-machine attempts entered the already-existing runtime recovery path instead of onboarding, so they are not counted as proof of this change.
Security Impact
Yes/No): NoYes/No): YesYes/No): NoYes/No): NoYes/No): NoYes, explain the risk and mitigation: the change deletes a local credential, so the risk is an attacker provoking credential loss or downgrade. Mitigations: recovery runs only on the authoritativeAUTH_DEVICE_TOKEN_MISMATCHcode, only when a device token was actually sent, only when pairing is allowed, and at most once per staged session. Gateway ownership and the setup credential are re-verified before the clear, so an unverified listener cannot trigger it. The clear is a compare-and-swap under the identity file lock against the exact rejected value, so a concurrently refreshed token survives. Only the operator role token is removed; the keypair, device id, and node token are untouched, and no credential is logged or transmitted anywhere new.Compatibility and Migration
Yes/No): YesYes/No): NoYes/No): NoReview Conversations