Repository navigation
Move system tray ownership to nodespaced daemon (closes #241) - #1143
Conversation
…#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
left a comment
There was a problem hiding this comment.
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 passingcargo clippy -p nodespace-daemon --all-targets -- -D warnings→ clean- ADR-031 +
daemon-cli-lifecycle.mdcross-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 266The 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:
Cell<Option<JoinHandle>>if you want to keep the slot pattern.- Change
tray::run's seed closure signature toFnOnce(TrayController) -> Tand returnTfromrun, 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::Exitif 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]>
Review feedback addressed (commit 8a1b98d)✅ Addressed (3)🟡 Dead field in 🟡 This required switching from 🟢 ⏭️ Skipped (3) — with reasoning🟢 Env-var test refactor: introducing an 🟢 Tray init error → 🟢 Status label wording / Tests after changes
Re-Review DecisionDecision: RE-REVIEW NEEDED Rationale: The The dead-field removal and |
malibio
left a comment
There was a problem hiding this comment.
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-> cleantao 0.31.1source in~/.cargo/registrycross-referenced forrun_returnsemantics
Previous Review Summary
The initial review (commit e8cd3f58) identified:
- Important (Yellow): Dead
active_rpcsfield onTrayStateplus a no-opload(Ordering::SeqCst)used to silence the unused-field lint — a CLAUDE.md violation in spirit. - Important (Yellow):
Mutex<Option<JoinHandle>>slot inmain.rswas heavier-than-required synchronization for a write-once-then-read pattern. Suggested eitherCellor aFnOnce(TrayController) -> Tseed-closure API returningT. - Suggestion (Green):
Ordering::SeqCston the RPC counter was overkill;Relaxedis 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,
_statusshadowing) 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:
TrayStateno longer carriesactive_rpcs(lines 81-89)initialize_traysignature is now(ui_binary: Option<PathBuf>) -> Result<TrayState>(line 216) — the parameter is gone- The no-op
let _ = self.active_rpcs.load(...)inopen_uiis gone (compare old line 266 vs new lines 244-275) - The status-label path correctly uses the outer
active_rpcscaptured 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 patternplatform_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:
- User picks Quit (
tray.rs:194) quit_notify.notify_waiters()(tray.rs:196) wakes theshutdown_controller.shutdown()awaiter inserve_grpc*control_flow = ControlFlow::Exit(tray.rs:197)- Worker runtime sees
shutdown()resolve and tonic'sserve_with_shutdownbegins draining in-flight RPCs (main.rs:147) - Event loop processes the
Exitflag andrun_returnreturns (sometime after step 3 — exact timing platform-dependent, but irrelevant) tray::runreturnsOk(seeded)whereseededis the gRPCJoinHandleruntime.block_on(grpc_handle)(main.rs:87) waits for serve_grpc to fully complete the drain, then unpacks the nestedResult
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_waiterssemantics: it wakes only currently-registered waiters, not future ones. Sinceserve_grpc'sshutdown_controller.shutdown().awaitis registered well before Quit can fire (thetokio::select!arm entersnotified()on first poll), this is safe. But if anyone ever adds a second consumer ofshutdown()that registers lazily, they'd miss the notification. Not worth changing now; a comment nearnotify_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 tomain, which then returns fromfn 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
EnvProvidertrait or#[ignore]flag for a single 2-line helper crosses into YAGNI territory. The existing combined-set+unset test plus the comment attray.rs:293-295documents 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 /
_statusshadowing / icon-dir consolidation / twotaoversions: All pure polish. The PR author called them green nits, and they should stay green. Two tao versions in particular:cargo tree -i taoconfirms onlytao 0.31.1in 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 theserve_grpc-sideshutdown_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::exitfromevent_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:213returnsOk(seeded)afterrun_return. Sincerun_returnreturns ani32exit 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-144is 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]>
Re-review feedback addressed (commit 669f593)✅ Addressed (1)🟢 Document 📌 Note for the mergerThe re-review correctly pointed out that the latent drain-on-Quit bug fixed by ⏭️ Skipped (2) — with reasoning🟢 Log non-zero 🟢 Reference upstream tao source paths in commit body: ties the commit message to a specific cargo registry cache layout ( Tests after changes
Re-Review DecisionDecision: 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 |
…mon-system-tray # Conflicts: # Cargo.lock
* 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]>
Summary
ADR-031 places the system tray on the long-running
nodespaceddaemon 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) —taoevent loop on the main thread, menu with Open NodeSpace / Status: N active calls / Quit, Tauri-binary spawn-or-skip, and atower::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=1keeps the pre-tray code path for Linux CI / headless servers without a display.packages/daemon/icons/tray-icon.png— 32×32 PNG copied fromdesktop-app/src-tauri/icons/32x32.png, embedded viainclude_bytes!so the daemon stays self-contained.packages/daemon/Cargo.toml— addstray-icon = 0.21,tao = 0.31,image = 0.25(png only),tower = 0.5. Spec called fortray-icon = 0.14; bumped to the current cross-platform-stable line that matches what the workspace already pulls transitively.lib.rs:480-504already exits only the UI process on window close (per ADR-031 lifecycle doc) and never signaled the daemon.Acceptance criteria
nodespacedstarts a system tray icon on startupNODESPACE_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)serve_with_shutdown) and all connected clientslib.rs:480-504)tray-iconis cross-platform; same code path. Headless mode (NODESPACED_HEADLESS=1) for systems without a display.bun run test: 3918/3918;cargo test -p nodespace-daemon: 9/9)bun run quality:fix(0 errors, 0 warnings)Design notes
Why a
tower::Layerfor 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 onServer::layerplus tonic's connect/disconnect hooks).Why
tao0.31 over the latest 0.35? It's whattray-icon0.21 pulls in transitively; staying on the same version avoids a duplicatetaoin the daemon binary. The Tauri side still getstao0.34 (its own pin) — twotaos in the workspace cargo tree, but never in the same binary.Threading model. macOS's
NSStatusItemis main-thread-only, somain()is no longer#[tokio::main]. It builds a multi-thread runtime explicitly, hands it to a worker viaruntime.spawn, and letstray::runtake the main thread. The seed closure pattern keeps the two pieces decoupled —tray::rundoesn't know there's a gRPC server, and the gRPC server doesn't know there's a tray (except via theTrayControllerit receives).Test plan
cargo clippy -p nodespace-daemon --all-targets -- -D warnings: cleancargo test -p nodespace-daemon: 2 lib tests + 7 gRPC round-trip integration tests, all passingbun run test: 3918 passed (matches baseline 3918, 0 regressions)bun run quality:fix: 0 errors, 0 warningscargo build -p nodespace-daemon, run./target/debug/nodespaced, confirm menu bar icon appears, Open NodeSpace spawns the UI whenNODESPACE_UI_BINARYis set, Quit terminates the daemon cleanly🤖 Generated with Claude Code