Skip to content

fix(setup): local gateway removal fails or leaves stale records during uninstall - #1954

Merged
RomneyDa merged 3 commits into
openclaw:mainfrom
MertBasar0:fix/uninstall-powershell-automatic-variables
Nov 5, 2026
Merged

RomneyDa merged 3 commits into
openclaw:mainfrom
MertBasar0:fix/uninstall-powershell-automatic-variables

Conversation

@MertBasar0

@MertBasar0 MertBasar0 commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1953

What Problem This Solves

Fixes: removing the local WSL gateway during uninstall reports failure after the gateway is already deleted when OPENCLAW_STATE_DIR is set, and leaves stale gateway records and tokens in other cases.

User Impact

User impact: choosing to remove the local gateway now finishes cleanly when OPENCLAW_STATE_DIR is set, and it removes older local gateway records instead of leaving Companion pointed at a deleted gateway.

Behavior to review: three cleanup steps that never ran now run, each matching existing intent.

  • Older local records (no setupManagedDistroName, friendly name Local (<distro>), loopback URL) and their identity directories are removed.
  • Root device tokens are cleared when only local or loopback records remain, which is what the README already documents. A user with an isLocal: false loopback record may need to pair again.
  • With OPENCLAW_STATE_DIR set, exec-approvals.json in that directory is deleted. TrayArtifactCleanup already does this on the C# uninstall path.

Why This Change Was Made

Uninstall-LocalGateway.ps1 assigned to $host and declared a $Home parameter. Both are read-only automatic variables in PowerShell, so Test-LocalGatewayUrl always returned false and Expand-ExecApprovalsHomePath always threw. This renames them, and applies the same rename to the copy in validate-wsl-gateway-uninstall.ps1.

Fixing the name exposed one more defect in the same check: Windows PowerShell 5.1 runs on .NET Framework, whose Uri.Host returns [::1] in its expanded form, so IPv6 loopback still failed to match. The new test caught this, and the check now accepts that form.

Evidence

Real script under Windows PowerShell 5.1, against a throwaway empty distro created with wsl --import, with OPENCLAW_STATE_DIR set. The distro is really unregistered in both runs:

Before (a4dd026) After (this PR)
Script exit code 1 0
Distro still registered No No
gateways.json records left managed none
Identity directory left Yes No
Root device tokens left Yes No
Legacy exec-approvals.json left Yes No
uninstall-gateway-result.json succeeded=False, Cannot overwrite variable Home... succeeded=True, Local WSL gateway '<distro>' removed.

The new tests fail on a4dd026 for the intended reasons (6 of 6, for example every URL classified False, and 2|True|0 records instead of 1|False|0), and pass with the fix.

Through the real Inno uninstaller. Unsigned Dev-variant installers from scripts/build-inno-local.ps1 -Dev, differing only in the script, with unins000.exe /VERYSILENT and OPENCLAW_STATE_DIR set. A registered throwaway OpenClawGateway-Dev distro was really removed in both runs, next to one managed, one remote and one SSH-tunneled record:

Before (a4dd026 script) After (this PR)
Inno log cleanup script exited with code 1, continuing without deleting generated state exited with code 0, completed successfully, Deleted generated app state
Managed record and identity Left, still activeId Removed, activeId cleared
Remote and tunnel records and identities Kept Kept
Root device tokens (external records remain) Kept Kept
Unrelated setting (Theme, EnableNodeMode) Kept Kept
Legacy Token in settings.json Left Removed
exec-approvals.json (state dir and app data) Left Removed
Install folder Left Removed

Existing data. RegistryCleanup_LeavesUnrelatedRecordsLoadableByGatewayRegistry writes a registry with the production GatewayRegistry, runs the cleanup under Windows PowerShell 5.1, and reloads it with GatewayRegistry. The remote record (non-ASCII name, shared token, lastConnected, V2 flag) and the tunnel record (SSH config, browser port) come back equal, the active record stays, and only the managed identity is gone. This cleanup already rewrites gateways.json for current managed records; this PR adds no new stored format or field.

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

Required proof pools

  • windows-clean-installer-upgrade: the uninstall path changed. Not run here; it needs exact signed artifacts.

Validation

Run on a4dd026 plus this change. Windows 11 x64 build 26200, tr-TR, .NET SDK 10.0.402.

  • ./build.ps1: all builds succeeded (Shared, WinUI, SetupEngine, Cli, WinNodeCli), documentation validation passed.
  • dotnet test ./tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj --no-restore, with the OPENCLAW_TRAY_* data directories isolated, including the new compatibility test: 4806 passed, 0 failed, 0 skipped.
  • dotnet test ./tests/OpenClaw.Shared.Tests/OpenClaw.Shared.Tests.csproj: 4806 passed, 2 failed, 26 skipped. This PR changes no Shared code or Shared tests, and both failures come from this host:
    • ExecReusableCommandBinderTests.PinnedCarrier_IgnoresShadowInsertedAfterApproval: expects the computer name truncated to 15 characters, and this host's name is longer.
    • MxcFolderAdmissionTests.OwnedJunctionAndSymbolicLinkAreRejectedWithoutFollowingTheirChildren(symbolic: True): the account does not hold the symbolic link privilege.
  • git diff --check: clean.
  • validate-wsl-gateway-uninstall.ps1 has 0 parse errors under PowerShell 7. It has 4 under Windows PowerShell 5.1 on this host, the same 4 without this change, so that script was not run end to end.

The harness that loads production functions from the script moved from UninstallOnboardingSettingsTests into UninstallScriptHost so the new tests reuse it. Those existing tests still pass.

Real Behavior Proof

  • Environment tested: Windows 11 x64 build 26200 (tr-TR), Windows PowerShell 5.1.26100, WSL2.
  • PR head or commit tested: production scripts as in 47ca09d; the later commit on this PR adds only a test. CI on the PR head is the current-head result.
  • Exact steps or command run: wsl --import of an empty rootfs as a uniquely named distro, set OPENCLAW_STATE_DIR, OPENCLAW_TRAY_DATA_DIR and OPENCLAW_TRAY_LOCAL_DATA_DIR to temp folders, seed gateways.json, device key and exec-approvals.json, then run the real script with powershell.exe -File scripts/Uninstall-LocalGateway.ps1 -AppRoot <temp> -DataDirectoryName OpenClawProof -AutoStartName <fake> -StartupTaskName <fake> -DistroName <distro>. The same run was repeated with the script from a4dd026. No other distro was touched.
  • Evidence after fix:
distro registered before uninstall script: True
script exit code: 0
script output: OpenClaw local WSL gateway removed successfully.
distro registered after uninstall script: False
gateways.json ids left: []
identity dir left: False
root tokens left: False
legacy exec-approvals.json left: False
result.json: succeeded=True message=Local WSL gateway '<distro>' removed.
  • Observed result: cleanup completes and reports success. The other two cases, run against fixture folders with a distro name that is not registered: an older local record is removed with its identity directory, and an isLocal: false loopback record no longer counts as external, so root tokens are cleared.
  • Screenshot or artifact links verified? (Yes/No/N/A): N/A
  • Not verified or blocked:
    • Signed artifacts and an upgrade from the latest stable release (windows-clean-installer-upgrade). The Inno run above is unsigned, on the Dev identity, so it skips the Store migration check.
    • The interactive uninstall dialogs and Retry; only the silent path was run.
    • A distro with a real Gateway inside it.
    • Independent rubber-duck review was not run.

Security Impact

  • New permissions or capabilities? (No)
  • Secrets or tokens handling changed? (Yes)
  • New or changed network calls? (No)
  • Command or tool execution surface changed? (No)
  • Data access scope changed? (No)
  • If any answer is Yes, explain the risk and mitigation: root device tokens are now cleared at uninstall when only local or loopback records remain, as the README documents. This removes credentials rather than keeping them. The cost is that a remaining loopback gateway may need to pair again.

Compatibility and Migration

  • Backward compatible? (Yes)
  • Config or environment changes? (No)
  • Migration needed? (No)
  • If yes, list the exact upgrade steps:

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.

…g uninstall

Uninstall-LocalGateway.ps1 assigned to $host and declared a $Home parameter.
Both are read-only automatic variables, so Test-LocalGatewayUrl always returned
false and Expand-ExecApprovalsHomePath always threw.

With OPENCLAW_STATE_DIR set, the script exited 1 after wsl --unregister had
already deleted the distro. Older local records stayed in gateways.json, and
isLocal=false loopback records counted as external and kept root tokens.

Rename both variables here and in the validate-wsl-gateway-uninstall.ps1 copy.
Accept the expanded [::1] host that .NET Framework's Uri returns under Windows
PowerShell 5.1. Add regression tests that load the production functions under
5.1, sharing the host previously private to UninstallOnboardingSettingsTests.

Closes openclaw#1953
@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

🦞👀
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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 31, 2026
@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge.

What this changes

The PR fixes PowerShell variable collisions and IPv6 loopback recognition so local Gateway uninstall completes its intended cleanup.

Example: Uninstall removes OpenClawGateway with OPENCLAW_STATE_DIR set to ~/state.

  • Before: The distro is unregistered, but cleanup exits 1 with a read-only Home variable error and leaves gateway state behind.
  • After: Cleanup resolves the state directory, removes the intended artifacts, and reports success.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, useful repair with credible script and unsigned-installer evidence, pending the required signed upgrade compatibility proof.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Removing a local Gateway can report failure after deleting the distro or leave Companion pointing at stale gateway state.
Reason: The change restores documented cleanup behavior without introducing an option, schema, or competing owner.

Merge readiness

⛔ Blocked before merge - 2 items remain

This PR fixes concrete uninstall failures still present on main, preserves the documented cleanup contract, and introduces no identified code defect.

Priority: P2
Reviewed head: d5c9036b46e8c004ddbf0e845725f641c97c1e0d

Before merge

  • Add real behavior proof - The supplied Windows 11 and PowerShell 5.1 output exercises the real cleanup script, and the unsigned Dev Inno comparison shows successful removal with unrelated records and preferences preserved; production code is unchanged since that run. The earlier review's signed-installer proof request remains unresolved because the author explicitly excludes the required official-artifact pool and latest-stable upgrade. Supply redacted logs or terminal screenshots from that run, excluding credentials, private endpoints, and user paths. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: The required exact-signed-artifact run from the latest stable release through upgrade and uninstall remains unverified.
Agent review details

How this fits together

The Inno uninstaller invokes the PowerShell cleanup script, which removes the selected WSL distro and then updates Windows-side gateway records, identities, credentials, and onboarding settings.

flowchart TD
  A[Inno uninstall choice] --> B[Migration preservation gate]
  B --> C[PowerShell cleanup script]
  C --> D[Selected WSL distro]
  C --> E[Gateway registry and identities]
  C --> F[Approval files and onboarding settings]
  C --> G[Uninstall result]
Loading

Technical review

Best possible solution:

Land the focused helper repair after the required installer compatibility proof confirms intended cleanup and preservation.

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

Main source establishes both reserved-variable failures, and the reporter supplies matching Windows PowerShell 5.1 output; this read-only review ran no reproduction.

Is this the best way to solve the issue?

Renaming the colliding variables and handling .NET Framework's expanded IPv6 host is the smallest complete repair within the existing cleanup owner, with distinct regression coverage.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Local gateway classification keeps the original intent (8af4b70: The original uninstall flow directly removed the selected distro and setup-managed artifacts while preserving unrelated gateway state.)
  • Alternate approval-state cleanup keeps the original intent (4806eaa: V2 approval storage supports OPENCLAW_STATE_DIR, and uninstall cleanup was updated to resolve that location.)
  • Isolated onboarding-reset test host keeps the original intent (0131e4c: Tests execute selected production functions under Windows PowerShell 5.1 without running destructive top-level uninstall code.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Verified introduced change: The pinned diff renames the reserved Home and Host variables, accepts the expanded IPv6 loopback host, and reuses the existing isolated PowerShell test harness; the later commit adds only a registry compatibility test. (scripts/Uninstall-LocalGateway.ps1:185, d5c9036b46e8)
  • Main still has both failures: Main declares Home as a function parameter and assigns Host inside the URL classifier; configured state-directory resolution aborts cleanup, while the classifier catches its assignment failure and returns false. (scripts/Uninstall-LocalGateway.ps1:282, a4dd026cc5f8)
  • Existing cleanup intent: README documents deleting the removed gateway's identity and retaining root tokens only while external records remain; the C# uninstall path already resolves alternate approval-state directories. (README.md:31, a4dd026cc5f8)
  • Supplied runtime evidence: The full PR body reports Windows PowerShell 5.1 before/after output against a disposable registered WSL distro and an unsigned Dev Inno silent-uninstall comparison preserving remote and SSH-tunneled records, identities, and unrelated preferences. (d5c9036b46e8)
  • Required installer proof remains outstanding: The selected proof pool requires exact official signed artifacts and stateful upgrade, repair, and uninstall validation; the author explicitly reports that this pool and latest-stable upgrade were not run. (.github/proof-pools.json:265, d5c9036b46e8)
  • Feature history: History identifies the original direct-WSL uninstall work, the V2 approval-path change, migration preservation work, and credential-reset coverage; follow-history stops at an unavailable older object, without affecting verification of these commits. (scripts/Uninstall-LocalGateway.ps1, a4dd026cc5f8)

Likely related people:

  • Ranjesh: Raw commit 8af4b70 adds scripts/Uninstall-LocalGateway.ps1:146 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8af4b70360a9; files: scripts/Uninstall-LocalGateway.ps1)
  • Sebastien Tardif: Raw commit 0131e4c adds tests/OpenClaw.Tray.Tests/UninstallOnboardingSettingsTests.cs:18 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0131e4ce1f79; files: tests/OpenClaw.Tray.Tests/UninstallOnboardingSettingsTests.cs)
  • Natalie Aguinaldo: Raw commit 5a59535 adds scripts/Uninstall-LocalGateway.ps1:818 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 5a59535216ee; files: scripts/Uninstall-LocalGateway.ps1)

Review metrics

Metric Value Why it matters
Change size Production script +7/-5; validation script +3/-3; tests +280/-68 Production changes are narrow; test growth covers classification, legacy cleanup, path expansion, and persisted-record preservation while sharing the existing process harness.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The repair addresses bounded uninstall failures involving configured state directories and older local gateway records.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

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

  • Complete the declared signed-installer proof pool from the latest stable release, showing intended removal and preservation of unrelated settings, records, and identities.

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 (1 earlier review cycle)
  • reviewed 2026-10-31T18:36:25.128Z sha 47ca09d :: needs real behavior proof before merge. :: none

Reviewed October 31, 2026, 6:06 PM ET / 22:06 UTC (Revision 2).

@MertBasar0

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Removing the local gateway at uninstall fails or leaves stale state: script assigns to read-only PowerShell variables

2 participants