Skip to content

Add SettingsService gRPC: daemon config via RPC, delete switch_database (closes #1138) - #1161

Merged
malibio merged 3 commits into
mainfrom
worktree-issue-1138-settings-service-grpc
May 18, 2026
Merged

malibio merged 3 commits into
mainfrom
worktree-issue-1138-settings-service-grpc

Conversation

@malibio

@malibio malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Add SettingsService proto with GetDaemonConfig/UpdateDaemonConfig RPCs and SettingsServiceImpl reading/writing ~/.nodespace/daemon.toml
  • Register SettingsService in nodespaced (headless and tray modes)
  • Add SettingsServiceClient to Tauri GrpcClient; rewrite commands/settings.rs so daemon config fetches via gRPC while display prefs (theme, render_markdown) remain in Tauri local storage
  • Delete AppServices::switch_database() and all hot-swap code; database path changes now persist via gRPC and require a restart
  • Remove savedDatabasePath from settings store; clean up dead database-changed event listeners from app-shell

Test plan

  • cargo build --package nodespace-daemon passes
  • cargo build --package nodespace-app passes
  • bun run test — 128 files / 3916 tests (no regressions vs baseline)
  • bun run quality:fix passes
  • Settings UI shows active database path fetched from daemon config
  • "Change Location..." saves new path to ~/.nodespace/daemon.toml (visible after restart)
  • "Reset to Default" saves default path to ~/.nodespace/daemon.toml
  • Display settings (theme, render_markdown) still update immediately

🤖 Generated with Claude Code

…se (closes #1138)

- Add settings_service.proto with GetDaemonConfig/UpdateDaemonConfig RPCs
- Implement SettingsServiceImpl reading/writing ~/.nodespace/daemon.toml
- Register SettingsService in nodespaced (headless and tray modes)
- Add SettingsServiceClient to Tauri GrpcClient
- Rewrite commands/settings.rs: daemon config fetched via gRPC, display
  prefs (theme, render_markdown) remain in Tauri local storage
- Delete AppServices::switch_database() and all hot-swap code
- Remove savedDatabasePath from settings store (replaced by gRPC config)
- Update database-settings UI: path changes now persist via gRPC,
  restart required instead of in-process hot-swap
- Clean up dead event listeners (database-changed) from app-shell

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This PR is a well-scoped, architecturally sound implementation of the SettingsService gRPC layer. The core design — daemon owns config, Tauri owns display prefs, hot-swap code deleted — is the correct model under ADR-031 and every acceptance criterion is met. The cleanup is thorough: the switch_database hot-swap machinery (Tauri command, AppServices method, all callers, database-changed event listener) is fully removed with no orphaned references found. The code is clean, well-commented, and consistent with the established gRPC service pattern across this codebase.

There is one functional correctness issue worth addressing and one design issue that should at least be documented.


Findings

[Improvement] Concurrent write hazard in update_daemon_config — settings_service.rs, lines 90–103

The UpdateDaemonConfig handler does a read-modify-write across two separate async I/O operations with no locking:

let mut config = self.read_config().await?;   // I/O #1
// ... mutate config ...
self.write_config(&config).await?;             // I/O #2

Two concurrent RPCs (e.g., two frontend windows both changing settings) can interleave: both read the same config, both apply their respective mutation, and the second write silently discards the first mutation. For a single-user desktop app this is low probability today, but SettingsServiceImpl is Send + Sync with no guard, so the race window is structural, not theoretical.

Recommended fix: add a tokio::sync::Mutex field to SettingsServiceImpl and hold it across the read-modify-write in update_daemon_config. A read lock is not needed because get_daemon_config is read-only and does not modify the file.

pub struct SettingsServiceImpl {
    config_path: PathBuf,
    write_lock: tokio::sync::Mutex<()>,
}
// In update_daemon_config:
let _guard = self.write_lock.lock().await;
let mut config = self.read_config().await?;
// mutate ...
self.write_config(&config).await?;

[Improvement] Tauri in-process GrpcClient creates a second SettingsServiceImpl — grpc_client.rs, line 90–91

The in-process Tauri gRPC server (for the embedded runtime) creates its own SettingsServiceImpl::with_default_path(), reading and writing the same ~/.nodespace/daemon.toml file as the standalone nodespaced daemon when it is also running. This means two processes can write the same TOML file simultaneously.

This is a pre-existing architectural tension (the in-process gRPC server is a migration artifact) and the issue description acknowledges nodespaced will eventually replace the in-process server entirely. For now, the risk is limited to development/testing scenarios where both are running. However, it would be worth a brief inline comment here documenting the known dual-writer situation so a future engineer is not surprised by it:

// NOTE: This SettingsServiceImpl reads/writes the same ~/.nodespace/daemon.toml
// as a standalone nodespaced process. The in-process server is a migration artifact
// (see grpc_client.rs module doc); once nodespaced fully replaces it, this
// duplicate instantiation is removed.
let settings_impl = SettingsServiceImpl::with_default_path()
    .map_err(|e| GrpcClientError::InvalidEndpoint(e))?;

[Improvement] database-settings.svelte: restartRequired flag is not surfaced to the user on the "Change Location" path

In app-shell.svelte the select_new_database result correctly shows a restart-required status bar message. However, the same command is also called directly from database-settings.svelte line 22, where the invoke result is typed as { newPath: string; success: boolean } (missing restartRequired) and the restart advisory is never shown — it just silently calls loadSettings(). The status bar feedback from the settings UI panel is weaker than the menu path.

This is not a blocker since both paths call the same Tauri command and both paths ultimately persist via gRPC, but the UX inconsistency could confuse users who change the DB path from Settings and don't see the restart advisory.


Nitpicks

  • Nit: packages/daemon/Cargo.toml pins toml = "0.8" directly rather than adding it to [workspace.dependencies] like serde, serde_json, and chrono. Minor consistency issue — not all workspace deps are currently in the workspace manifest, so this pattern is consistent with some existing crates, but aligning it would reduce future version drift.

  • Nit: with_default_path() uses std::env::var("HOME"). On macOS /Users/malibio is reliable, but dirs::home_dir() (from the dirs crate) is the cross-platform idiomatic approach. Not a problem given macOS-only target today.

  • Nit: The toml crate is not in the workspace Cargo.toml but serde is. Since toml is used only in packages/daemon, the direct pin is acceptable for now, but a comment or follow-up to hoist it would prevent version divergence if another crate adds TOML support later.


Acceptance Criteria Verification

  • SettingsService proto defined and compiled via tonic-build
  • nodespaced handler reads/writes ~/.nodespace/daemon.toml
  • commands/settings.rs fetches daemon config via gRPC; display prefs remain in Tauri local storage
  • switch_database Tauri command deleted
  • AppServices::switch_database() and related hot-swap code deleted
  • Settings UI continues working for both daemon config and display preferences
  • cargo build succeeds (not verified by reviewer, but structure is correct and no obvious compile issues)
  • bun run test:all (tests updated to match new AppSettings interface)
  • bun run quality:fix (embeddings.rs reformatting included)

Verdict

Approve with recommendations. The concurrent write hazard in update_daemon_config is the only behavioral correctness issue; it is low-risk today (single-user, low-frequency operation) but has a clear, low-effort fix. The dual-writer comment is the right documentation to leave for the in-process GrpcClient. The database-settings UX gap is worth a follow-up. None of these block merge of a pre-release, greenfield codebase.

- Add Mutex to SettingsServiceImpl to serialize read-modify-write in
  update_daemon_config, preventing interleaved concurrent RPCs from
  silently discarding each other's writes
- Show restart-required notice in database-settings.svelte after
  path changes (previously only surfaced via menu path / status bar)
- Fix redundant_closure clippy lint in grpc_client.rs

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

Review Feedback Addressed

✅ Fixed: Concurrent write hazard in update_daemon_config — Added Mutex to SettingsServiceImpl to serialize the read-modify-write sequence, preventing interleaved concurrent RPCs from silently discarding each other's writes.

✅ Fixed: Missing restart advisory in database-settings.svelte — Settings panel now shows a restart-required notice after path changes (previously only visible via the menu path / status bar).

✅ Fixed: redundant_closure clippy lint in grpc_client.rs.

⏭️ Skipped: Dual-writer comment on in-process SettingsServiceImpl — Migration-era artifact; will disappear when Tauri connects to a real nodespaced subprocess. Not worth a comment that would need deleting immediately after.

⏭️ Skipped: toml not in workspace deps — Greenfield, not worth workspace churn for one dep in one crate.

⏭️ Skipped: dirs::home_dir() vs std::env::var("HOME") — macOS-only desktop app; adding dirs as a daemon dep for one call is scope creep.

…ettings-service-grpc

# Conflicts:
#	packages/daemon/build.rs
#	packages/daemon/src/lib.rs
#	packages/daemon/src/main.rs
#	packages/desktop-app/src-tauri/src/commands/settings.rs
#	packages/desktop-app/src-tauri/src/lib.rs
#	packages/desktop-app/src-tauri/src/services/grpc_client.rs
@malibio
malibio merged commit ea8849a into main May 18, 2026
@malibio
malibio deleted the worktree-issue-1138-settings-service-grpc branch May 18, 2026 10:52
malibio added a commit that referenced this pull request May 31, 2026
LocalAgentServiceServer was accidentally dropped in ea8849a (PR #1161,
Add SettingsService) when the diff removed it while adding SettingsService.
This caused ListModels, EnsureModelReady, StartSession, and all other
LocalAgent RPCs to return Unimplemented for 13 days.

Also clones node_service before ImportServiceImpl::new() consumes it,
matching the original pattern from PR #1160.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
malibio added a commit that referenced this pull request May 31, 2026
 partially)

## Completed in This Session

- [x] Verified issue #1142: Gemma 4 E4B downloads, loads, and streams tokens without ffi error -1
- [x] Found root cause: Gemma 4 tool-call parsing was broken — model emits <|tool_call> special
      tokens but old code used token_to_piece(special=false) which silently dropped them
- [x] Fixed tool-call parsing: replaced custom StreamingToolCallParser + sentinel detection with
      ChatParseStateOaicompat (llama.cpp native streaming parser, handles Gemma 4 natively via
      COMMON_CHAT_FORMAT_PEG_GEMMA4 PEG grammar)
- [x] Confirmed fix works: agent_loop logs show tool_calls=1 per inference round (was 0 before)
- [x] Restored LocalAgentServiceServer registration in daemon main.rs (accidentally dropped in
      PR #1161 ea8849a when SettingsService was added — missing for 13 days)
- [x] Committed and pushed: 3a4efd6 (parser fix), 443bad0 (LocalAgent restore)

## Remaining Work

- [ ] Fix raw token leak in final no-tools inference pass: when the agent loop runs its final
      plain-text pass (no tools), raw tokens like <|tool_call> still stream as ChatChunk::Token
      instead of being consumed by the OAI parser. The content deltas from oai_parser.update()
      are supposed to emit plain text but something is dropping them.
- [ ] Verify plain-text streaming works correctly end-to-end in the UI
- [ ] Close issue #1142 once the above is confirmed

## Current State

- Files modified: packages/nlp-engine/src/chat/mod.rs, packages/daemon/src/main.rs
- Tests status: 51/51 passing (cargo test -p nodespace-nlp-engine -- chat)
- Daemon binary: ~/.nodespace/bin/nodespaced is up to date, running via launchctl
- Gemma 4 E4B model: downloaded at ~/Library/Application Support/NodeSpace/models/

## Context for Next Session

The ChatParseStateOaicompat approach is correct and working for tool-call detection. The
remaining raw token issue is in emit_oai_delta() — the content delta path. When the final
no-tools inference pass runs, each token piece is fed via oai_parser.update(piece, true) and
the C++ layer returns content deltas, but something in the delta JSON parsing or in the
generate_blocking flow is dropping them. Start by adding a tracing::debug! in emit_oai_delta
to log the raw delta_json strings arriving from the OAI parser — confirm whether content
deltas are coming through or whether the parser is silently buffering them.

Key file: packages/nlp-engine/src/chat/mod.rs
- emit_oai_delta() at ~line 465 — parses OAI delta JSON and emits ChatChunk events
- generate_blocking() token loop at ~line 370 — feeds tokens to oai_parser

The 5 "duplicate" tool_call_start blocks seen in gRPC SendMessage output are NOT a bug —
they are 5 ReAct loop iterations each emitting one correct tool call, as expected.

## Acceptance Criteria Status (issue #1142)

- [x] Gemma 4 E4B downloads and loads (5.3GB, no ffi error)
- [x] Tokens stream without ffi error -1
- [x] Tool-call Format detection works (tool_calls=1 per iteration, correct name+args)
- [ ] Plain-text response streaming works (raw tokens not leaking)
- [ ] Results documented on #1142 (partial comment added, full close pending)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
malibio added a commit that referenced this pull request Jun 22, 2026
…se (closes #1138) (#1161)

* Add SettingsService gRPC: daemon config via RPC, delete switch_database (closes #1138)

- Add settings_service.proto with GetDaemonConfig/UpdateDaemonConfig RPCs
- Implement SettingsServiceImpl reading/writing ~/.nodespace/daemon.toml
- Register SettingsService in nodespaced (headless and tray modes)
- Add SettingsServiceClient to Tauri GrpcClient
- Rewrite commands/settings.rs: daemon config fetched via gRPC, display
  prefs (theme, render_markdown) remain in Tauri local storage
- Delete AppServices::switch_database() and all hot-swap code
- Remove savedDatabasePath from settings store (replaced by gRPC config)
- Update database-settings UI: path changes now persist via gRPC,
  restart required instead of in-process hot-swap
- Clean up dead event listeners (database-changed) from app-shell

Co-Authored-By: Claude <[email protected]>

* Address review: fix concurrent write hazard, add restart advisory

- Add Mutex to SettingsServiceImpl to serialize read-modify-write in
  update_daemon_config, preventing interleaved concurrent RPCs from
  silently discarding each other's writes
- Show restart-required notice in database-settings.svelte after
  path changes (previously only surfaced via menu path / status bar)
- Fix redundant_closure clippy lint in grpc_client.rs

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Jun 22, 2026
LocalAgentServiceServer was accidentally dropped in b88096c (PR #1161,
Add SettingsService) when the diff removed it while adding SettingsService.
This caused ListModels, EnsureModelReady, StartSession, and all other
LocalAgent RPCs to return Unimplemented for 13 days.

Also clones node_service before ImportServiceImpl::new() consumes it,
matching the original pattern from PR #1160.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
malibio added a commit that referenced this pull request Jun 22, 2026
 partially)

## Completed in This Session

- [x] Verified issue #1142: Gemma 4 E4B downloads, loads, and streams tokens without ffi error -1
- [x] Found root cause: Gemma 4 tool-call parsing was broken — model emits <|tool_call> special
      tokens but old code used token_to_piece(special=false) which silently dropped them
- [x] Fixed tool-call parsing: replaced custom StreamingToolCallParser + sentinel detection with
      ChatParseStateOaicompat (llama.cpp native streaming parser, handles Gemma 4 natively via
      COMMON_CHAT_FORMAT_PEG_GEMMA4 PEG grammar)
- [x] Confirmed fix works: agent_loop logs show tool_calls=1 per inference round (was 0 before)
- [x] Restored LocalAgentServiceServer registration in daemon main.rs (accidentally dropped in
      PR #1161 b88096c when SettingsService was added — missing for 13 days)
- [x] Committed and pushed: 8a9a9e0 (parser fix), 6c81f7f (LocalAgent restore)

## Remaining Work

- [ ] Fix raw token leak in final no-tools inference pass: when the agent loop runs its final
      plain-text pass (no tools), raw tokens like <|tool_call> still stream as ChatChunk::Token
      instead of being consumed by the OAI parser. The content deltas from oai_parser.update()
      are supposed to emit plain text but something is dropping them.
- [ ] Verify plain-text streaming works correctly end-to-end in the UI
- [ ] Close issue #1142 once the above is confirmed

## Current State

- Files modified: packages/nlp-engine/src/chat/mod.rs, packages/daemon/src/main.rs
- Tests status: 51/51 passing (cargo test -p nodespace-nlp-engine -- chat)
- Daemon binary: ~/.nodespace/bin/nodespaced is up to date, running via launchctl
- Gemma 4 E4B model: downloaded at ~/Library/Application Support/NodeSpace/models/

## Context for Next Session

The ChatParseStateOaicompat approach is correct and working for tool-call detection. The
remaining raw token issue is in emit_oai_delta() — the content delta path. When the final
no-tools inference pass runs, each token piece is fed via oai_parser.update(piece, true) and
the C++ layer returns content deltas, but something in the delta JSON parsing or in the
generate_blocking flow is dropping them. Start by adding a tracing::debug! in emit_oai_delta
to log the raw delta_json strings arriving from the OAI parser — confirm whether content
deltas are coming through or whether the parser is silently buffering them.

Key file: packages/nlp-engine/src/chat/mod.rs
- emit_oai_delta() at ~line 465 — parses OAI delta JSON and emits ChatChunk events
- generate_blocking() token loop at ~line 370 — feeds tokens to oai_parser

The 5 "duplicate" tool_call_start blocks seen in gRPC SendMessage output are NOT a bug —
they are 5 ReAct loop iterations each emitting one correct tool call, as expected.

## Acceptance Criteria Status (issue #1142)

- [x] Gemma 4 E4B downloads and loads (5.3GB, no ffi error)
- [x] Tokens stream without ffi error -1
- [x] Tool-call Format detection works (tool_calls=1 per iteration, correct name+args)
- [ ] Plain-text response streaming works (raw tokens not leaking)
- [ ] Results documented on #1142 (partial comment added, full close pending)

Co-Authored-By: Claude Sonnet 4.6 <[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