Skip to content

Move system tray ownership to nodespaced daemon (closes #241) - #1143

Merged
malibio merged 4 commits into
mainfrom
feature/issue-241-daemon-system-tray
May 17, 2026
Merged

malibio merged 4 commits into
mainfrom
feature/issue-241-daemon-system-tray

Conversation

@malibio

@malibio malibio commented May 17, 2026

Copy link
Copy Markdown
Collaborator

Summary

ADR-031 places the system tray on the long-running nodespaced daemon so the tray (and the daemon) survive Tauri UI restarts. The daemon owns the menu-bar icon and manages the UI lifecycle; closing the Tauri window only exits the UI process while the daemon keeps running.

Implementation

  • packages/daemon/src/tray.rs (new) — tao event loop on the main thread, menu with Open NodeSpace / Status: N active calls / Quit, Tauri-binary spawn-or-skip, and a tower::Layer (TrayMetricsLayer) that reports in-flight RPC counts to the Status label.
  • packages/daemon/src/main.rs — restructured to run the tray on the main thread and the tonic gRPC server on a worker tokio runtime. NODESPACED_HEADLESS=1 keeps the pre-tray code path for Linux CI / headless servers without a display.
  • packages/daemon/icons/tray-icon.png — 32×32 PNG copied from desktop-app/src-tauri/icons/32x32.png, embedded via include_bytes! so the daemon stays self-contained.
  • packages/daemon/Cargo.toml — adds tray-icon = 0.21, tao = 0.31, image = 0.25 (png only), tower = 0.5. Spec called for tray-icon = 0.14; bumped to the current cross-platform-stable line that matches what the workspace already pulls transitively.
  • No Tauri changes — lib.rs:480-504 already exits only the UI process on window close (per ADR-031 lifecycle doc) and never signaled the daemon.

Acceptance criteria

  • nodespaced starts a system tray icon on startup
  • Tray menu: Open NodeSpace, Status (shows in-flight call count — proxy for connected clients, since one Tauri client → one stream of RPCs), Quit
  • Open NodeSpace spawns the Tauri UI if not running (path via NODESPACE_UI_BINARY); if a child is already alive, leaves it for the OS to focus (cross-process window focus is platform-specific and tracked separately)
  • Quit gracefully shuts down the gRPC server (drains via serve_with_shutdown) and all connected clients
  • Closing the Tauri window already exits only the UI process — daemon + tray stay alive (unchanged Tauri behavior, validated against lib.rs:480-504)
  • Tray icon updates to reflect daemon health (running / error state) — out of scope for v1; current icon is static. Adding a degraded-state icon swap when health-check probes fail is a follow-up.
  • Works on macOS (primary)
  • Linux & Windows: tray-icon is cross-platform; same code path. Headless mode (NODESPACED_HEADLESS=1) for systems without a display.
  • Tests pass (bun run test: 3918/3918; cargo test -p nodespace-daemon: 9/9)
  • Code passes bun run quality:fix (0 errors, 0 warnings)

Design notes

Why a tower::Layer for client count? tonic doesn't expose a connection-level counter, and per-RPC tracking is a useful proxy for the Status menu: an idle Tauri client shows 0; an actively-streaming one shows 1+. Re-doing this as true connection tracking is straightforward later (interceptor on Server::layer plus tonic's connect/disconnect hooks).

Why tao 0.31 over the latest 0.35? It's what tray-icon 0.21 pulls in transitively; staying on the same version avoids a duplicate tao in the daemon binary. The Tauri side still gets tao 0.34 (its own pin) — two taos in the workspace cargo tree, but never in the same binary.

Threading model. macOS's NSStatusItem is main-thread-only, so main() is no longer #[tokio::main]. It builds a multi-thread runtime explicitly, hands it to a worker via runtime.spawn, and lets tray::run take the main thread. The seed closure pattern keeps the two pieces decoupled — tray::run doesn't know there's a gRPC server, and the gRPC server doesn't know there's a tray (except via the TrayController it receives).

Test plan

  • cargo clippy -p nodespace-daemon --all-targets -- -D warnings: clean
  • cargo test -p nodespace-daemon: 2 lib tests + 7 gRPC round-trip integration tests, all passing
  • bun run test: 3918 passed (matches baseline 3918, 0 regressions)
  • bun run quality:fix: 0 errors, 0 warnings
  • Manual macOS smoke test before merge: build cargo build -p nodespace-daemon, run ./target/debug/nodespaced, confirm menu bar icon appears, Open NodeSpace spawns the UI when NODESPACE_UI_BINARY is set, Quit terminates the daemon cleanly
  • Manual Windows / Linux smoke test: out of scope for this PR; tray-icon is reported to work cross-platform but we don't ship those yet

🤖 Generated with Claude Code

…#241)

ADR-031 places the system tray on the long-running `nodespaced` process so
the tray (and the daemon) survive Tauri UI restarts. Implements a `tao`
event loop on the main thread with the tonic gRPC server on a worker
tokio runtime, signalled via a shared `TrayController`.

- packages/daemon/src/tray.rs (new): event loop, menu (Open NodeSpace /
  Status: N active calls / Quit), Tauri binary spawn-or-skip, and a
  `tower::Layer` that reports in-flight RPC counts to the Status label.
- packages/daemon/src/main.rs: restructured to run the tray on the main
  thread and the gRPC server on a worker; `NODESPACED_HEADLESS=1` keeps the
  pre-tray code path for headless CI / Linux servers without a display.
- packages/daemon/icons/tray-icon.png: 32×32 PNG copied from
  desktop-app/src-tauri/icons/32x32.png, embedded via include_bytes!.
- packages/daemon/Cargo.toml: add tray-icon 0.21, tao 0.31, image 0.25
  (png only), tower 0.5.

No changes to Tauri code: closing the UI window already exits the Tauri
process only (per ADR-031 lifecycle doc) and never signaled the daemon.

Tests:
- Frontend: 3918 passed (matches baseline)
- Daemon: 2 lib tests + 7 grpc round-trip tests, all passing
- cargo clippy --all-targets -- -D warnings: clean
- bun run quality:fix: 0 errors, 0 warnings

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Code Review: PR #1143 — Move system tray ownership to nodespaced daemon

Review Type: Initial Review
Branch: feature/issue-241-daemon-system-tray
Commits reviewed: e8cd3f58
Validation performed locally:

  • cargo test -p nodespace-daemon → 9/9 passing
  • cargo clippy -p nodespace-daemon --all-targets -- -D warnings → clean
  • ADR-031 + daemon-cli-lifecycle.md cross-referenced against implementation

Summary

Solid, well-thought-out implementation of a tricky problem: hosting a main-thread tao event loop alongside a worker-runtime tonic server, with clean lifecycle handoff via tokio::sync::Notify and a tower::Layer for status reporting. Threading model is sound, documentation is thorough, and module boundaries are appropriate (the tray::run API takes a seed closure so the gRPC and tray sides stay decoupled). The PR description is honest about deferred work (icon health states; cross-process focus).

A few real findings below — none are blockers, but the dead-field workaround in TrayState and the Mutex-around-JoinHandle pattern are worth tightening.


Requirements Check (Issue #241)

AC Status Notes
Tray icon on startup Met tray::run invoked from main; icon is built inside Init callback.
Tray menu: Open / Status / Quit Met build_menu at tray.rs:94-114.
Open NodeSpace spawns or focuses Partial Spawns when no live child; falls through to OS when one exists. Cross-process focus is explicitly deferred and tracked elsewhere. Acceptable v1 scope — see note below.
Quit gracefully shuts down Met serve_with_shutdown drains, then main awaits JoinHandle.
Close window does not quit daemon Met (already correct upstream) Verified at desktop-app/src-tauri/src/lib.rs:480-504. No Tauri changes needed.
Health-state icon updates Not met Explicitly deferred in PR description. Reasonable scope decision — there is no health-check probe in the daemon yet, so a status icon would be cosmetic. Open a follow-up.
Cross-platform Met (macOS verified by build; Linux/Windows by code path) Headless fallback exists.
bun run test:all passes Met 3918 frontend + 9 Rust daemon tests, per PR description.
bun run quality:fix clean Met Reported clean.

Verdict on deferred ACs: Both deferrals are pragmatic — the missing pieces depend on infrastructure (health probes; gRPC focus channel) that doesn't exist yet. Opening a tracking follow-up is the right call.


Findings

Threading & lifecycle correctness (the user's question #1)

The ordering in main.rs:83-96 is sound. The seed closure runs synchronously inside tray::run before the event loop starts (tray.rs:152-156), so by the time tray::run returns, the gRPC JoinHandle is guaranteed to be in the Mutex<Option<...>> slot. The only failure mode that matters: if tray::run itself returns Err before reaching the user-event branch (e.g., EventLoopBuilder::build panicked), the seed closure already fired and serve_grpc is running with no way to be told to stop except via OS signal. That's mitigated by serve_grpc's own install_shutdown_handler, so an unhandled tray init error degrades to "you must Ctrl-C the daemon." That's acceptable but worth a comment.

There is one panic-safety concern worth tightening — see 🟢 below on the Mutex slot.

tower::Layer mem::replace pattern (the user's question #2)

The pattern at tray.rs:362-372 is correct as written for tonic's typical usage. tonic wraps services in BoxCloneService / MakeService patterns that always call poll_ready on self.inner (the clone you leave behind) before the next call, not on the moved-out instance. The classic foot-gun (using the not-yet-poll_ready'd clone) doesn't apply here because tonic's per-request service is built by cloning a ready service and immediately calling it.

That said, the conventional formulation in the tower docs is to clone into the future and move the readied original out, which makes the poll_ready-before-call contract more obviously preserved. Either form works; this one is fine.

NODESPACED_HEADLESS=1 bifurcation (the user's question #3)

Justified — Linux CI absolutely will hit display-server failures otherwise, and the headless path is small (one function, ~15 lines). The duplication risk is minimal because both paths funnel through build_node_service and install_shutdown_handler. Keep it.

open_ui semantics (user question #4)

Deferring cross-process focus is fine for v1. The current behavior — "spawn if no live child, otherwise leave to OS" — is well-documented in code (tray.rs:227-233) and aligns with daemon-cli-lifecycle.md:19. The follow-up will need a gRPC "show/focus" stream from daemon → UI; that's a meaningful chunk of work and shouldn't block this PR.

Icon path duplication (user question #5)

Two copies of the same 1.5KB asset. Workspace-level assets/ is the cleaner long-term answer, but it's not urgent — the asset is small, build-embedded, and unlikely to drift in a way that breaks anything (worst case: tray icon stops matching the app icon, which a code reviewer would catch). 🟢 follow-up nit.

Two tao versions (user question #6)

Real but acceptable. cargo tree confirms tao 0.31 in the daemon and tao 0.34 in Tauri's tree — different binaries, no runtime conflict. Bumping tray-icon past 0.21 would re-unify, but tray-icon 0.22+ pulls in a newer muda API; not worth the churn now. 🟢

Status semantics: "active calls" ≠ "connected clients" (user question #7)

This is the closest thing to a substantive design concern, but it's documented honestly in the PR description and in code (tray.rs:307-309). For the current single-Tauri-client topology it's a perfectly reasonable proxy (an idle UI → 0; a streaming one → 1+). The real client-count metric requires hooking tonic's connection lifecycle events, which the upstream API doesn't expose cleanly yet. Ship the proxy with the existing comment.


🟡 Important

Dead field in TrayState + load-to-suppress-lint

📁 packages/daemon/src/tray.rs:84, 218, 265-266

struct TrayState {
    ...
    active_rpcs: Arc<AtomicUsize>,  // line 84
    ...
}

// in open_ui:
// Touch the counter purely so unused-field lints don't fire; the
// value isn't actually consumed here.
let _ = self.active_rpcs.load(Ordering::SeqCst);  // line 266

The status-label update path uses the outer active_rpcs captured by the closure (tray.rs:194), not s.active_rpcs. The field on TrayState is genuinely unread. Doing a no-op atomic load to silence the warning is a code smell and contradicts CLAUDE.md's "NO #[allow(dead_code)]. Delete unused code, don't suppress warnings" rule — this is functionally equivalent suppression done with a runtime no-op.

Recommendation: Remove the field from TrayState and the active_rpcs.clone() argument from initialize_tray. The closure capture at line 149 already gives the event loop what it needs.

Principle: Single source of truth — the same atomic shouldn't be reachable through two paths when only one is used. Future maintainers reading the struct will assume the field is live.

Mutex<Option<JoinHandle>> is heavier than necessary

📁 packages/daemon/src/main.rs:79-86

let grpc_handle: std::sync::Mutex<Option<tokio::task::JoinHandle<Result<()>>>> =
    std::sync::Mutex::new(None);
let grpc_handle_ref = &grpc_handle;

tray::run(move |controller| {
    let join = runtime_handle.spawn(async move { serve_grpc(controller).await });
    *grpc_handle_ref.lock().expect("grpc handle slot poisoned") = Some(join);
})?;

The seed closure runs synchronously and exactly once before tray::run returns. There's no concurrent access to the slot — the mutex never has more than one acquirer at a time. Two cleaner options:

  1. Cell<Option<JoinHandle>> if you want to keep the slot pattern.
  2. Change tray::run's seed closure signature to FnOnce(TrayController) -> T and return T from run, eliminating the slot entirely.

Option 2 also drops the .expect("grpc handle slot poisoned") (twice). Worth doing while the seed-closure API is new and has no other callers.

Principle: Use the minimum-strength synchronization primitive that the access pattern requires. Mutex signals "potential concurrent access" to readers; here there is none.


🟢 Suggestions

Ordering::SeqCst is overkill for a counter

📁 packages/daemon/src/tray.rs:60, 70, 194, 266

AtomicUsize::fetch_add / fetch_sub / load for an unsynchronized counter only need Relaxed. The status label doesn't depend on ordering relative to any other memory operation. Nit; SeqCst-everywhere is a defensible default, but using the right ordering documents intent.

Env-var test mutates global state

📁 packages/daemon/src/tray.rs:289-301

std::env::set_var / remove_var are process-global and cargo test runs tests in parallel by default. The test comment acknowledges this ("parallel tests share the process env") but the mitigation (combining set+unset into one test) doesn't help if another test elsewhere ever reads NODESPACE_UI_BINARY. Today that's only used in resolve_ui_binary, so the race window is narrow, but future contributors won't see the trap.

Suggestion: Either gate this test with #[ignore] + a comment explaining how to run it, or factor resolve_ui_binary to take an &dyn EnvProvider so it's testable without touching real env vars. Low priority.

Tray init error path doesn't surface to main

📁 packages/daemon/src/tray.rs:165-176

If initialize_tray fails, the event loop logs and continues running with state == None. Menu events become no-ops because of the let Some(s) = state.as_mut() else { return }; guard, so the daemon is functionally headless-with-no-quit-button until SIGTERM. The PR description doesn't flag this. Not a bug — but worth either:

  • Promoting to ControlFlow::Exit if the operator probably wants the daemon to crash so a supervisor restarts it; or
  • Adding a "tray init failed; only SIGTERM/SIGINT can stop nodespaced" log line at warn level so ops sees it.

Status label phrasing

📁 packages/daemon/src/tray.rs:102, 196

"Status: 0 active calls" reads strangely in a menu (most menu bar tools use "Idle" / "1 client" / etc.). Since the PR explicitly notes this is a proxy for "connected clients," consider:

  • "Active RPCs: N" (matches the code's terminology), or
  • "Idle" / "N active calls" (toggle on count == 0).

Pure polish.

_status shadowing

📁 packages/daemon/src/tray.rs:246

Ok(Some(_status)) => {
    self.ui_child = None;
}

_status is unused but bound for documentation. Fine, but consider Ok(Some(_exit_status)) for clarity. Nit.


Recommendation: APPROVE (with optional cleanup)

This is a net-positive change that lands a well-engineered piece of infrastructure. The 🟡 items above are genuine cleanup opportunities (dead field + over-strong synchronization) but neither risks correctness. The deferred ACs are properly tracked and depend on infrastructure that should be built separately. I'd suggest addressing the dead-field issue before merge — it's a five-line fix and removes a workaround that future readers will trip on — but the rest can be follow-ups.

The threading model, the tower::Layer implementation, and the seed_controller decoupling pattern are all good calls that will pay off when more lifecycle work lands on the daemon.

Code review feedback on PR #1143:

1. 🟡 Remove dead `active_rpcs` field from `TrayState` and the no-op
   `load(Ordering::SeqCst)` that was masking the unused-field lint.
   The status-label path uses the outer atomic captured by the event-loop
   closure, not the struct field. (Violated CLAUDE.md "delete unused code,
   don't suppress warnings" rule.)

2. 🟡 Replace `Mutex<Option<JoinHandle>>` slot in `main.rs` with a value
   returned from `tray::run`. `seed_controller` is now
   `FnOnce(TrayController) -> T`, and `run` returns `Result<T>`.

   This required switching from `event_loop.run` (which has return type `!`
   and calls `process::exit(0)` on macOS) to `event_loop.run_return` —
   which fixes a latent bug: on macOS the `runtime.block_on(grpc_handle)`
   after `tray::run` was unreachable. With `run_return`, the gRPC server
   actually gets to drain on Quit. `run_return`'s documented mid-resize
   caveat doesn't apply (daemon has no window, only a tray icon).

3. 🟢 `Ordering::SeqCst` → `Ordering::Relaxed` on the RPC counter. The
   status label doesn't synchronize with any other memory operation.

Skipped (with justification):
- Env-var test refactor: introducing an EnvProvider trait for one helper
  is over-engineering; existing comment documents the trap.
- Tray init error → ControlFlow::Exit: behavior change that deserves a
  separate decision; current error-log behavior is correct for the
  "daemon stays serving even without tray" model.
- Status label wording, _status shadowing, icon-dir consolidation: pure
  polish, no maintainability cost.

Tests:
- cargo test -p nodespace-daemon: 9/9 (2 lib + 7 grpc round-trip)
- cargo clippy -p nodespace-daemon --all-targets -- -D warnings: clean
- bun run quality:fix: 0 errors, 0 warnings
- bun run test: 3918/3918 (baseline match)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@malibio

malibio commented May 17, 2026

Copy link
Copy Markdown
Collaborator Author

Review feedback addressed (commit 8a1b98d)

✅ Addressed (3)

🟡 Dead field in TrayState + load-to-suppress-lint (tray.rs)
Removed active_rpcs: Arc<AtomicUsize> from TrayState and dropped the no-op load(Ordering::SeqCst) in open_ui. The status-label path correctly uses the outer atomic captured by the event-loop closure; the struct field was unreachable. The runtime no-op was effectively #[allow(dead_code)] in disguise, which CLAUDE.md prohibits.

🟡 Mutex<Option<JoinHandle>> overkill (main.rs + tray.rs)
Refactored tray::run to FnOnce(TrayController) -> T returning Result<T>. The Mutex/expect slot in main.rs is gone; the gRPC JoinHandle flows back as a value.

This required switching from event_loop.run to event_loop.run_return. Caught a latent bug: tao's event_loop.run returns ! and calls process::exit(0) on macOS at ControlFlow::Exit, which meant the runtime.block_on(grpc_handle) after tray::run was unreachable on macOS. With run_return, the gRPC server actually gets to drain on Quit. run_return's documented mid-resize caveat doesn't apply — the daemon has no window, only a tray icon.

🟢 Ordering::SeqCst → Ordering::Relaxed (tray.rs)
Changed all three sites on the RPC counter. The status label doesn't synchronize with any other memory operation.

⏭️ Skipped (3) — with reasoning

🟢 Env-var test refactor: introducing an EnvProvider trait or #[ignore] flag for one tiny helper is over-engineering. The trap is narrow (single env var unique to this module) and the existing comment documents it. Will revisit if a second test ever wants to read this var.

🟢 Tray init error → ControlFlow::Exit: this is a behavior change worth a separate decision. The current "log error, keep serving gRPC" path matches the daemon-stays-up-even-if-display-server-died model. A supervisor-restart policy can be wired explicitly if/when one exists.

🟢 Status label wording / _status shadowing / icon-dir consolidation: pure polish, no maintainability cost. Two-copies-of-the-same-1.5KB-PNG isn't a load-bearing concern; if a workspace-level assets/ dir lands later for other reasons, the tray icon can move then.

Tests after changes

  • cargo test -p nodespace-daemon: 9/9 passing (2 lib + 7 gRPC round-trip)
  • cargo clippy -p nodespace-daemon --all-targets -- -D warnings: clean
  • bun run quality:fix: 0 errors, 0 warnings
  • bun run test: 3918/3918 (baseline match)

Re-Review Decision

Decision: RE-REVIEW NEEDED

Rationale: The event_loop.run → run_return switch is a substantive control-flow change that surfaced a latent macOS-only bug. The Quit-then-drain path now actually executes on macOS where it previously didn't. Worth a second pass to confirm the new lifecycle ordering is sound and that nothing else in the daemon assumed the never-returns semantics of the previous event_loop.run call.

The dead-field removal and Relaxed ordering changes are straightforward and don't need re-verification on their own.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Re-Review: PR #1143 — Move system tray ownership to nodespaced daemon

Review Type: Re-Review (delta only)
Branch: feature/issue-241-daemon-system-tray
Previous commit reviewed: e8cd3f58
New commit under review: 8a1b98d8
Validation performed locally:

  • cargo test -p nodespace-daemon -> 9/9 passing (2 lib + 7 grpc round-trip)
  • cargo clippy -p nodespace-daemon --all-targets -- -D warnings -> clean
  • tao 0.31.1 source in ~/.cargo/registry cross-referenced for run_return semantics

Previous Review Summary

The initial review (commit e8cd3f58) identified:

  • Important (Yellow): Dead active_rpcs field on TrayState plus a no-op load(Ordering::SeqCst) used to silence the unused-field lint — a CLAUDE.md violation in spirit.
  • Important (Yellow): Mutex<Option<JoinHandle>> slot in main.rs was heavier-than-required synchronization for a write-once-then-read pattern. Suggested either Cell or a FnOnce(TrayController) -> T seed-closure API returning T.
  • Suggestion (Green): Ordering::SeqCst on the RPC counter was overkill; Relaxed is sufficient since the label doesn't synchronize with any other memory operation.
  • Other green nits (env-var test, tray init error path, status wording, icon directory, _status shadowing) which the author elected to skip with stated justifications.

Recommendation was APPROVE with optional cleanup, with the dead-field item flagged as worth fixing before merge.


Delta Verification

Did the two yellow findings actually get fixed?

1. Dead active_rpcs field on TrayState — Confirmed fixed.

Verified at packages/daemon/src/tray.rs:

  • TrayState no longer carries active_rpcs (lines 81-89)
  • initialize_tray signature is now (ui_binary: Option<PathBuf>) -> Result<TrayState> (line 216) — the parameter is gone
  • The no-op let _ = self.active_rpcs.load(...) in open_ui is gone (compare old line 266 vs new lines 244-275)
  • The status-label path correctly uses the outer active_rpcs captured by the event-loop closure at line 203

Net: single source of truth restored. The struct field that violated CLAUDE.md's "no dead code, no suppression" rule is gone. Clean fix.

2. Mutex<Option<JoinHandle>> slot — Confirmed fixed via the suggested Option-2 path (closure returns T).

Verified at packages/daemon/src/main.rs:78-89:

let grpc_handle = tray::run(move |controller| {
    runtime_handle.spawn(async move { serve_grpc(controller).await })
})?;
runtime.block_on(grpc_handle).context(...)?.context(...)?;

And the tray::run signature at tray.rs:145:

pub fn run<T>(seed_controller: impl FnOnce(TrayController) -> T) -> Result<T>

Both .expect("grpc handle slot poisoned") calls are gone. The seed closure runs once at tray.rs:161, captures seeded, and the value flows out via Ok(seeded) at line 213. Cleaner than the prior pattern, no synchronization primitive needed.

3. Ordering::SeqCst -> Ordering::Relaxed — Confirmed at all three sites: tray.rs:60, :70, :203. Correct change; the counter has no memory-ordering relationship to any other operation in this module.


Is the event_loop.run_return switch sound?

This is the substantive change in the new commit. I verified the following from the tao 0.31.1 source on disk:

a) run_return exists and has the documented semantics.

tao 0.31.1/src/platform/run_return.rs defines EventLoopExtRunReturn::run_return(&mut self, F) -> i32 where F: FnMut(...) (non-'static). The doc string says: "returns control flow to the caller when control_flow is set to ControlFlow::Exit."

b) The platform implementations confirm that run is run_return + process::exit.

This is true on all three desktop platforms, not just macOS:

  • platform_impl/macos/event_loop.rs:200-206: fn run(...) -> ! { let exit_code = self.run_return(callback); process::exit(exit_code); }
  • platform_impl/linux/event_loop.rs:970-976: same pattern
  • platform_impl/windows/event_loop.rs:217-223: same pattern

So the latent bug the commit message calls "macOS-only" was actually present on Linux and Windows too — runtime.block_on(grpc_handle) after tray::run was unreachable on every platform that uses event_loop.run. Not a blocker for the PR (the fix is correct everywhere), but the commit message's "latent macOS-only bug" framing is slightly understated. Worth noting in the eventual squash-merge commit message.

c) The documented caveat for run_return doesn't apply.

The doc warns: "this function will not return on Windows or macOS while a window is getting resized." The daemon has no window — only a tray icon, which is not a window and is not resized. The comment at tray.rs:140-144 reflects this correctly.

d) New lifecycle ordering is correct.

I traced the Quit path end-to-end:

  1. User picks Quit (tray.rs:194)
  2. quit_notify.notify_waiters() (tray.rs:196) wakes the shutdown_controller.shutdown() awaiter in serve_grpc
  3. *control_flow = ControlFlow::Exit (tray.rs:197)
  4. Worker runtime sees shutdown() resolve and tonic's serve_with_shutdown begins draining in-flight RPCs (main.rs:147)
  5. Event loop processes the Exit flag and run_return returns (sometime after step 3 — exact timing platform-dependent, but irrelevant)
  6. tray::run returns Ok(seeded) where seeded is the gRPC JoinHandle
  7. runtime.block_on(grpc_handle) (main.rs:87) waits for serve_grpc to fully complete the drain, then unpacks the nested Result

This is the property the previous code couldn't deliver: block_on(grpc_handle) is now reachable and actually drains the server. Steps 4 and 5 can race (drain completing before or after run_return returns) but the synchronization is by block_on waiting on the JoinHandle — order doesn't matter.

Two subtleties worth flagging, neither blocking:

  • Notify::notify_waiters semantics: it wakes only currently-registered waiters, not future ones. Since serve_grpc's shutdown_controller.shutdown().await is registered well before Quit can fire (the tokio::select! arm enters notified() on first poll), this is safe. But if anyone ever adds a second consumer of shutdown() that registers lazily, they'd miss the notification. Not worth changing now; a comment near notify_waiters() clarifying this would be defensive.
  • gRPC tasks panicking inside the runtime: the new block_on(grpc_handle).context("gRPC task panicked")? returns an error to main, which then returns from fn main -> Err. The runtime gets dropped (synchronously) on the way out, which will abort any other lingering tasks (signal handler, etc.). This is fine for a shutdown path; no change needed.

e) Cross-platform user-visible behavior change.

Previously on all three platforms: tray Quit -> process::exit(0) mid-drain. Any in-flight RPC would be cut off; the tonic serve_with_shutdown future would be dropped without finishing its drain loop. The user-visible difference is subtle (RPC clients see connection-reset rather than a clean response) but real, and the new behavior is clearly the correct one.

On Linux/X11/Wayland specifically: run_return is documented to return 1 on display-server disconnect (vs Quit's normal exit). The current code ignores the i32 return value of run_return (which is the right call — we already log Quit at tray.rs:195, and the unrelated "display server died" case is observable via the tray initialization log path). No regression.


Skipped Items — Sanity Check

  • Env-var test refactor: Concur. Introducing an EnvProvider trait or #[ignore] flag for a single 2-line helper crosses into YAGNI territory. The existing combined-set+unset test plus the comment at tray.rs:293-295 documents the trap adequately. Defer until a second test wants to read this env var.
  • Tray init error -> ControlFlow::Exit: Reasonable defer. "Daemon stays serving even if display server died" is a defensible policy (a supervisor like systemd or launchd can restart the daemon on its own schedule), and changing this is a product decision that deserves its own discussion. Current path is "log error + serve gRPC only" which is operationally acceptable.
  • Status wording / _status shadowing / icon-dir consolidation / two tao versions: All pure polish. The PR author called them green nits, and they should stay green. Two tao versions in particular: cargo tree -i tao confirms only tao 0.31.1 in the daemon's tree; tao 0.34 is on the Tauri side of the workspace and is a separate binary entirely. No runtime interaction.

All three skips are justified.


Findings on the New Commit

Critical Issues

None.

Suggested Improvements

None blocking. Two minor observations from the verification above:

  • tray.rs:196 — Notify::notify_waiters() one-line comment: Consider adding a single-line comment noting that the serve_grpc-side shutdown_controller.shutdown() await is guaranteed to be registered before Quit can be clicked (the gRPC server is brought up synchronously in the seed closure). Defensive against future code that adds a lazy waiter. Strictly optional — current code is correct.

  • Commit message accuracy: The fix isn't macOS-only; Linux and Windows also process::exit from event_loop.run. The squash-merge commit message can be tightened to say "fixes drain-on-Quit on all desktop platforms" rather than "macOS-only." Doesn't affect the code at all.

Nitpicks

  • Nit: tray.rs:213 returns Ok(seeded) after run_return. Since run_return returns an i32 exit code that is currently discarded, you could log it at debug level if non-zero (Linux X11/Wayland disconnect = 1). Pure polish; current behavior is fine because we log Quit explicitly at line 195.

  • Nit: The doc comment at tray.rs:140-144 is excellent. Consider a one-liner in the commit body referencing the upstream tao source paths (platform_impl/{macos,linux,windows}/event_loop.rs::run) so future readers can verify the claim without digging through cargo's registry cache.


Recommendation: APPROVE

Both yellow findings from the initial review are cleanly addressed:

  • Dead field removal restores single source of truth, removes the runtime-no-op workaround.
  • Closure-returns-T refactor eliminates the Mutex entirely, which also surfaced and fixed a latent unreachable-code bug on all three desktop platforms.

The event_loop.run_return switch is sound, well-documented in the code, and verified against the tao 0.31.1 source. The new lifecycle ordering is correct: tray Quit -> notify -> Exit -> run_return returns -> block_on(grpc_handle) drains. The documented run_return caveat (mid-resize) genuinely doesn't apply to a windowless daemon.

The green-tier Relaxed ordering change is correct and the skipped items are all defensible scope decisions.

This is a net-positive set of changes that materially improves both code quality and correctness over commit e8cd3f58. No further blocking work required.

Re-review on PR #1143 flagged a defensive doc opportunity: `notify_waiters`
wakes only currently-registered waiters, so any future consumer of
`shutdown()` must register before Quit can fire. The current architecture
already satisfies this (gRPC server is spawned synchronously inside the
seed closure before the event loop processes user input), but a comment
prevents future code from accidentally violating the invariant.

Skipped (with justification):
- Log non-zero `run_return` exit code at debug: pure polish; Quit is
  already logged explicitly at info level.
- Reference upstream tao source paths in commit body: ties documentation
  to a specific cargo registry cache layout that will rot.

Tests: clippy clean; lib tests still 2/2 passing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@malibio

malibio commented May 17, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review feedback addressed (commit 669f593)

✅ Addressed (1)

🟢 Document Notify::notify_waiters ordering invariant (tray.rs:194-200)
Added a 6-line comment explaining that notify_waiters only wakes already-registered waiters and that the gRPC server's shutdown().await is guaranteed to be parked before Quit can fire (it's spawned synchronously inside the seed closure). Defensive doc for future maintainers who might add a lazy waiter.

📌 Note for the merger

The re-review correctly pointed out that the latent drain-on-Quit bug fixed by event_loop.run_return was not macOS-only — tao 0.31.1's event_loop.run calls process::exit on Linux and Windows too (verified at platform_impl/{macos,linux,windows}/event_loop.rs::run). When squash-merging, please tighten the commit message from "macOS-only" to "all desktop platforms."

⏭️ Skipped (2) — with reasoning

🟢 Log non-zero run_return exit code at debug level: pure polish. Quit is already logged explicitly at info level; the i32 exit code is primarily a display-server-disconnect signal that the tray-init log path already surfaces.

🟢 Reference upstream tao source paths in commit body: ties the commit message to a specific cargo registry cache layout (~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tao-0.31.1/...). Future readers would hit dead links; the comment block at tray.rs:140-144 already explains the why in stable terms.

Tests after changes

  • cargo clippy -p nodespace-daemon --all-targets -- -D warnings: clean
  • cargo test -p nodespace-daemon --lib: 2/2 passing (no behavior changes; doc-comment only)

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The single change is a 6-line code comment with no behavior impact. The re-review already gave an APPROVE verdict on the substantive changes in commit 8a1b98d8. Ready for merge pending any other approvals.

@malibio
malibio merged commit efb6749 into main May 17, 2026
@malibio
malibio deleted the feature/issue-241-daemon-system-tray branch May 17, 2026 21:15
malibio added a commit that referenced this pull request Jun 22, 2026
* Move system tray ownership from Tauri app to nodespaced daemon (closes #241)

ADR-031 places the system tray on the long-running `nodespaced` process so
the tray (and the daemon) survive Tauri UI restarts. Implements a `tao`
event loop on the main thread with the tonic gRPC server on a worker
tokio runtime, signalled via a shared `TrayController`.

- packages/daemon/src/tray.rs (new): event loop, menu (Open NodeSpace /
  Status: N active calls / Quit), Tauri binary spawn-or-skip, and a
  `tower::Layer` that reports in-flight RPC counts to the Status label.
- packages/daemon/src/main.rs: restructured to run the tray on the main
  thread and the gRPC server on a worker; `NODESPACED_HEADLESS=1` keeps the
  pre-tray code path for headless CI / Linux servers without a display.
- packages/daemon/icons/tray-icon.png: 32×32 PNG copied from
  desktop-app/src-tauri/icons/32x32.png, embedded via include_bytes!.
- packages/daemon/Cargo.toml: add tray-icon 0.21, tao 0.31, image 0.25
  (png only), tower 0.5.

No changes to Tauri code: closing the UI window already exits the Tauri
process only (per ADR-031 lifecycle doc) and never signaled the daemon.

Tests:
- Frontend: 3918 passed (matches baseline)
- Daemon: 2 lib tests + 7 grpc round-trip tests, all passing
- cargo clippy --all-targets -- -D warnings: clean
- bun run quality:fix: 0 errors, 0 warnings

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Address review: cleaner tray::run handoff and lifecycle fix

Code review feedback on PR #1143:

1. 🟡 Remove dead `active_rpcs` field from `TrayState` and the no-op
   `load(Ordering::SeqCst)` that was masking the unused-field lint.
   The status-label path uses the outer atomic captured by the event-loop
   closure, not the struct field. (Violated CLAUDE.md "delete unused code,
   don't suppress warnings" rule.)

2. 🟡 Replace `Mutex<Option<JoinHandle>>` slot in `main.rs` with a value
   returned from `tray::run`. `seed_controller` is now
   `FnOnce(TrayController) -> T`, and `run` returns `Result<T>`.

   This required switching from `event_loop.run` (which has return type `!`
   and calls `process::exit(0)` on macOS) to `event_loop.run_return` —
   which fixes a latent bug: on macOS the `runtime.block_on(grpc_handle)`
   after `tray::run` was unreachable. With `run_return`, the gRPC server
   actually gets to drain on Quit. `run_return`'s documented mid-resize
   caveat doesn't apply (daemon has no window, only a tray icon).

3. 🟢 `Ordering::SeqCst` → `Ordering::Relaxed` on the RPC counter. The
   status label doesn't synchronize with any other memory operation.

Skipped (with justification):
- Env-var test refactor: introducing an EnvProvider trait for one helper
  is over-engineering; existing comment documents the trap.
- Tray init error → ControlFlow::Exit: behavior change that deserves a
  separate decision; current error-log behavior is correct for the
  "daemon stays serving even without tray" model.
- Status label wording, _status shadowing, icon-dir consolidation: pure
  polish, no maintainability cost.

Tests:
- cargo test -p nodespace-daemon: 9/9 (2 lib + 7 grpc round-trip)
- cargo clippy -p nodespace-daemon --all-targets -- -D warnings: clean
- bun run quality:fix: 0 errors, 0 warnings
- bun run test: 3918/3918 (baseline match)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Address re-review: document Notify::notify_waiters ordering invariant

Re-review on PR #1143 flagged a defensive doc opportunity: `notify_waiters`
wakes only currently-registered waiters, so any future consumer of
`shutdown()` must register before Quit can fire. The current architecture
already satisfies this (gRPC server is spawned synchronously inside the
seed closure before the event loop processes user input), but a comment
prevents future code from accidentally violating the invariant.

Skipped (with justification):
- Log non-zero `run_return` exit code at debug: pure polish; Quit is
  already logged explicitly at info level.
- Reference upstream tao source paths in commit body: ties documentation
  to a specific cargo registry cache layout that will rot.

Tests: clippy clean; lib tests still 2/2 passing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant