Skip to content

fix(macos): prevent launchd ghosting on cache wipe and force install - #180307

Closed
avnishkirnalli wants to merge 1 commit into
openclaw:mainfrom
avnishkirnalli:fix-macos-btm-ghosting
Closed

avnishkirnalli wants to merge 1 commit into
openclaw:mainfrom
avnishkirnalli:fix-macos-btm-ghosting

Conversation

@avnishkirnalli

Copy link
Copy Markdown
Contributor

Closes #180301

What Problem This Solves

Fixes: the local gateway becoming permanently unrecoverable when a macOS user manually deletes their ~/.openclaw or LaunchAgent .plist files.

User Impact

User impact: macOS users can now successfully recover and reinstall the local gateway after a manual cache wipe without being permanently blocked by hidden OS registry ghosting.

Why This Change Was Made

The app previously assumed a loaded macOS launchd service would always have a corresponding .plist file on disk, which caused --force installs to crash and UI uninstalls to skip the bootout step if the cache was wiped. This change decouples the OS-level teardown from the file's existence, forcing a launchctl bootout on the target label directly so the Background Task Management (BTM) registry is cleanly flushed. It also explicitly clears the ~/Library/Application Support/OpenClaw directories during uninstall to prevent hidden state retention.

Evidence

  • Verified openclaw gateway install --force successfully flushes a ghosted launchd environment without throwing a missing-plist error.
  • Verified openclaw uninstall properly clears all macOS Application Support directories (~/Library/Application Support/OpenClaw).
  • Verified the macOS GUI successfully executes launchctl bootout on the service label during a teardown even when the .plist file is manually deleted.
  • Local pnpm vitest run src/commands/uninstall.test.ts passes with the new macOS directory cleanup assertions.

Copilot AI balanced review requested due to automatic review settings October 22, 2026 04:47
@clawsweeper

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@openclaw-barnacle openclaw-barnacle Bot added app: macos App: macos gateway Gateway runtime commands Command implementations size: S labels Oct 22, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 22, 2026
@clawsweeper

clawsweeper Bot commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR adds label-based LaunchAgent teardown, permits reinstalling loaded services with missing plists, and deletes macOS Application Support directories during state uninstall.

Example: gui/501/ai.openclaw.gateway remains loaded after its plist is deleted.

  • Before: Installation refuses to stop a service whose definition cannot be restored.
  • After: Installation boots out the service before writing its replacement and records the previous service as unloaded.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The recovery problem is useful work, but the patch introduces service-loss and data-loss paths and lacks demonstrated after-fix behavior.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🧂 unranked krab (1/6) Security review found an item that needs attention.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Partial
User problem: After deleting local artifacts, a macOS user cannot restore the local Gateway through the app.
Reason: Recovery has clear value, but discarding an unrestorable loaded definition changes an intentional owner-established contract; the retained-environment failure shown in the report also remains outside this patch's repair.

Merge readiness

⛔ Blocked before merge - 10 items remain

Keep this PR open for the documented recovery problem, but repair its service-loss, lifecycle-guard, profile-isolation, and data-preservation regressions before merging.

Priority: P1
Reviewed head: ea7edee6e815dd27b1ded35e3af9799868e2b20e
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should missing-plist recovery permit discarding a loaded Gateway's only remaining definition?
  • Recommendation: Preserve recoverability: Keep automatic recovery transactional and preserve the loaded service until a restorable replacement is available.
  • Why: The proposed recovery changes an intentional service-preservation contract, and no maintainer approval of that tradeoff appears in the discussion.

Before merge

  • Add real behavior proof - The inspected linked images show the original retained-environment error, while the PR supplies only verification assertions for its changed install, teardown, and cleanup behavior; provide redacted macOS terminal output or a recording showing recovery after deletion and both permitted and ownership-blocked teardown before native I/O. 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.
  • Preserve the loaded definition until replacement can be rolled back (P1) - When a Gateway remains loaded after its plist is deleted, this snapshot helper now boots it out before writeLaunchAgentPlist runs and returns false for its prior loaded state. A subsequent filesystem or bootstrap failure cannot restore the original definition, and rollback skips restoring supervision because loaded is false. The previous guard deliberately preserved the working job. Keep snapshot capture non-destructive and perform recovery only through a transaction with a restorable prior definition.
  • Route bootout through the guarded CLI lifecycle (P1) - This direct launchctl call executes before runDaemonCommand reaches the service-operation lock and managed-handoff checks. If an updater currently reserves the service resource, Swift can stop its Gateway first and only afterward receive the CLI's ownership refusal. ServiceAuthority.currentError checks file identity, not that reservation. Remove the parallel native mutation and implement missing-plist teardown inside the existing guarded service owner.
  • Preserve the no-op for profiles without a local service (P1) - Removing the missing-plist return makes every remote or unconfigured profile stop invoke CLI uninstall even when no job exists. With an incompatible shared handoff-store record, uninstall fails and GatewayProcessManager marks that profile failed. This is the field failure fixed by fix(macos): remote-mode profile reports a Gateway uninstall failure when it has no local service #164069 and covered by AppStateIsolationTests. Distinguish a confirmed loaded orphan from an absent service instead of removing the no-op.
  • Keep state cleanup within the selected data scope (P1) - Running openclaw uninstall --state --yes --non-interactive now recursively deletes the global Application Support/OpenClaw tree. For a configured workspace at ~/Library/Application Support/OpenClaw/workspace, the normal cleanup preserves its files but this second deletion removes them despite --workspace being absent. Named-profile cleanup also removes the shared native databases and tunnel ledger used by other app instances. Remove this blanket cleanup from the recovery fix; any native-data cleanup must use its owning subsystem and honor selected scopes and preserved workspaces.
  • Resolve security concern: Reject borrowed service mutations before launchctl - The forbidden caller is an ordinary app teardown while an updater owns the service reservation; rejection must occur before bootout, with both allowed and reservation-blocked paths exercised through the production owner.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • 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.
  • Explain or restore the original intent of Missing-plist install refusal and transactional supervision - unknown: Merged fix: prevent LaunchAgent reinstall from leaving gateway down #120699 establishes preservation of prior definitions and supervision after failed activation; refactor(daemon): split launchd into concept modules #121929 moved this behavior into concept modules. Local git log -S and git show could not inspect older unavailable blobs to establish the exact guard introduction.
  • Explain or restore the original intent of Missing-profile LaunchAgent teardown no-op - 95529b5: Merged fix(macos): remote-mode profile reports a Gateway uninstall failure when it has no local service #164069 prevents remote or unconfigured profiles without a service from reaching shared lifecycle locks and reporting spurious Gateway failures.

Findings

  • [P1] Preserve the loaded definition until replacement can be rolled back — src/daemon/launchd-install.ts:132-142
  • [P1] Route bootout through the guarded CLI lifecycle — apps/macos/Sources/OpenClaw/GatewayLaunchAgentManager.swift:291-295
  • [P1] Preserve the no-op for profiles without a local service — apps/macos/Sources/OpenClaw/GatewayLaunchAgentManager.swift:291-295
  • [medium] Reject borrowed service mutations before launchctl — apps/macos/Sources/OpenClaw/GatewayLaunchAgentManager.swift:291

Provenance

Tests

  • Missing end-to-end proof: Provide red-on-base/green-on-head recovery regressions and macOS entry-point evidence for deletion-and-relaunch recovery, failed activation, absent remote profiles, guarded teardown rejection, and a latest-stable upgrade preserving settings and unrelated data.
Agent review details

How this fits together

The macOS app invokes the CLI service lifecycle, whose owners coordinate launchd mutations, runtime intent, and rollback; uninstall separately removes explicitly selected local data.

flowchart TD
  A[macOS app] --> B[Gateway CLI]
  B --> C[Service mutation guards]
  C --> D[LaunchAgent transaction]
  D --> E[launchd]
  F[Uninstall command] --> G[Selected data cleanup]
  A --> E
Loading

Technical review

Best possible solution:

Recover deleted artifacts through the existing guarded lifecycle and an in-app Repair action while preserving rollback, profile isolation, and selected data scopes.

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

Source confirms missing-plist install refusal and teardown skipping; the screenshots establish retained-environment failure, while permanent BTM corruption remains unverified.

Is this the best way to solve the issue?

Label-based teardown belongs in the existing lifecycle owner, but destructive snapshot capture, direct Swift mutation, and global data deletion do not form a safe complete recovery.

Full review comments:

  • [P1] Preserve the loaded definition until replacement can be rolled back — src/daemon/launchd-install.ts:132-142
    When a Gateway remains loaded after its plist is deleted, this snapshot helper now boots it out before writeLaunchAgentPlist runs and returns false for its prior loaded state. A subsequent filesystem or bootstrap failure cannot restore the original definition, and rollback skips restoring supervision because loaded is false. The previous guard deliberately preserved the working job. Keep snapshot capture non-destructive and perform recovery only through a transaction with a restorable prior definition.
    Confidence: 0.99
  • [P1] Route bootout through the guarded CLI lifecycle — apps/macos/Sources/OpenClaw/GatewayLaunchAgentManager.swift:291-295
    This direct launchctl call executes before runDaemonCommand reaches the service-operation lock and managed-handoff checks. If an updater currently reserves the service resource, Swift can stop its Gateway first and only afterward receive the CLI's ownership refusal. ServiceAuthority.currentError checks file identity, not that reservation. Remove the parallel native mutation and implement missing-plist teardown inside the existing guarded service owner.
    Confidence: 0.98
  • [P1] Preserve the no-op for profiles without a local service — apps/macos/Sources/OpenClaw/GatewayLaunchAgentManager.swift:291-295
    Removing the missing-plist return makes every remote or unconfigured profile stop invoke CLI uninstall even when no job exists. With an incompatible shared handoff-store record, uninstall fails and GatewayProcessManager marks that profile failed. This is the field failure fixed by fix(macos): remote-mode profile reports a Gateway uninstall failure when it has no local service #164069 and covered by AppStateIsolationTests. Distinguish a confirmed loaded orphan from an absent service instead of removing the no-op.
    Confidence: 0.99
  • [P1] Keep state cleanup within the selected data scope — src/commands/uninstall.ts:49-57
    Running openclaw uninstall --state --yes --non-interactive now recursively deletes the global Application Support/OpenClaw tree. For a configured workspace at ~/Library/Application Support/OpenClaw/workspace, the normal cleanup preserves its files but this second deletion removes them despite --workspace being absent. Named-profile cleanup also removes the shared native databases and tunnel ledger used by other app instances. Remove this blanket cleanup from the recovery fix; any native-data cleanup must use its owning subsystem and honor selected scopes and preserved workspaces.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Testing

Proof path: none.

Security

Needs attention: The added native bootout bypasses the existing service-operation ownership boundary.

Evidence

Security concerns:

  • [medium] Reject borrowed service mutations before launchctl — apps/macos/Sources/OpenClaw/GatewayLaunchAgentManager.swift:291
    The forbidden caller is an ordinary app teardown while an updater owns the service reservation; rejection must occur before bootout, with both allowed and reservation-blocked paths exercised through the production owner.
    Confidence: 0.98

What I checked:

Likely related people:

  • Dallin Romney: Raw commit 98e49a9 adds apps/macos/Sources/OpenClaw/GatewayLaunchAgentManager.swift:21 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 98e49a9280bc; files: apps/macos/Sources/OpenClaw/GatewayLaunchAgentManager.swift)

PR surface

Source +50. Total +50 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 65 15 +50
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 65 15 +50

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #180301
Summary: This PR is the same author's unmerged fixing candidate for the linked macOS recovery report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add P1: The reported macOS recovery workflow is blocked, and the patch introduces concrete service-availability and data-preservation regressions.
  • add merge-risk: 🚨 compatibility: State-only uninstall gains global deletions that violate existing workspace-preservation and profile-scoping behavior.
  • add merge-risk: 🚨 security-boundary: Direct Swift bootout reaches the native effect before the existing service-operation ownership and handoff guards.
  • add merge-risk: 🚨 availability: A failed reinstall can leave a previously running Gateway without its original launchd definition or supervision.
  • add proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🧂 unranked krab.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P1: The reported macOS recovery workflow is blocked, and the patch introduces concrete service-availability and data-preservation regressions.
  • merge-risk: 🚨 compatibility: State-only uninstall gains global deletions that violate existing workspace-preservation and profile-scoping behavior.
  • merge-risk: 🚨 availability: A failed reinstall can leave a previously running Gateway without its original launchd definition or supervision.
  • merge-risk: 🚨 security-boundary: Direct Swift bootout reaches the native effect before the existing service-operation ownership and handoff guards.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.

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.

Reviewed October 22, 2026, 1:05 AM ET / 05:05 UTC.

steipete added a commit that referenced this pull request Oct 22, 2026
…nd uninstall (#180390)

Fixes #180301. After the launchd plist disappeared (for example a cache clear), the macOS app skipped uninstall and CLI install refused the surviving registration, so the Gateway could not be reinstalled. Recovery now boots out the service by label at the daemon owner and the app delegates there; existing plist and environment backups keep rollback protection. Supersedes #180307, thanks @avnishkirnalli.

Co-authored-by: Avnish Kirnalli <[email protected]>
@steipete

Copy link
Copy Markdown
Contributor

Thank you @avnishkirnalli, both for the report and the fix! We re-implemented it in #180390: label-based bootout recovers the ghost registration in both the app and the CLI, and plist backups still protect rollback. It landed with you credited as co-author. Closing this one as superseded.

@steipete steipete closed this Oct 22, 2026
@avnishkirnalli
avnishkirnalli deleted the fix-macos-btm-ghosting branch October 22, 2026 07:53
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 23, 2026
…nd uninstall (openclaw#180390)

Fixes openclaw#180301. After the launchd plist disappeared (for example a cache clear), the macOS app skipped uninstall and CLI install refused the surviving registration, so the Gateway could not be reinstalled. Recovery now boots out the service by label at the daemon owner and the app delegates there; existing plist and environment backups keep rollback protection. Supersedes openclaw#180307, thanks @avnishkirnalli.

Co-authored-by: Avnish Kirnalli <[email protected]>
RomneyDa pushed a commit that referenced this pull request Oct 26, 2026
…nd uninstall (#180390)

Fixes #180301. After the launchd plist disappeared (for example a cache clear), the macOS app skipped uninstall and CLI install refused the surviving registration, so the Gateway could not be reinstalled. Recovery now boots out the service by label at the daemon owner and the app delegates there; existing plist and environment backups keep rollback protection. Supersedes #180307, thanks @avnishkirnalli.

Co-authored-by: Avnish Kirnalli <[email protected]>
Release adaptation: the stable line keeps the standalone
getGatewayServiceAutoRefreshMessage helper and inline bootstrap calls, so the
missing-definition refresh message and restoreLoaded gate were applied there
without main's helper restructuring. Main's launchd tests use fixtures absent on
this line; the deleted-plist install/uninstall cases were ported into
launchd.test.ts (launchd-missing-plist.test.ts dropped), the real-launchd e2e case
was rewritten with the baseline helpers, and only the macOS paragraph was added to
docs/install/updating.md.

(cherry picked from commit f620293)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: macos App: macos commands Command implementations gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S 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.

[Bug]: macOS launchd service ghosting when cache is cleared (Gateway install/uninstall fails)

3 participants