Skip to content

Route backend emits to the matching window instead of "main" - #2184

Merged
mstomar125 merged 2 commits into
mainfrom
issue-2033-window-per-db
Aug 20, 2026
Merged

mstomar125 merged 2 commits into
mainfrom
issue-2033-window-per-db

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Second half of #1536 — the multi-window piece. Closes #2033.

Problem

The app is single-window and every backend emit hardcoded
app.get_webview_window("main"). The node/relationship watch events (which
already carry a database_id per ADR-053) broadcast to every open window
via app.emit(...) regardless of which database they belonged to — with one
daemon serving N databases, a second window on a different database would
see the first window's data.

Change

  • window_routing.rs (new): WindowDatabaseRegistry, a live
    window label -> database id pin map, plus emit_routed, the replacement
    for every previous get_webview_window("main") + .emit(...) call. An
    event carrying a non-empty database_id reaches only the window(s) pinned
    to it; an event with no id (or the daemon's empty-string "not
    database-scoped" convention) reaches the focused window, falling back to a
    deterministic default when nothing is focused. Falls back to an unscoped
    broadcast only when the app has no window at all yet — load-bearing for
    the optimistic_echo_race_test.rs/cross_window_hierarchy_sync_test.rs
    integration tests, which drive the watcher against a bare AppHandle with
    no window, and a real edge case at process startup before the first window
    exists.
  • Replaced every get_webview_window("main") site in lib.rs and
    commands/settings.rs, plus watcher.rs's node:*/relationship:*
    broadcasts, with emit_routed.
  • handle_relaunch and the tray:select-database emit previously called
    window.emit(...) believing that scoped the event to that window —
    confirmed against the tauri 2.11 source that Emitter::emit's default
    body always calls the manager's unscoped broadcast regardless of which
    object it's called on. With more than one window that would broadcast a
    database switch to every window instead of just the one being raised. Fixed
    via Emitter::emit_to(label, ...). This bug was caught by the very first
    test written against emit_routed (see the module doc comment).
  • A window's Tauri label is its database id wherever that's known at creation
    time. The one exception is the bootstrap window: its database isn't
    resolved until the frontend's async databaseStore.load() runs (remembered
    selection in localStorage, or the registry default over gRPC), so it
    can't be labeled at Rust-side window-creation time. It keeps the static
    "main" label but is tracked in WindowDatabaseRegistry exactly like any
    other window via the new pin_window_database command — the frontend calls
    it from databaseStore's load()/switchTo().
  • window_state.rs (new): per-database window size/position
    persistence — JSON file, atomic write (temp + rename), mirroring
    preferences.rs. Restored via pin_window_database the first time a
    window pins to a database whose saved geometry differs from what it's
    currently pinned to.

Scope decision: event routing, not per-window command routing

The daemon (confirmed against its source) already supports genuine
concurrent multi-database live streaming — it keeps every opened database's
DatabaseServices (and its own event broadcast channel) alive independently,
so a client can open N WatchNodes streams, one per database, and get true
concurrent live updates. This PR does not wire up N concurrent
watcher::run tasks in production, or make GrpcClient (currently one
Tauri-global instance with a single "active database") per-window for
outbound commands. Both are real, larger changes; the issue's acceptance
criteria are specifically about event routing/cross-talk, and there is no
way to open a second window in the shipped app yet regardless (the app
remains genuinely single-window at runtime today — tauri-plugin-single-instance,
just added in #2180, dedupes any second launch into an in-place switch of the
existing window). This PR is the client-side routing foundation the issue
asks for; wiring N independently-bound watchers (or per-window command
routing) for when a real "open a second window" UX lands is a follow-up.

Tests

  • window_routing.rs: the routing decision (resolve_targets) is a pure
    function with no Tauri types, exhaustively unit-tested — database-id match/
    no-match/multiple-match/stale-registry-entry, focused-window fallback,
    deterministic no-focus fallback, empty-database-id-treated-as-none. Plus
    tauri::test::mock_app()-based tests (mirroring shutdown_tests.rs/
    relaunch_tests already in lib.rs) proving emit_routed actually
    scopes via the real Tauri event/window APIs — the first version of this
    function called .emit() on the resolved WebviewWindow directly, which
    this exact test caught as still broadcasting to every window.
  • window_state.rs: save/load round-trip, per-database isolation, corrupt-file
    and missing-file fallback, atomic write leaves no temp file, against a temp
    directory (never a real or mock app's actual config directory).
  • tests/window_routing_no_cross_talk_test.rs (new, real daemon): spawns
    a real headless nodespaced, registers two real databases, connects three
    independent GrpcClients (mirroring optimistic_echo_race_test.rs's "two
    windows = two independent clients" pattern), drives two real watcher::run
    tasks concurrently — one per database — and asserts a mock window pinned to
    database A receives its node:created event while a mock window pinned to
    database B never does. This is the actual production watcher::run +
    window_routing::emit_routed path against a real daemon, not a mock of the
    routing logic.
  • Full bun run test:all green (frontend + skill + every Rust workspace
    crate rust:test covers — it excludes nodespace-app/
    nodespace-app-test-support, same as prior PRs in this area — that
    exclusion is why the crate needs the separate run below).
  • Separately, cargo test -p nodespace-app -- --test-threads=1: every test
    green except ai_chat_send_to_idle_test.rs, including the two pre-existing
    real-daemon tests this PR's watcher.rs change directly touches
    (optimistic_echo_race_test.rs, cross_window_hierarchy_sync_test.rs —
    both went from broadcast to routed emit_routed underneath them and still
    pass) and the new window_routing_no_cross_talk_test.rs.
    ai_chat_send_to_idle_test.rs (real local LLM inference, unrelated to this
    PR — no diff touches commands/local_agent.rs, commands/agent_session.rs,
    or the agent/nlp-engine crates) timed out at its 300s bound with 0
    tokens generated, twice — once under heavy machine load (concurrent builds
    from another session) and once rerun alone. That exact symptom is called
    out in the test's own doc comment as a known failure mode it has hit before
    with a different model "independent of machine load"; treating this as
    pre-existing environment flakiness, not a regression, given nothing in this
    diff is reachable from that code path. bun run test:all — the mandated
    gate — never runs this crate at all.
  • bun run quality:fix clean (eslint, svelte-check, tsc, cargo fmt --all,
    cargo clippy --all-targets -D warnings -D clippy::unused-async). Checked
    the diff for packages/agent drift (a prior PR in this area hit that) —
    none; this PR never touches that package.

Not independently verified here (no GUI console)

Actual multi-window rendering — two real OS windows on screen, resized/
dragged, showing different databases — needs a real desktop session; there is
no way to open a second window from the shipped UI yet regardless (see scope
decision above), so this was never reachable to click through even with a
GUI. What's covered instead: the routing decision in isolation (pure-function
unit tests), the real Tauri event/window APIs wired correctly (mock_app()
tests), and the real production watcher + routing path against a real daemon
with two real databases (the new integration test) — the parts of "two
windows, two databases, no cross-talk" that don't require an actual on-screen
window.

Co-Authored-By: Claude Sonnet 5 [email protected]

Every backend emit hardcoded app.get_webview_window("main"), and the
node/relationship watch events broadcast to every open window regardless
of which database they belonged to — with one daemon serving N databases
(ADR-053), a second window on a different database would see the first
window's data.

Adds window_routing::WindowDatabaseRegistry (a label -> database id pin
map) and emit_routed, which routes an event carrying a database_id to
only the window(s) pinned to it, and falls back to the focused window
(or a deterministic default) for events with no id. Replaces every
get_webview_window("main") site in lib.rs and commands/settings.rs, and
watcher.rs's node:*/relationship:* broadcasts, with emit_routed. Falls
back to an unscoped broadcast only when no window exists in the app at
all, matching prior behavior for that edge case (load-bearing for the
optimistic-echo-race and cross-window-hierarchy-sync integration tests,
which drive the watcher against a bare AppHandle with no window).

A window's Tauri label is its database id wherever that's known at
creation time; the bootstrap window (database resolved asynchronously by
the frontend) keeps its static "main" label but is tracked in the
registry via the new pin_window_database command, which the frontend
calls from databaseStore's load()/switchTo(). Also fixes handle_relaunch
and the tray:select-database emit, which previously called window.emit()
believing it was scoped to that window — Emitter::emit is never scoped
to the object it's called on, so with more than one window that would
have broadcast a database switch to every window.

window_state.rs persists window size/position per database id (JSON,
atomic write, mirroring preferences.rs), restored via pin_window_database
the first time a window pins to a database whose geometry changed.

Adds a real end-to-end integration test (window_routing_no_cross_talk_test.rs)
that drives two independent watcher::run tasks against two real databases
in a spawned daemon and asserts a window pinned to database A never
receives database B's events, plus unit tests for the routing decision
in isolation and the geometry persistence round-trip.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
- emit_routed now falls back to broadcast when no window has pinned to a
  database yet, not just when the app has zero windows: watcher::spawn
  starts forwarding real events as soon as the daemon reports healthy,
  independent of the frontend's async pin_window_database call landing.
  An event arriving in that gap (bootstrap window open, nothing pinned)
  was being silently dropped instead of reaching the one window that
  exists.
- window_state's save_geometry_at now serializes concurrent saves behind
  a mutex: rapid Resized/Moved deliveries during a drag (or two windows
  resizing at once) each ran their own read-modify-write cycle against
  window_state.json and wrote through the same temp path, which could
  lose an update or interleave writes.
- pin_window_database now validates saved geometry (WindowGeometry::
  is_plausible) before applying it to a real window, rejecting a
  degenerate size like 0x0 rather than leaving the window unusable.
- Removed every "issue #2033" reference from code/doc comments per
  CLAUDE.md's rule against embedding GitHub issue numbers in code.
- Extracted atomic_file::write_json, the shared write-to-temp-then-rename
  mechanics preferences.rs and window_state.rs each had their own copy
  of.
- watcher.rs's forward() now computes the routing target once instead of
  repeating the same non_empty(&database_id).map(str::to_string) in each
  match arm.
- window_routing's emit_routed/resolve_focus_window now gather the open
  window map and pin snapshot once per call instead of twice.

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

Window per database: route backend emits to the matching window instead of "main"

1 participant