Skip to content

Daemon lifecycle: dev worktrees, production app, and Pro/community builds collide on shared launchd service + socket #1468

Closed

Description

@malibio

Summary

Every NodeSpace instance on a given macOS user account — every dev worktree, the installed production app, and both community/Pro build editions — shares exactly one launchd service label, one plist file, and one Unix domain socket. There is no per-instance, per-version, or per-edition scoping anywhere in the daemon lifecycle path, and no locking/coordination between instances. This produces reliably reproducible daemon breakage for any workflow (like this repo's mandatory EnterWorktree-per-issue model) that runs more than one build concurrently or in quick succession. A separate, narrower bug (substring process-matching) also lets a community build kill a running Pro daemon and vice versa.

This was reproduced live tonight; see below.

Reproduction (verified live tonight)

Ran bun run dev:tauri in worktree issue-1465-ornith-model while a production-installed /Applications/NodeSpace.app daemon was already active from over a week ago:

  1. App boot calls kill_stale_daemon_sync (packages/desktop-app/src-tauri/src/daemon_setup.rs:74): detects the installed ~/.nodespace/bin/nodespaced (25,534,384 bytes) differs in size from this worktree's freshly built bundled sidecar (102,630,888 bytes) → SIGKILLs whatever process holds the socket and deletes the socket file.
  2. ensure_daemon_running (daemon_setup.rs:175) extracts the new binary, rewrites ~/Library/LaunchAgents/app.nodespace.daemon.plist, and calls bootstrap_launchd_agent (daemon_setup.rs:574).
  3. launchctl bootstrap gui/501 <plist> returned exit code 5 ("Input/output error"). bootstrap_launchd_agent only special-cases exit codes 36/37 or specific stderr substrings as "already bootstrapped" (daemon_setup.rs:592-594); any other failure — including this one — just logs a tracing::warn! and returns Ok(()) (daemon_setup.rs:617-622) without starting anything or retrying.
  4. Nothing was listening on ~/.nodespace/daemon.sock. wait_for_daemon (daemon_setup.rs:386, called from ensure_daemon_running at line 245) polled for 30s, timed out, and the frontend loop-retried gRPC calls every 2s with No such file or directory (os error 2) — producing the console errors observed (getAllSchemas, SchemaPluginLoader, SharedNodeStore failures) and an extended "Initializing NodeSpace..." splash.
  5. launchctl print gui/501/app.nodespace.daemon showed launchd's in-memory registered job still pointed at /Users/malibio/.nodespace/bin/nodespaced-pro (process start timestamp "23Jun26", over a week old) — even though the plist file on disk had already been rewritten to point at the new community nodespaced binary. The failed bootstrap left launchd's live state permanently diverged from the plist file.
  6. ls ~/.nodespace/bin/ showed three coexisting binaries: nodespaced (community, just extracted), nodespaced-pro (Pro/sync build, ~2 weeks old), and nodespace (CLI). Nothing ever cleans up the other edition's binary.

Root cause: zero scoping across ALL shared state

Every path/identifier the daemon lifecycle touches is derived only from $HOME, with no per-instance, per-worktree, per-build, or per-edition component:

  • DAEMON_BIN_DIR = ".nodespace/bin" — daemon_setup.rs:27
  • DAEMON_SOCKET_RELATIVE = ".nodespace/daemon.sock" — packages/desktop-app/src-tauri/src/constants.rs:6
  • LAUNCH_AGENT_LABEL = "app.nodespace.daemon" / PLIST_FILENAME = "app.nodespace.daemon.plist" — daemon_setup.rs:35,37, written to ~/Library/LaunchAgents/ (daemon_setup.rs:485-487)
  • daemon_binary_name() (daemon_setup.rs:59-65) picks "nodespaced" vs "nodespaced-pro" based on NODESPACE_PRO_SUPABASE_URL baked in at compile time, but the launchd label/plist/socket are identical regardless of edition — a community dev build and a Pro build fight over the same launchd job and socket.

The module doc comment at the top of the file (daemon_setup.rs:1-16) describes a clean state machine ("check socket → healthy no-op → else restart → else fresh install") but the implementation doesn't account for: concurrent instances racing to rewrite the same plist/bootstrap/kill the same daemon; community/Pro churn on the same paths; launchd bootstrap failures beyond two hardcoded exit codes; or any cross-instance coordination.

Call sites confirmed in packages/desktop-app/src-tauri/src/lib.rs:

  • Line 238: kill_stale_daemon_sync(app) — sync, runs before the gRPC client is managed, on every app boot.
  • Line 248: gRPC client managed eagerly (lazy-connect) right after.
  • Line 263-289: ensure_daemon_running spawned async; on success/failure emits daemon-status to the frontend.
  • Line 362-376: post-startup re-check of check_daemon_socket on grpc_client::resolve_socket_path() (same socket, honors NODESPACED_SOCKET override) to catch a daemon that's still down after the probe.

No single-instance guard exists anywhere. Searched for flock, single_instance, tauri-plugin-single-instance, PID files, and lock file patterns across packages/desktop-app/src-tauri — no matches. tauri-plugin-single-instance (which would prevent multiple copies of the GUI app itself from running, a separate concern from the daemon) is not in Cargo.toml and not used. The only pre-existing coordination is the NODESPACED_SOCKET env var override (services/grpc_client.rs:161-192), which both the plist writer (daemon_setup.rs:540-541) and the gRPC client already honor when set — but nothing currently sets it to a distinct value per instance.

Production app collision confirmed structurally. packages/desktop-app/tauri.conf.json gives the app a single fixed identifier (com.nodespace.desktop) and there's no build-time variant of DAEMON_SOCKET_RELATIVE/LAUNCH_AGENT_LABEL. A production-installed /Applications/NodeSpace.app (with RunAtLoad: true in its plist, daemon_setup.rs:545-546, meaning it can auto-start on login) and any dev build from any worktree share the identical ~/.nodespace/ tree and launchd label. There is currently no way to tell "the production app the user runs daily" apart from "today's dev build in worktree #N" — they collide on every path, every time.

Blast radius

(a) Single developer, multiple worktrees run sequentially (the common case under this repo's EnterWorktree-per-issue workflow): Every bun run dev:tauri invocation from a different worktree has a different bundled sidecar size (different build), so kill_stale_daemon_sync fires almost every time, tearing down whatever was running. If bootstrap_launchd_agent hits any launchctl error outside the two hardcoded codes, the daemon silently fails to restart and the app hangs on "Initializing..." until the user manually intervenes (launchctl bootout + relaunch, or reboot). This is the exact failure reproduced above and is very likely the dominant source of the "weeks" of daemon lifecycle pain.

(b) Dev build running while production app is installed (and possibly auto-starting via RunAtLoad): Direct collision — confirmed above. A dev session can kill the user's actual production daemon (losing whatever state/connections it had), and a subsequent production app launch (or its RunAtLoad auto-start) can just as easily kill/replace the dev daemon. There is no notion of "leave production alone."

(c) Multiple macOS user accounts on one machine: NOT shared — confirmed independently. ~/.nodespace/ and ~/Library/LaunchAgents/ are per-$HOME, and launchctl bootstrap gui/<uid> scopes to the calling user's uid (daemon_setup.rs:576, via get_uid() at line 626 which calls libc::getuid()). Two accounts (e.g. malibio and mayanktomar) each get independent trees and independent launchd agents. This confirms the bug is scoped to within one user account, across all that account's builds/worktrees — not machine-wide.

(d) Community vs Pro edition churn for one user: Confirmed as its own failure mode, compounded by the process-matching bug below. Switching between a community-edition dev build and a Pro build on the same machine leaves stale nodespaced-pro or nodespaced binaries in ~/.nodespace/bin/ indefinitely (nothing cleans up the other edition's binary — only the current edition's binary is size-checked), and both editions fight over the identical launchd label/socket.

Independent bug: substring process matching cross-kills editions

kill_stale_daemon_sync (daemon_setup.rs:134-141) and kill_running_daemon (daemon_setup.rs:288-295) both verify a candidate PID via:

String::from_utf8_lossy(&o.stdout).trim().ends_with("nodespaced")

"nodespaced-pro".ends_with("nodespaced") is false (the suffix is "-pro", not "nodespaced") — actually verified this: ends_with requires an exact trailing match, and nodespaced-pro ends in -pro, so ends_with("nodespaced") is false for the Pro binary's comm name. I want to flag that the original hypothesis (Pro cross-contamination via this specific substring check) does not hold on closer inspection — ps -o comm= reports the literal binary name, and nodespaced-pro does not end with the literal string nodespaced.

That said, this check is still fragile and worth fixing on its own merits, independent of the launchd issue:

  • It matches "any process whose comm name ends with nodespaced," which is a purely lexical check with no verification that the PID belongs to this installation, this edition, or even this machine's ~/.nodespace/bin/ path (e.g. a symlinked or renamed binary, or a coincidentally-named process, would pass).
  • More importantly, the deeper problem observed in the reproduction (item 5 above) is that kill_stale_daemon_sync/kill_running_daemon operate purely on whatever is bound to the shared socket path, regardless of which edition or instance put it there — so a community build's stale-binary check will still SIGKILL a live Pro daemon it finds squatting on ~/.nodespace/daemon.sock, just via the socket-sharing path rather than the substring match. The substring imprecision is a secondary hardening concern; the primary cross-edition kill vector is the shared socket/PID resolution via lsof -U <shared socket>, which has no edition awareness at all.

Recommend fixing both, but they are not the same bug — the shared-socket issue is fixed by the scoping recommendation below; the substring match should additionally be tightened to compare against the full resolved binary path (e.g. ps -o comm=,args= or resolve /proc/lsof's reported path) rather than a trailing-string heuristic, as defense in depth.

Recommendation

Primary fix: scope the socket + launchd label per build variant, using a stable identifier for dev vs. production, and a distinct one per edition. Concretely:

  1. Dev builds get a permanently distinct socket + label suffix, e.g. .nodespace/daemon-dev.sock and label app.nodespace.daemon.dev, gated on cfg!(debug_assertions) (already used elsewhere in this codebase, e.g. main.rs:2, commands/pro_sync.rs:26). This means every bun run dev:tauri invocation from every worktree shares one dev socket/label — they still collide with each other, but never with the production app. This directly fixes blast-radius case (b), the most damaging one (a dev session killing the user's real daily-driver daemon).
  2. Edition-scope the label/socket too: append -pro / community stays unsuffixed (or vice versa), derived from the existing is_pro_build() (daemon_setup.rs:54-56) compile-time check. This fixes blast-radius case (d) and eliminates the shared-socket cross-edition kill vector described above — a community daemon and Pro daemon can no longer contend for the same launchd job or socket at all.
  3. Harden bootstrap_launchd_agent (daemon_setup.rs:574-623) to treat any non-success exit code as "might already be registered" and attempt launchctl bootout gui/<uid>/<label> followed by a fresh bootstrap, rather than special-casing only 36/37. This makes recovery from arbitrary launchctl failures (like the exit-code-5 I/O error reproduced tonight) self-healing instead of requiring manual bootout/reboot. This is valuable regardless of which scoping approach is chosen.
  4. Tighten the process-match check in kill_stale_daemon_sync/kill_running_daemon to verify against the full binary path, not just a trailing substring, as defense in depth once sockets are edition-scoped.

Alternatives considered and rejected (or deferred)

  • Per-worktree/per-instance socket+label scoping (e.g. hash of the worktree path or build timestamp baked into the socket/label): would fully eliminate collisions between concurrent worktrees, but at real cost — every worktree would run its own daemon process (its own model load, ~9s cold start per daemon_setup.rs:243, own DB connection unless the DB path is also shared/coordinated), multiplying memory and load time per open worktree, and leaving N daemons running indefinitely with no obvious cleanup trigger. Given this repo's workflow keeps many worktrees around, this could mean many resident daemons. Worth a follow-up if per-worktree isolation is later deemed necessary (e.g. for schema/DB experiments), but not proposed as the primary fix here — dev-mode-shared-among-worktrees (option above) captures most of the benefit (never touching prod) at much lower resource cost, since worktrees are rarely run truly concurrently in practice (the EnterWorktree workflow is one-active-worktree-at-a-time per session, even though many exist on disk).
  • Single true singleton daemon with version negotiation (one daemon serves all instances regardless of build, with a handshake to check compatibility): elegant in principle but requires a real client/server version-negotiation protocol, migration handling if schemas differ across worktree branches, and doesn't solve the production-vs-dev collision at all (you'd still want prod isolated). Substantially more design and implementation work than the problem currently warrants; revisit only if per-instance daemons prove too resource-heavy in practice.
  • "Just don't run two at once" / rely on developer discipline: not viable — this repo's CLAUDE.md startup sequence mandates a new worktree per issue and worktrees accumulate by design; the collision isn't a rare edge case, it's the default outcome of following the documented workflow.
  • More robust launchctl error handling alone, without any scoping: would reduce the "silently never starts" failure mode but does nothing for the cross-edition/cross-instance kill behavior or the production/dev collision — treated as a complementary fix (item 3 above), not a substitute for scoping.

Suggested split

This should likely be split into:

  1. Primary issue (this one): dev/prod and community/Pro socket+launchd scoping, plus launchctl error-handling hardening.
  2. Optional follow-up: tighten the substring process-match check (item 4) — small, mechanical, low-risk, can ride along with Set up Tauri + Svelte project structure #1 or land separately since it's independent of whether scoping lands first.

Files referenced

  • packages/desktop-app/src-tauri/src/daemon_setup.rs (all line references above)
  • packages/desktop-app/src-tauri/src/constants.rs:6
  • packages/desktop-app/src-tauri/src/services/grpc_client.rs:161-192
  • packages/desktop-app/src-tauri/src/lib.rs:74, 238, 248, 263-289, 362-376
  • packages/desktop-app/src-tauri/src/main.rs:2 (existing debug_assertions precedent)
  • packages/desktop-app/tauri.conf.json

Activity

  1. malibio commented on Jul 1, 2026

    @malibio
    CollaboratorAuthor

    Frontend: 141 files, 3896 tests passed

  2. self-assigned this
    on Jul 1, 2026
  3. added a commit that references this issue on Jul 2, 2026
    fd2a89b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions