Skip to content

fix: subscribe to Tauri events through one helper that unlistens safely - #268

Merged
fylorn merged 1 commit into
devfrom
fix/tauri-unlisten
Oct 3, 2026
Merged

fylorn merged 1 commit into
devfrom
fix/tauri-unlisten

Conversation

@fylorn

@fylorn fylorn commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

What was wrong

Switching pages left a trail of unhandled promise rejections: undefined is not an object (evaluating 'listeners[eventId].handlerId'). In the real app (dev build against an isolated core), runs of 60 page switches (Settings → Dashboard → Traffic → Security → MCP → Upstreams, repeated) produced 11, 64 and 43 of them.

Root cause (Tauri 2.11 source)

  • The plugin:event|listen command posts the script that installs the listener in the page (listeners[event][id] = { handlerId }) to the main thread through the event-loop proxy and returns the id at once; the IPC answer goes back from the async runtime directly. The answer can reach the page first: in the real app the entry was still missing when listen() resolved for a few dozen of every ~1000 subscriptions, and it appeared milliseconds later.
  • _unlisten first calls unregisterListener, which reads listeners[eventId].handlerId and throws when the entry is not there yet, and only then invokes plugin:event|unlisten. So the throw
    1. becomes an unhandled rejection: the unlisten function is async and the call sites did void un.then((f) => f());
    2. skips telling Rust: the listener stays registered, gets installed when the script arrives, and the unmounted component keeps receiving events (43 such leftovers in one run).
  • A cleanup that runs before listen() resolves (React StrictMode's double effects, a component that unmounts right away) unlistens at exactly the moment listen() resolves, i.e. inside that gap. (A double unlisten does not throw in 2.11, it was only wasteful.)

Fix

src/lib/tauriEvent.ts:

  • subscribe(event, handler, options?) returns a synchronous, idempotent unsubscribe that is safe to call before registration resolves (it then unlistens as soon as it does), plus .ready for the "subscribe, then read the current state" call sites.
  • The handler stops the moment unsubscribe is called, without waiting for Tauri.
  • A failed unlisten is caught and retried once 250 ms later, by when the listener is installed; a second failure is dropped (a debug log in dev only). Retrying cannot remove anything else: the failure above happens before anything is touched, and a repeated unlisten only removes the same id again.
  • useTauriEvent(event, handler): the latest handler via a ref, resubscribing only when the event name changes. It replaces useAppEvent in the settings sections.

All 27 listen() calls (14 files) go through it: listen → subscribe, void un.then((f) => f()) → un(), await un → await un.ready. Events, handlers and effect dependencies are unchanged.

source.test.ts now fails if a non-test file outside the helper takes a value from @tauri-apps/api/event or calls .listen( / .once( / a window onXxx( event helper. CI's frontend job runs typecheck and build but not vitest, so this is enforced by pnpm test (the pre-PR checklist in CONTRIBUTING).

Rust side

No change. Every emitter is AppHandle::emit, which only evaluates into live webviews, and there are no Rust-side listeners. (Tauri never drops a closed webview's JS listener ids, so a reopened main window is sent stale ids that the page skips silently: framework behavior, not an error.)

Verification

  • Real app, same 60-switch run (screen locked, webview kept awake with gateway traffic): unhandled rejections 11 / 64 / 43 before, 0 / 0 / 0 / 0 after. In the instrumented runs after the fix, Tauri's internal unlisten still threw 4, 19 and 38 times; every one was caught and its retry succeeded (none left registered, at most two attempts per listener). Tauri's own Couldn't find callback id warnings under load appear before and after this change and are not addressed here.
  • pnpm typecheck, pnpm test (69 files, 625 tests), pnpm build; cargo fmt --check, cargo clippy --all-targets -- -D warnings, cargo test.
  • New tests cover cleanup before registration, double cleanup, a StrictMode double mount, an unlisten that rejects, throws synchronously or fails twice, .ready, and running outside Tauri.

🤖 Generated with Claude Code

Switching pages left a trail of unhandled rejections ("undefined is not an
object (evaluating 'listeners[eventId].handlerId')"), 11 and 64 in two runs
of 60 page switches in the real app.

`listen()` resolves as soon as Rust has registered the listener, but the
script that installs it in the page is queued on the main thread while the
IPC answer goes straight back from the async runtime, so the answer can win.
Unlistening in that gap (cleanup that ran before `listen()` resolved: React
StrictMode, a page that unmounts right away) makes Tauri's `_unlisten` read
a listener that is not there yet. It throws before telling Rust, so besides
the unhandled rejection the listener stays registered and the unmounted
component keeps getting events.

`subscribe()` / `useTauriEvent()` in `src/lib/tauriEvent.ts` replace every
`listen()` call (27 call sites in 14 files, and `useAppEvent`):

- the unsubscribe is synchronous, idempotent and safe before registration
  resolves (it then unlistens as soon as it does);
- the handler stops the moment it is called, without waiting for Tauri;
- a failed unlisten is caught and retried once a moment later, by when the
  listener is installed; `.ready` replaces awaiting the listen promise.

`source.test.ts` now fails on a direct `listen`/`once` or window event
helper outside the helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fylorn
fylorn merged commit f6c2682 into dev Oct 3, 2026
4 checks passed
@fylorn
fylorn deleted the fix/tauri-unlisten branch October 3, 2026 00:18
fylorn added a commit that referenced this pull request Oct 3, 2026
Brings in the Tauri event helper (#268): every subscription goes through subscribe() / useTauriEvent() in src/lib/tauriEvent.ts, which unlistens exactly once, also when the cleanup runs before listen() resolves, and catches Tauri's throw instead of leaving an unhandled rejection. No conflicts. The Plugins page, the conversation view and the guard UI added no direct listen() calls: they subscribe through useResource's events, i.e. useCoreEvent, which now uses the helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fylorn added a commit that referenced this pull request Oct 3, 2026
The Frontend job ran typecheck and build but not vitest, so the 600+
unit tests, including the rule that every Tauri event subscription goes
through src/lib/tauriEvent.ts (#268), only ran on developers' machines.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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