Skip to content

fix: Companion fails to reconnect after isolated session replacement - #1649

Merged
RomneyDa merged 3 commits into
mainfrom
fix/stale-session-native-gateway-recovery
Oct 7, 2026
Merged

RomneyDa merged 3 commits into
mainfrom
fix/stale-session-native-gateway-recovery

Conversation

@RomneyDa

@RomneyDa RomneyDa commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

Fixes: Companion fails to reconnect to its packaged local Gateway after a reboot when Windows replaces the stale isolated session and the replacement has no OpenClaw config.

User Impact

User impact: launching Companion automatically reprovisions a stale package session, restores Companion's saved endpoint credential, starts the Gateway, and reconnects without asking the user to rerun setup manually.

Why This Change Was Made

The isolated runtime now admits repair only from typed package facts: a stale recorded session, or a running session whose config file is explicitly absent. It runs package setup only for the stale-session case, restores the existing Companion token through redirected stdin, verifies that the package returned the same port and token, and then continues the existing start and listener-ownership checks. Unknown and malformed states still fail closed.

Depends on the coordinated package contract in openclaw/openclaw-windows-packaging#157, which has merged.

Evidence

  • Commit: d0e3eb4a
  • dotnet test tests/OpenClaw.Connection.Tests --filter 'FullyQualifiedName~NativeGatewayPackageClientTests|FullyQualifiedName~IsolatedGatewayRuntimeTests': 70 passed, 0 failed in 325 ms.
  • ClawSweeper's security note (superseded restoration persisting stale authority) is addressed in d0e3eb4a: the runtime now checks cancellation immediately before the package credential write instead of relying on the process launcher. CancellationDuringReprovisioningNeverRestoresTheSavedCredential fails without that line (restore is invoked after cancellation) and passes with it. PackagePreservingANewerTokenBlocksStartWithSupersededCredential proves that when the package keeps a newer token, Companion fails closed, never retries the restore, and never starts the Gateway or admits ownership proof.
  • NativeGatewayPackageClientTests: 17 passed, 0 failed on macOS; the new Windows cancellation case runs in hosted CI.
  • Release build of OpenClaw.Connection and its tests succeeded on macOS. The unfiltered suite then reached 1,295 passes before 279 existing Windows-principal/path tests failed because the host is macOS; those failures do not touch this diff.
  • ClawSweeper identified that stdin transmission preceded the process cleanup scope. The accepted fix starts output draining and the linked three-minute deadline before the write, and routes write cancellation through process-tree termination.
  • Independent P0-P2 AutoReview: scoped clean.
  • Required rubber-duck review: clean; it retained the Windows build/MXC live-proof limitations below.
  • Azure Crabbox run run_c83f1cc50fed8b302b9dac85d4daf584 provisioned a real Windows host and checked out the coordinated package PR, but the base image lacked PowerShell 7, winget, and the .NET SDK, so it could not build or deploy either candidate. The lease was released; this is infrastructure-gap evidence, not product proof.
  • Hosted Windows CI passed fast validation, proof-pool contracts, Tray/setup/integration, setup/connect E2E, network recovery E2E, revocation recovery E2E, CodeQL, and both security lanes. Core and CLI tests stopped in the unrelated Shared suite on BoundedProcessWaitTests.WaitAsync_DelayedKillOwnsProcessAfterBoundedReturn; current main passed that same Core job, and this PR does not change Shared code. Per repository policy, the flaky job was not blindly rerun.

Authority Chain

Restoration can only persist a credential Companion currently holds for the active record, and a superseded attempt cannot send or keep using it:

  1. Callers admit the record before entry: AuthorizeCredentialHandoffAsync rejects superseded attempts and changed endpoint/token/package records before calling the runtime.
  2. Supersession cancels the operation token. The runtime checks it after reprovisioning and immediately before the restore write (new), and the package launcher checks it again before starting the process.
  3. Cancellation during the write kills the package process tree. The package-side write in fix: Companion cannot recover after isolated session replacement openclaw-windows-packaging#157 is a snapshot-hash compare-and-swap that preserves an existing usable token and rejects racing configuration changes, so a killed or late restore cannot replace newer authority.
  4. Companion requires the package to return exactly the saved port and token. Any mismatch (including a preserved newer token) fails closed before start.
  5. After the runtime returns, the handoff rereads the registry and requires the same record and token before any credential is sent.

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

  • none: no named custom pool covers the MSIX isolated-session replacement contract; hosted Windows CI provides the required package/connection test surface.

Validation

  • Focused connection/package recovery suite: 70 passed, 0 failed.
  • Hosted Windows CI: all completed product-adjacent, E2E, and security lanes passed. The Core job stopped before Connection tests because an unrelated Shared timing test exceeded its bound; current main passed the same Core job.
  • Test cost: focused suite 325 ms locally (10.4 s wall including build); no timers, polling, process boots, or serial worker changes were added.

Real Behavior Proof

  • Environment tested: macOS cross-target build/test host
  • PR head or commit tested: d0e3eb4a
  • Exact steps or command run: focused NativeGatewayPackageClientTests and IsolatedGatewayRuntimeTests
  • Evidence after fix: the original stale-session flow executes status → setup → credential restore → status → start → ownership verification; the healthy-session/missing-config sibling restores without reprovisioning.
  • Observed result: 70 passed, 0 failed, including the superseded-cancellation and newer-token-preservation cases.
  • Screenshot or artifact links verified? (Yes/No/N/A): N/A
  • Not verified or blocked: live Windows reboot plus backend stale-identity replacement requires a coordinated package candidate and a Windows MXC environment. An Azure Crabbox attempt reached a real Windows host but could not reach the product boundary because the image lacked the repository prerequisites. End-to-end MXC replacement therefore remains a release-validation concern.

Security Impact

  • New permissions or capabilities? (Yes/No): No
  • Secrets or tokens handling changed? (Yes/No): Yes
  • New or changed network calls? (Yes/No): No
  • Command or tool execution surface changed? (Yes/No): Yes
  • Data access scope changed? (Yes/No): No
  • If any answer is Yes, explain the risk and mitigation: Companion sends only its already-authoritative saved token to the trusted package-qualified alias through redirected stdin, never argv or environment. The package response must match the saved port/token before lifecycle work continues.

Compatibility and Migration

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

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.

@clawsweeper

clawsweeper Bot commented Oct 6, 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 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: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. 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. labels Oct 6, 2026
@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge. Reviewed October 7, 2026, 2:47 AM ET / 06:47 UTC (Revision 5).

ClawSweeper review

What this changes

Companion repairs stale isolated Gateway sessions or missing configuration, restores its saved credential through standard input, and verifies the returned endpoint before reconnecting.

Merge readiness

⛔ Blocked before merge - 5 items remain

This recovery remains necessary on current main. The new cancellation guard addresses the earlier concern, and no concrete patch defect was established, but the previously requested authority and upgrade proof remains outstanding.

Priority: P2
Reviewed head: d0e3eb4a76987bdccc17ceaf13de21b1d60df2e3

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The focused repair and regression coverage are useful, but material authority and persistent-state proof remains incomplete.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: Authority-chain proof required: IsolatedGatewayRuntime restoration is exercised with injected package responses, while the real Windows attempt stopped before deployment. Show allowed restoration and superseded-record rejection through the real package’s persistent write, including newer-token preservation, racing configuration changes, and cancellation containment. Existing-state compatibility is independently insufficient. Redacted terminal traces or logs count; remove credentials and private endpoints. Updating the PR body triggers re-review, or a maintainer can request @clawsweeper re-review. 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 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: Authority-chain proof required: IsolatedGatewayRuntime restoration is exercised with injected package responses, while the real Windows attempt stopped before deployment. Show allowed restoration and superseded-record rejection through the real package’s persistent write, including newer-token preservation, racing configuration changes, and cancellation containment. Existing-state compatibility is independently insufficient. Redacted terminal traces or logs count; remove credentials and private endpoints. Updating the PR body triggers re-review, or a maintainer can request @clawsweeper re-review. 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 10 items Pinned introduced change: The merge-base-to-head diff introduces recovery in three production files and two test files. Base-only icon and UI-test changes are excluded from this review.
Current main still needs recovery: Current main starts or verifies the existing isolated Gateway but does not repair missing configuration or restore the saved token. Its package client does not expose the restore operation. Therefore no implemented-on-main or fixed-release conclusion is supported.
Cancellation and credential equality guards: Recovery checks cancellation immediately before RestoreAsync and refuses to start when the package returns a different port or token. New regression tests cover cancellation after setup and preservation of a newer package token using injected package responses.
Findings None None.
Security Needs attention Verify superseded restoration at the isolated write boundary: The pre-write cancellation check and package snapshot checks are useful safeguards. Available tests do not show that cancellation after dispatch prevents the isolated configuration worker from persisting superseded authority; no reachable violation is established by this review.

How this fits together

Companion manages connections to the packaged local Gateway, while the Gateway package owns its isolated Windows session and configuration. Recovery consumes package status and Companion’s saved connection record, then starts and verifies the Gateway before credentials are sent.

flowchart TD
 A[Saved connection record] --> B[Package status]
 B --> C{Stale session or missing config}
 C -->|Yes| D[Package setup and credential restoration]
 C -->|No| E[Gateway lifecycle]
 D --> E
 E --> F[Listener and record verification]
 F --> G[Authorized connection]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: Authority-chain proof required: IsolatedGatewayRuntime restoration is exercised with injected package responses, while the real Windows attempt stopped before deployment. Show allowed restoration and superseded-record rejection through the real package’s persistent write, including newer-token preservation, racing configuration changes, and cancellation containment. Existing-state compatibility is independently insufficient. Redacted terminal traces or logs count; remove credentials and private endpoints. Updating the PR body triggers re-review, or a maintainer can request @clawsweeper re-review. 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.
  • Resolve security concern: Verify superseded restoration at the isolated write boundary - The pre-write cancellation check and package snapshot checks are useful safeguards. Available tests do not show that cancellation after dispatch prevents the isolated configuration worker from persisting superseded authority; no reachable violation is established by this review.
  • Resolve merge risk (P1) - Cancellation and supersession are not proven through the real package and isolated configuration worker: a restore already dispatched across that boundary must not persist superseded authority or continue using it.
  • Resolve merge risk (P1) - Fresh setup and existing-install compatibility remain unverified, including preservation of existing tokens and rejection of racing configuration changes during restoration.
  • Complete next step (P2) - Provide current-head Windows final-effect authority and existing-install compatibility evidence through the coordinated package before merge.

Findings

  • [medium] Verify superseded restoration at the isolated write boundary — src/OpenClaw.Connection/NativeGateway/IsolatedGatewayRuntime.cs:138
Agent review details

Security

Needs attention: Source safeguards are present, but cancellation containment across the persistent credential-write boundary still needs evidence.

Review metrics

Metric Value Why it matters
Production and test delta production +128/-21; tests +212/-10 Production growth supports the stated recovery and cancellable stdin contract, with most added coverage in focused tests.

Merge-risk options

Maintainer options:

  1. Verify the coordinated package boundary (recommended)
    Provide current-head Windows evidence that restoration succeeds for the active record, rejects superseded authority before persistent I/O, and preserves existing configuration across upgrade.

Technical review

Best possible solution:

Keep recovery in the package-owned configuration path, preserving current credentials and configuration while making stale-session reconnection safe under supersession and upgrade.

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

Yes, source establishes the failure path: current main cannot repair a stale session or restore missing Gateway configuration from its saved record. A failing live Windows replacement scenario was not executed in this review.

Is this the best way to solve the issue?

Yes, using the package’s existing configuration owner is the narrowest approach, and the new cancellation guard improves it. Final-effect authority and upgrade evidence is still needed to establish merge readiness.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This repairs a bounded packaged-Gateway reconnection failure after isolated-session replacement.
  • merge-risk: 🚨 compatibility: Recovery writes persistent Gateway configuration through a coordinated package contract whose existing-install behavior lacks final-path evidence.
  • merge-risk: 🚨 security-boundary: Saved credentials cross into an isolated account’s persistent configuration, and superseded-operation containment remains unproven at that write boundary.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: Authority-chain proof required: IsolatedGatewayRuntime restoration is exercised with injected package responses, while the real Windows attempt stopped before deployment. Show allowed restoration and superseded-record rejection through the real package’s persistent write, including newer-token preservation, racing configuration changes, and cancellation containment. Existing-state compatibility is independently insufficient. Redacted terminal traces or logs count; remove credentials and private endpoints. Updating the PR body triggers re-review, or a maintainer can request @clawsweeper re-review. 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

Security concerns:

  • [medium] Verify superseded restoration at the isolated write boundary — src/OpenClaw.Connection/NativeGateway/IsolatedGatewayRuntime.cs:138
    The pre-write cancellation check and package snapshot checks are useful safeguards. Available tests do not show that cancellation after dispatch prevents the isolated configuration worker from persisting superseded authority; no reachable violation is established by this review.
    Confidence: 0.91

What I checked:

Likely related people:

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

Rank-up moves

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

  • Add final-effect Windows evidence for allowed restoration and superseded-record rejection, including cancellation after dispatch into the isolated configuration worker.
  • Verify fresh setup and existing-install restoration, preserving newer tokens and rejecting racing configuration changes.

Rating scale

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

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

Workflow

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

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-06T06:25:06.686Z sha 8ecdcda :: needs real behavior proof before merge. :: [P2] Put stdin transmission inside the subprocess cleanup scope
  • reviewed 2026-10-06T06:36:01.443Z sha f47dc36 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-06T07:04:54.696Z sha 0fec248 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-06T07:23:30.189Z sha 0fec248 :: needs real behavior proof before merge. :: none

@RomneyDa

RomneyDa commented Oct 6, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

🦞👀
Exact review queued.

Re-review progress:

@RomneyDa
RomneyDa force-pushed the fix/stale-session-native-gateway-recovery branch from f47dc36 to 0fec248 Compare October 6, 2026 06:51
@RomneyDa

RomneyDa commented Oct 6, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

🦞👀
Exact review queued.

Re-review progress:

@RomneyDa RomneyDa added the status: 🚢 actively landing A maintainer or agent is actively driving this item through implementation, validation, or merge. label Oct 7, 2026
@clawsweeper

clawsweeper Bot commented Oct 7, 2026

Copy link
Copy Markdown

ClawSweeper status: review started.

I am starting a fresh review of this pull request: fix: Companion fails to reconnect after isolated session replacement This is item 1/1 in the current shard. Shard 0/1.

This temporary status tracks the active review worker. The completed review will appear in the durable ClawSweeper review comment.

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

@RomneyDa
RomneyDa merged commit 5a8830e into main Oct 7, 2026
27 checks passed
@RomneyDa
RomneyDa deleted the fix/stale-session-native-gateway-recovery branch October 7, 2026 07:00
@RomneyDa RomneyDa removed the status: 🚢 actively landing A maintainer or agent is actively driving this item through implementation, validation, or merge. label Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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