Skip to content

fix: local gateway connections recover after listener or token drift#1053

Draft
bkudiess wants to merge 2 commits into
openclaw:mainfrom
bkudiess:bkudiess-connection-analysis
Draft

fix: local gateway connections recover after listener or token drift#1053
bkudiess wants to merge 2 commits into
openclaw:mainfrom
bkudiess:bkudiess-connection-analysis

Conversation

@bkudiess

@bkudiess bkudiess commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes an issue where users connected to a setup-managed local WSL gateway could
be left in misleading re-pair/token states or unstable reconnect loops when a
stale native gateway owned the local port, the WSL gateway was wedged, or a
role-specific device token drifted.

Why This Change Was Made

This makes GatewayConnectionManager the canonical operator/node lifecycle and
user-intent owner, adds a shared local-listener provenance service, and adds a
bounded managed-WSL repair monitor/coordinator. Strong shared/bootstrap
credentials are sent only after the expected local gateway owner is proven;
unknown listeners are never killed, and explicit Disconnect/Stop intent is
never overridden by automatic repair.

The old owners were scattered UI/client reconnect paths and best-effort port
diagnostics. The new owners are the connection manager for lifecycle and
credential recovery, ManagedLocalGatewayPortProvenanceService for endpoint
identity/remediation, and the monitor/coordinator for bounded automatic repair.

User Impact

Setup-managed local gateways now recover automatically from stale listener
collisions, WSL service/VM failures, and role-specific device-token mismatch.
When ownership cannot be proven, the UI reports a local port conflict instead
of incorrectly asking the user to re-pair.

Evidence

  • Repeated native-vs-WSL fault injection removed only the proven obsolete
    OpenClaw native listener, left the task disabled, restored signed
    wslrelay.exe ownership in about 50 seconds, returned the WSL systemd gateway
    to active, and refreshed LastConnected.
  • Final fault-injection trial removed native PID 42840 and restored the expected
    relay without terminating an unknown process.
  • Current host state after rebase: 127.0.0.1:18789 is owned by
    C:\Program Files\WSL\wslrelay.exe (PID 38548);
    OpenClawGateway is active/running (MainPID 483).
  • Feature head 9d418433 launched successfully in isolated mode and remained
    responsive as PID 41088.
  • Current PR head c2e13727 completed the real fresh-distro setup/connect,
    revocation-recovery, and network-recovery E2E shards. This also proved signed
    wslrelay verification under a PowerShell 7 parent and dual-stack Windows
    relay projection onto the expected systemd-owned WSL socket.
  • Final adversarial sign-off on the feature snapshot: GPT-5.6 Sol max 96/100,
    Claude Opus 4.8 95/100, Gemini 3.1 Pro 100/100; no material findings.
  • Post-rebase rubber-duck review of the four upstream-overlap surfaces found no
    material blockers and confirmed model-catalog, settings, exec-approval, and
    connection-recovery behavior remain wired.

Change Type

  • Bug fix
  • Feature
  • Refactor
  • Docs or instructions
  • Tests or validation
  • Security hardening
  • Chore or infrastructure

Scope

  • Tray or WinUI UX
  • Windows node capability
  • Local MCP or winnode
  • Gateway, connection, or pairing
  • Setup or onboarding
  • Permissions, privacy, or security
  • Tests, CI, or docs

Validation

  • .\build.ps1
    • All five projects built successfully.
  • dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore
    • 3,241 passed, 31 skipped, 0 failed.
  • dotnet test .\tests\OpenClaw.Connection.Tests\OpenClaw.Connection.Tests.csproj --no-restore
    • 496 passed, 0 failed.
  • dotnet test .\tests\OpenClaw.SetupEngine.Tests\OpenClaw.SetupEngine.Tests.csproj --no-restore
    • 698 passed, 0 failed.
  • dotnet test .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj --no-restore
    • 2,000 passed, 0 failed.
  • Unit/closeout total: 6,435 passed, 31 skipped, 0 failed.
  • CI E2E shards:
    • Setup/connect and MXC: 18 passed, 0 failed.
    • Network recovery: 2 passed, 0 failed.
    • Revocation recovery: 1 passed, 0 failed.

Known telemetry listener tests flaked transiently during exploratory runs.
Their isolated reruns passed, and the complete required closeout rerun passed.

Real Behavior Proof

  • Environment tested: Windows 11 host, WSL2 OpenClawGateway, setup-managed
    loopback gateway on port 18789.
  • PR head or commit tested: c2e13727.
  • Exact steps or command run: launched
    .\run-app-local.ps1 -NoBuild -AllowNonMain -Isolated; inspected the
    address-specific Windows listener and WSL systemd service; repeated controlled
    native-listener collision/recovery trials before the mechanical rebase; ran
    all three CI setup E2E filters on the current head.
  • Evidence after fix: isolated PR-head app remained responsive; expected signed
    relay owns the loopback listener; WSL service is active/running; controlled
    collisions self-repaired without sending strong credentials to or killing an
    unproven owner; current-head fresh-distro setup, revocation, network recovery,
    and keepalive idempotence all passed.
  • Observed result: managed-local connection health recovers, while explicit
    user intent and unknown-listener safety remain authoritative.
  • Screenshot or artifact links verified? (Yes/No/N/A): N/A; copied
    terminal/runtime evidence is included above.
  • Not verified or blocked: current-head non-isolated launch was blocked by the
    global singleton already owned by another worktree (PID 2496), which was not
    terminated. Current-head runtime behavior was instead exercised through the
    real fresh-distro E2E shards; non-isolated collision recovery was exercised
    repeatedly on the identical feature snapshot before the conflict-free rebase.

Security Impact

  • New permissions or capabilities? (Yes/No): No.
  • Secrets or tokens handling changed? (Yes/No): Yes.
  • New or changed network calls? (Yes/No): Yes, local listener/provenance and
    reconnect probes only.
  • Command or tool execution surface changed? (Yes/No): Yes, bounded repair
    can restart the expected WSL service/VM and disable/stop only a fully proven
    obsolete OpenClaw native task/process.
  • Data access scope changed? (Yes/No): No.
  • If any answer is Yes, explain the risk and mitigation: shared/bootstrap
    credentials are now gated by complete Windows IPv4/IPv6 listener capture,
    signed relay, expected-distro systemd MainPID target-port ownership, and
    listener recapture. Destructive remediation additionally proves native
    task/profile/process lineage and PID start identity. Unknown owners fail closed.

Compatibility and Migration

  • Backward compatible? (Yes/No): Yes.
  • Config or environment changes? (Yes/No): No.
  • Migration needed? (Yes/No): Yes, automatic only.
  • If yes, list the exact upgrade steps: none. Existing setup-managed Release,
    Dev, direct-override, and legacy Local (<distro>) records are migrated or
    resolved in place.

Review Conversations

  • I replied to or resolved every bot review conversation addressed by this PR.
  • I left unresolved only conversations that still need maintainer judgment.

Add trusted endpoint provenance, role-aware credential recovery, explicit operator intent, and bounded managed-WSL repair so local gateway failures recover safely without leaking stronger credentials or overriding disconnects.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. labels Jul 24, 2026
@clawsweeper

clawsweeper Bot commented Jul 24, 2026

Copy link
Copy Markdown

Codex review: needs maintainer review before merge. Reviewed July 24, 2026, 4:35 PM ET / 20:35 UTC.

ClawSweeper review

What this changes

This PR adds verified local-listener ownership checks, role-specific device-token recovery, and bounded automatic WSL gateway repair for setup-managed local connections.

Merge readiness

Blocked until stronger real behavior proof is added - 5 items remain

Keep this draft open for human review. It introduces a large, security-sensitive local-gateway recovery path, and the supplied evidence does not independently demonstrate the exact-head non-isolated repair flow or its upgrade behavior.

Priority: P2
Reviewed head: 9d418433416905f1813def7e0bbe8f760af4a074
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The patch includes substantial targeted coverage and a coherent safety design, but reviewer confidence is capped by missing inspectable current-head real-behavior proof for the central recovery path.
Proof confidence 🦪 silver shellfish (2/6) Needs stronger real behavior proof before merge: The PR body describes terminal and runtime results, but it contains no inspectable redacted transcript, log artifact, or recording that proves the exact-head non-isolated listener-conflict recovery path after the rebase. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The PR body describes terminal and runtime results, but it contains no inspectable redacted transcript, log artifact, or recording that proves the exact-head non-isolated listener-conflict recovery path after the rebase. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 4 items Broad lifecycle and credential change: The PR changes 58 files with 6,135 additions across connection state, gateway records, setup pairing, browser proxy authorization, WSL lifecycle control, and tray recovery UI.
Credential boundary coverage: The branch adds provenance-gating tests for interactive credentials, browser proxy requests, setup pairing, and reconnect authorization, showing that credential disclosure is an intentional security boundary.
Automatic repair changes persisted behavior: The branch adds an enabled-by-default persisted auto-repair setting and migration/preservation behavior for managed-local gateway records, so upgrade behavior needs explicit review.
Findings None None.
Security None None.

How this fits together

The tray connects operator and Windows-node clients to configured gateways using records and credentials stored locally. This patch inserts listener-provenance checks before credential use and reconnects, then uses bounded WSL repair and connection UI recovery states when a setup-managed local gateway fails.

flowchart LR
  A[Gateway record and credentials] --> B[Connection manager]
  B --> C[Local listener provenance check]
  C --> D{Verified managed WSL gateway?}
  D -->|Yes| E[Reconnect or bounded WSL repair]
  D -->|No| F[Local port conflict]
  E --> G[Operator and node connection state]
  F --> G
  G --> H[Connection recovery UI]
Loading

Decision needed

Question Recommendation
Should this repository accept enabled-by-default automatic WSL restart and verified native-process remediation as part of the managed-local gateway connection contract? Accept the bounded recovery contract: Approve the default-on repair path after reviewing exact-head evidence that verifies process provenance, credential gating, user disconnect intent, and upgrade behavior.

Why: The patch creates a new autonomous recovery capability that can restart a WSL distro and stop a process after provenance checks; code review alone cannot determine whether that operational and security boundary matches maintainer policy.

Before merge

  • Resolve merge risk (P1) - Existing setup-managed local records are migrated and preserved differently, so upgrades need proof that manual localhost records, legacy records, SSH records, and explicit disconnect intent retain their prior behavior.
  • Resolve merge risk (P1) - The new provenance service governs when shared or bootstrap credentials may be sent and when an app-owned process can be stopped; false classification could either block healthy users or weaken the intended credential boundary.
  • Resolve merge risk (P1) - Automatic WSL restart and port-conflict remediation change runtime behavior outside the normal connection loop, and the exact PR head has not supplied inspectable evidence for the non-isolated repair scenario.
  • Complete next step (P2) - The remaining blocker is maintainer acceptance of the autonomous lifecycle and security boundary, plus contributor-supplied real behavior evidence, rather than a narrow mechanical repair.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Changed surface 58 files, 6,135 added, 135 removed The patch spans connection lifecycle, credential handling, setup, tray UI, persisted settings, and tests.
New recovery components 5 added production files New listener-provenance and managed-local repair components establish a substantial new runtime ownership boundary.

Merge-risk options

Maintainer options:

  1. Add current-head recovery proof (recommended)
    Provide a redacted non-isolated current-head fault-injection transcript or recording that shows the detected listener, provenance decision, repair action, reconnect, and preserved explicit disconnect behavior.
  2. Accept the new recovery contract
    A maintainer may accept the upgrade and operational risk if enabled-by-default automatic repair is the intended supported contract.
  3. Split autonomous remediation
    Pause the autonomous WSL restart and process-remediation portion if maintainers want the credential-provenance work to land without a new automatic lifecycle contract.

Technical review

Best possible solution:

Keep a narrowly scoped, fail-closed provenance boundary, then provide redacted current-head fault-injection evidence plus explicit fresh-install and upgrade coverage before deciding whether to accept automatic WSL repair as a default behavior.

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

No high-confidence independent reproduction was completed in this review. The source and PR body define a concrete Windows plus WSL fault-injection path, but the supplied current-head proof is summary-only and the reported non-isolated run was blocked.

Is this the best way to solve the issue?

Unclear. The design attempts to centralize lifecycle and provenance safely, but its default-on autonomous restart and remediation policy needs maintainer approval and exact-head upgrade proof before it can be called the best solution.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against f50af187865c.

Labels

Label justifications:

  • P2: This is a substantial local-gateway reliability and security-boundary improvement with meaningful but bounded user impact.
  • merge-risk: 🚨 compatibility: The patch changes persisted managed-local gateway migration, preservation, reconnect behavior, and a defaulted setting for existing users.
  • merge-risk: 🚨 auth-provider: It changes when device, shared, and bootstrap credentials may be used and how device-token mismatch recovers.
  • merge-risk: 🚨 security-boundary: It makes local listener provenance authoritative before credential disclosure and before stopping a proven obsolete process.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR body describes terminal and runtime results, but it contains no inspectable redacted transcript, log artifact, or recording that proves the exact-head non-isolated listener-conflict recovery path after the rebase. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

Likely related people:

  • bkudiess: The supplied PR history identifies this contributor as the author of the connection-recovery implementation; current-main feature ownership could not be established from the available read-only inspection. (role: proposed implementation contributor; confidence: low; commits: 9d4184334169; files: src/OpenClaw.Connection/GatewayConnectionManager.cs, src/OpenClaw.Connection/ManagedLocalGatewayPortProvenanceService.cs, src/OpenClaw.Tray.WinUI/Services/ManagedLocalGatewayRepairCoordinator.cs)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Post a redacted current-head runtime transcript or recording of the non-isolated fault-injection recovery, including listener provenance and successful reconnect.
  • Document or demonstrate upgrade behavior for legacy, managed-local, manually configured localhost, and SSH-backed gateway records.
  • Obtain maintainer confirmation that default-on automatic WSL restart and proven-process remediation are acceptable product and security boundaries.

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.

Preserve WSL shell variables through stdin, isolate the Windows PowerShell module path for Authenticode verification, and account for relay family translation. Update the keepalive E2E contract to recognize an already-proven setup keepalive without spawning a duplicate.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@clawsweeper

clawsweeper Bot commented Jul 24, 2026

Copy link
Copy Markdown

ClawSweeper status: review started.

I am starting a fresh review of this pull request: fix: local gateway connections recover after listener or token drift This is item 1/1 in the current shard. Shard 0/1.

This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. P2 Normal priority bug or improvement with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant