tauri icon indicating copy to clipboard operation
tauri copied to clipboard

[feat] Rust-side hook for invoke responses and IPC transport errors

Open fwhskr opened this issue 1 month ago • 1 comments

Describe the problem

Applications sometimes need a Rust-side extension point for consistent response normalization and test instrumentation across ordinary invoke replies and IPC transport errors. Wrapping command handlers only covers application-owned command execution, while Builder::channel_interceptor applies to channel messages rather than ordinary invoke responses.

A supported response extension point would avoid replacing the transport just to implement these cross-cutting behaviours.

Describe the solution you'd like

An opt-in Rust-side response hook, scoped to the requesting webview, that can inspect and optionally replace a response before delivery. Ideally it would cover:

  • Synchronous and asynchronous invoke successes and errors, including framework-generated replies.
  • Both custom-protocol and postMessage transports.
  • Transport failures that cannot be dispatched as an invoke, with typed metadata distinguishing them from command responses.

With no hook installed, existing behaviour should remain unchanged. The API should preserve ACL and isolation checks, avoid a shared response queue, and document ordering relative to channel interception and serialization. Exact API shape and whether transport failures need a separate hook are open to maintainer guidance.

Alternatives considered

  • Wrapping application handlers: useful for application-owned results but not a common response boundary.
  • Builder::channel_interceptor: useful precedent, but channel-specific.
  • Builder::invoke_system and a custom protocol: a substantially larger maintenance commitment for response normalization or instrumentation alone.
  • Frontend instrumentation: observes frontend delivery rather than providing a Rust-side response transformation point.

Additional context

This is a feature suggestion for discussion before any PR, per the contribution guide. Would such an extension point be welcome, and what scope/API would maintainers prefer?

Related: #11362 (channel interceptor), #16061 (custom fetch implementation), and #11571 / #4899 (adjacent web-request middleware discussions).

fwhskr avatar Oct 26 '26 14:10 fwhskr

I looked at how the current dev branch (5edd31c) routes invoke responses, and I'd like to propose a concrete shape for this so maintainers have something to react to. Happy to open a PR if the direction is acceptable.

Where responses actually flow today

  • Webview::on_message (crates/tauri/src/webview/mod.rs) is the single entry point for both transports. It wraps the transport-specific OwnedInvokeResponder and hands it to InvokeResolver.
  • InvokeResolver::return_result (crates/tauri/src/ipc/mod.rs) is the only place the responder is called. Sync/async handler results, ACL rejections, and "Command not found" all go through it.
  • The custom-protocol responder (ipc::protocol::get) and the postMessage responder (handle_ipc_message) only differ in delivery. On the postMessage path, large JSON/raw responses are delivered via Channel::from_callback_fn, which is why channel_interceptor already sees some invoke responses today, but not all of them.
  • There are three places where a request never reaches on_message's responder: request parsing failure on the custom protocol (HTTP 500), deserialization failure on postMessage (console.error eval), and invoke-key mismatch inside on_message (log only, no reply).

Proposal

1. Builder::invoke_response_interceptor (mirrors channel_interceptor)

pub enum IpcTransport { CustomProtocol, PostMessage }

pub struct InvokeResponseContext<'a> {
  pub cmd: &'a str,
  pub callback: CallbackFn,
  pub error: CallbackFn,
  pub transport: IpcTransport,
}

pub type InvokeResponseInterceptor<R> = Box<
  dyn Fn(&Webview<R>, &InvokeResponseContext<'_>, InvokeResponse) -> InvokeResponse
    + Send + Sync + 'static,
>;

impl<R: Runtime> Builder<R> {
  pub fn invoke_response_interceptor<F>(self, f: F) -> Self
  where
    F: Fn(&Webview<R>, &InvokeResponseContext<'_>, InvokeResponse) -> InvokeResponse
      + Send + Sync + 'static;
}
  • Stored on AppManager next to channel_interceptor.
  • Applied in exactly one place: the responder wrapper built in Webview::on_message. That gives coverage of sync and async replies, framework-generated replies (ACL rejection, command not found), both transports, and tauri::test::get_ipc_response, without touching the transport code.
  • Taking InvokeResponse by value and returning it avoids a clone when the hook only observes; replacing is just returning a different value.
  • ACL resolution and isolation decryption happen before the resolver is created, so they are unaffected.
  • Documented ordering: handler result serialized → InvokeResponse built → this interceptor → transport delivery (HTTP response / eval / Channel). Only when the postMessage path picks Channel delivery does channel_interceptor run, and it runs after this hook. I'd add a note to the channel_interceptor docs as well.
  • One detail on the custom-protocol responder: the Tauri-Response header is currently derived from the response at the top of the closure. With a hook that may turn Ok into Err, the header must be computed after the hook runs. That's internal, no API impact.
  • With no interceptor registered the only cost is one Option check per response, so behaviour is unchanged.

2. A separate, observe-only Builder::on_ipc_transport_error

pub enum IpcTransportError<'a> {
  InvalidRequest { transport: IpcTransport, reason: &'a str },
  InvokeKeyMismatch,
}

pub type IpcTransportErrorHandler<R> =
  Box<dyn Fn(&Webview<R>, &IpcTransportError<'_>) + Send + Sync + 'static>;
  • Called at the three sites above. The existing default behaviour (500 response, console.error, log line) stays as-is.
  • I'd keep this observe-only rather than letting it replace the reply. Invoke-key mismatch is an authentication failure, and giving app code a way to synthesize a reply for an unauthenticated request seems like a footgun. If maintainers would rather fold this into the response hook as a typed variant, that's doable, but it would force the response hook to return something for requests that never had a callback id, which is awkward.

Implementation notes

  • AppManager::with_handlers grows by two arguments; the existing call sites in ipc/protocol.rs tests and test/mod.rs need updating in the same PR.
  • Changeset: "tauri": minor:feat.
  • Tests via tauri::test::mock_builder: success, error, ACL rejection and async responses all pass through the hook; a replaced response is what reaches the responder; existing IPC tests pass with no hook registered. Transport errors tested with malformed headers in the style of the existing parse_invoke_request tests.

Open questions for maintainers:

  1. Is a single response hook plus a separate transport-error hook acceptable, or would you prefer one hook with an enum argument?
  2. Should the response hook receive the InvokeRequest headers/body as well, or is cmd + callback ids + transport enough for a first iteration?

TakahiroNago avatar Nov 12 '26 11:11 TakahiroNago