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().
Basic shape
Section titled “Basic shape”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 };}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();StreamCall<Y, R>
Section titled “StreamCall<Y, R>”type StreamCall<Y, R> = AsyncIterable<Y> & PromiseLike<R> & { cancel(): Promise<void>;};[Symbol.asyncIterator]()— yieldsYchunks..then(…)/await— resolves to the finalRreturn value..cancel()— sends a cancel signal; pendingnext()calls and the final promise reject with aTyndIpcErrorwhosecodeis"CANCELLED".
Marshalling
Section titled “Marshalling”- Each
yieldsends one framed message over the Bun-to-host IPC channel. - The final
returnvalue 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, …);Errorand class instances do not. A value devalue cannot encode ends the stream with aPROTOCOL_ERROR.
Flow control
Section titled “Flow control”Three mechanisms keep streaming safe at arbitrary yield rates:
- 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. - Yield batching — Rust buffers yields and flushes every 10 ms or at 64 items. One
evaluate_scriptper flush per webview. - 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.
Cancellation
Section titled “Cancellation”const stream = api.processFiles(hugeBatch);
setTimeout(() => void stream.cancel(), 3000);Also triggers automatically on:
breakout offor await→ implicititerator.return()→ cancel signal.- Originating window closes, navigates or reloads → the Rust host cancels every stream that window started.
- The
signalortimeoutofapi.withOptions({ signal, timeout })fires.
Inside the generator, getCallContext().signal aborts at the same time, so pending fetch calls and timers can stop early.
Error handling
Section titled “Error handling”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.
Typical patterns
Section titled “Typical patterns”- 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.
Limitations
Section titled “Limitations”- 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.