Skip to content

Desktop: live database switcher + client-side routing (ADR-053) - #1598

Merged
mstomar125 merged 1 commit into
NodeSpaceAI:mainfrom
mstomar125:ns/adr053-desktop-db-switcher
Jul 9, 2026
Merged

mstomar125 merged 1 commit into
NodeSpaceAI:mainfrom
mstomar125:ns/adr053-desktop-db-switcher

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Summary

Desktop half of ADR-053 "One Daemon, Multiple Local Databases" (#1533). Adds a sidebar database switcher and client-side x-ns-database-id routing to the Tauri app, so a user can create, register, switch, and manage local databases live — no restart. Builds on the merged daemon side (#1532) and CLI half (#1597).

This is the desktop slice; it does not close #1533 (any remaining polish tracked separately).

Changes

  • GrpcClient routing (services/grpc_client.rs) — a concrete DatabaseIdInterceptor (mirroring the CLI's) stamps x-ns-database-id on the routed data-plane clients (node/import/embeddings/agent_session); settings/local_agent/database_service stay unrouted. set_active_database(id) rebuilds only the routed clients over the same channel (no reconnect) and bumps a generation watch; subscribe_active_database() feeds the watcher. for_id degrades an unparseable id to no-routing rather than poisoning requests.
  • Shared wire constant — DATABASE_ID_HEADER moved to packages/proto/src/lib.rs and re-exported from the daemon's db_routing.rs, so the daemon and every client (CLI, desktop) reference one canonical key. nodespace_daemon::DATABASE_ID_HEADER still resolves (re-export), so the CLI is unaffected.
  • Watcher (watcher.rs) — now rides the shared GrpcClient's routed node client (so WatchNodes carries the active-database header) and select!s on the generation watch, re-opening the stream immediately on a switch. Each event's originating database_id is threaded onto the Tauri payloads.
  • Tauri commands (commands/database.rs) — list_databases, create_database, register_database, set_default_database, rename_database, remove_database, set_active_database.
  • Frontend — database.svelte.ts store (load, switchTo = flush pending → re-point → clear caches → reset workspace → reload, plus create/register/rename/setDefault/remove); database-switcher.svelte in the sidebar header (active db + local/synced glyph; dropdown lists databases with New…/Open…); database-name-dialog.svelte (New/Rename); database-settings.svelte rewritten as a management list; and an isActiveDatabaseEvent database_id guard on all six node/relationship listeners in tauri-sync-listener.ts (empty id = Pro single-db = always applies).
  • Cleanup — deleted the orphaned restart_app command + its registration (zero callers after the earlier database-settings cleanup; graceful_shutdown is retained).

Validation

  • bun run test: 3965 passed / 151 files (baseline 3952/150; +13 new database.test.ts, zero regressions).
  • bun run quality:fix / svelte-check: 0 errors / 0 warnings.
  • Sidecar cargo build --bin nodespaced --bin nodespace succeeds; cargo clippy -p nodespace-app --tests and cargo check -p nodespace-app --tests clean; cargo fmt --check clean.

Notes

  • The watcher::run signature gained a GrpcClient param (it rides the shared channel now instead of opening its own); the two optimistic_echo_race_test.rs call sites were updated.
  • Community-unchanged: a fresh install has one default database; with no switch, routed clients carry an empty interceptor and everything behaves exactly as before.
  • No live GUI run was possible headless; the switch flow (flush/clear/reset/reload + Rust-side watcher re-subscribe) is covered by unit tests + type/clippy checks, and would benefit from a manual click-test on a build with two registered databases.

Wire the desktop app to the daemon's local-database registry so a user can
create, register, rename, remove, and switch between local databases from the
sidebar and Settings.

- GrpcClient stamps the x-ns-database-id routing header via a concrete
  DatabaseIdInterceptor on the routed data-plane clients (node, import,
  embeddings, agent_session); settings, local_agent, and database_service stay
  unrouted. set_active_database rebuilds only the routed clients over the same
  channel and bumps a generation the node-event watcher observes to re-open its
  WatchNodes stream against the newly-active database.
- Move DATABASE_ID_HEADER into nodespace-proto (the shared wire crate) and
  re-export it from the daemon so client and server share one canonical key.
- New database Tauri commands (list/create/register/set_default/rename/remove/
  set_active) wrapping DatabaseService.
- The watcher now rides the shared GrpcClient and stamps each event's
  originating database_id onto the Tauri payload; the frontend drops events
  tagged for a database it is no longer viewing.
- database.svelte.ts store: load/switchTo/create/register/rename/setDefault/
  remove. Switching flushes pending writes, re-points the routed clients, clears
  the node and structure-tree caches, resets the workspace to the new database's
  daily journal, and reloads the sidebar.
- database-switcher.svelte in the sidebar header and a database management
  section in Settings, both driven by the store and reusing the design-system
  dropdown, dialog, input, and button primitives.
- Delete the orphaned restart_app command.

Implements the desktop half of #1533.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

APPROVE (confirming re-review)

Independently traced the switch/re-subscribe path end-to-end and verified the risky areas.

The switch/re-subscribe path is race-free at the Rust level. set_active_database rebuilds the routed clients under the write lock and releases it before bumping the generation watch; the watcher's select! (both the streaming and backoff arms carry a db_changed.changed() branch, with only synchronous code between them) can't miss a wakeup, and on a switch it drops the in-flight stream_once (holding a clone of the OLD client) and re-clones the NEW client — never retaining a stale client. OLD-database events already in flight carry database_id = A and are dropped by the frontend guard, so no wrong-database event is applied and there is no data bleed.

Also verified:

  • Constant move (DATABASE_ID_HEADER proto→daemon re-export): nodespace_daemon::DATABASE_ID_HEADER still resolves, so the just-merged CLI is unaffected; daemon reads the same key; no divergent definition.
  • Routed vs unrouted split is correct (node/import/embeddings/agent_session routed; settings/local_agent/database_service not). for_id degrades an unparseable id to no-routing.
  • Plumbing: watcher::run signature change propagated to lib.rs + both optimistic_echo_race_test.rs call sites; restart_app removal has zero remaining callers; graceful_shutdown retained.
  • Standards: runes correct, createLogger (no console.*), no any, design-system primitives with aria; database-settings.svelte rewrite leaves no dead imports.

Four non-blocking review findings addressed in this commit:

  • Added a monotonic switchSeq guard to switchTo so a rapid B→C switch can't leave activeDatabaseId and the routed client transiently pointed at different databases (+ a concurrent-switch regression test — store tests now 14).
  • DatabaseIdInterceptor::for_id now logs when an id can't be parsed instead of silently serving the default database.
  • Corrected the stale test-support docstrings that claimed the watcher re-resolves NODESPACED_SOCKET (it rides the shared channel now).
  • Documented the in-flight-read orphan window (a pre-switch read resolving after clearAll) as follow-on hardening (needs per-request database tagging to fully close).

Validation: cargo fmt --check + workspace cargo clippy --all-targets -- -D warnings clean; svelte-check 0 errors/0 warnings; bun run test 3966 passed. cargo test -p nodespace-app (Tauri-seam integration tests) passes — note it flakes under parallel daemon-spawns on a loaded machine (daemon never became healthy timeout), reliably green run serially; unrelated to this change.

Community build unchanged: a fresh install has one default database; with no switch the routed clients carry an empty interceptor and behavior is identical to before.

@mstomar125
mstomar125 merged commit ba8ec9c into NodeSpaceAI:main Jul 9, 2026
2 checks passed
@mstomar125
mstomar125 deleted the ns/adr053-desktop-db-switcher branch July 9, 2026 16:45
@mstomar125

Copy link
Copy Markdown
Contributor Author

APPROVE (post-merge — opened and merged between watcher polls; reviewing for the record). Well-designed and defensively coded; the two things most likely to break here are both handled correctly.

The event-filtering guard is correct AND community-safe

The risk with isActiveDatabaseEvent was dropping legitimate events on the community build (where, per #1590/#1593, the default DB is opened through the manager so its WatchNodes events carry the default's non-empty id — the "empty id = always apply" clause alone wouldn't cover it). Verified it's guarded on both ends:

  • database.svelte.ts:230 — if (!databaseId) return true (Pro single-db) and if (activeDatabaseId === null) return true (pre-load: never drop before the store initializes), then databaseId === activeDatabaseId.
  • load() initializes activeDatabaseId = defaultDatabaseId ?? databases[0]?.id ?? null on first load, so community's default-id events match the active default id → applied. No switch → no drops → behaves exactly as before. ✅
  • After a switch to B, the watcher re-opens WatchNodes with header B (server-routed), and the client guard additionally drops any stale in-flight A-events (id ≠ B) — correct defense-in-depth against the stream-swap race. ✅

The switch flow orders writes safely

switchTo (database.svelte.ts:104): flush pending saves first (sharedNodeStore.flushAllPendingSaves()) so debounced edits land in the old database before the clients re-point — then set_active_database → clear caches → reset workspace → reopen the daily journal. Concurrent switches are handled by a monotonic switchSeq token checked after each await (a superseded switch bails). Correct ordering; pending edits can't leak into the target DB. ✅

Honest­ly-flagged residual race (documented + deferred — acceptable)

The code comments a known narrow race: a read (e.g. loadChildren) dispatched against the previous DB before the switch, resolving after clearAll(), can setNode orphan rows into the now-active store (unreferenced by the new tree, but may surface via global search until the next reload). Closing it fully needs per-request database tagging — explicitly tracked as follow-on hardening. That's the right call (flag-not-hide); the window is small and the orphans are non-corrupting.

Other checks

  • Shared wire constant done right: DATABASE_ID_HEADER moved to packages/proto/src/lib.rs, re-exported from db_routing.rs so nodespace_daemon::DATABASE_ID_HEADER still resolves — CLI (CLI: client-side multi-database selection (ADR-053) #1597) unaffected, one canonical key across daemon/CLI/desktop.
  • set_active_database rebuilds only the routed clients over the same channel (no reconnect) + bumps a generation watch the watcher select!s on → immediate stream re-open on switch. for_id degrades an unparseable id to no-routing (safe fallback to default rather than poisoning requests).
  • Removing the active DB is handled (remove sets activeDatabaseId = null then switches to a fallback).
  • CI green (test:all + test:e2e); bun test 3965/151 (+13 new database.test.ts, zero regressions); svelte-check 0/0; clippy/fmt clean.

Follow-up (matches the impl's own note)

No live GUI run was possible headless — the flush/clear/reset/reload + watcher re-subscribe path is unit- and type-checked but not click-tested on a two-database build. Recommend a manual click-test on a build with 2 registered databases (switch back-and-forth, confirm no cross-DB node bleed in the tree or search, confirm pending edits land in the right DB) before relying on it in a demo. Non-blocking.

Net: correct, community-safe desktop slice of #1533. Approve.

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.

CLI and desktop app: multiple databases with a live, restart-free switcher

1 participant