Skip to content

Streaming RPC

If a backend export is an async function*, the frontend gets a StreamCall<Y, R> handle: awaitable (resolves to the generator’s return value) and async-iterable (yields each chunk). Cancellation propagates end-to-end via iterator.return().

backend/main.ts
export async function* processFiles(paths: string[]) {
let ok = 0;
for (const [i, path] of paths.entries()) {
await doWork(path);
ok++;
yield { path, progress: (i + 1) / paths.length };
}
return { ok, failed: paths.length - ok };
}
src/main.ts
const stream = api.processFiles(["a.txt", "b.txt"]);
for await (const chunk of stream) {
render(chunk.progress);
}
const summary = await stream; // { ok, failed }
// or early-stop: await stream.cancel();
type StreamCall<Y, R> = AsyncIterable<Y> & PromiseLike<R> & {
cancel(): Promise<void>;
};
  • [Symbol.asyncIterator]() — yields Y chunks.
  • .then(…) / await — resolves to the final R return value.
  • .cancel() — sends a cancel signal; pending next() calls and the final promise reject with a TyndIpcError whose code is "CANCELLED".
  • Each yield sends one framed message over the Bun-to-host IPC channel.
  • The final return value is delivered as a single resolve on the promise side.
  • Values are devalue-encoded, as in regular RPC: the same types survive (Date, Map, Set, BigInt, RegExp, URL, cyclic references, …); Error and class instances do not. A value devalue cannot encode ends the stream with a PROTOCOL_ERROR.

Three mechanisms keep streaming safe at arbitrary yield rates:

  1. Per-stream credit — backend starts with 64 credits; every yield decrements; at 0 the generator awaits. Frontend replenishes with { type: "ack", id, n: 32 } per 32 consumed chunks.
  2. Yield batching — Rust buffers yields and flushes every 10 ms or at 64 items. One evaluate_script per flush per webview.
  3. Cleanup on window close — the Rust host cancels every active stream that originated in a window when it closes, navigates or reloads.

See the Streaming RPC guide for details.

const stream = api.processFiles(hugeBatch);
setTimeout(() => void stream.cancel(), 3000);

Also triggers automatically on:

  • break out of for await → implicit iterator.return() → cancel signal.
  • Originating window closes, navigates or reloads → the Rust host cancels every stream that window started.
  • The signal or timeout of api.withOptions({ signal, timeout }) fires.

Inside the generator, getCallContext().signal aborts at the same time, so pending fetch calls and timers can stop early.

try {
for await (const n of api.flaky()) {
console.log(n);
}
} catch (err) {
console.error(err.message);
}

Thrown errors in the generator propagate into both for await and await stream.

  • Progress + summary — yield progress, return summary.
  • Cancellable long task — bind a cancel button to stream.cancel().
  • LLM tokens — yield decoded fragments from res.body.getReader().

Examples: Streaming RPC guide.

  • No transferable objects; values are encoded and copied on every yield.
  • Generator back-pressure is credit-based — not propagated to the producer’s I/O source (it’s a generator, not a stream).
  • To push to the caller from an ordinary call (progress next to a normal result), pass a Channel<T> instead. A channel has no back-pressure.
  • For multi-MB binary chunks, yield handles/IDs over JSON and fetch the bytes separately via binary IPC.