The "append-as-you-go" UI pattern is the standard for streaming token display. Here's how to build a robust token renderer that handles partial responses, cancellation, and errors.
Core Pattern
In web applications, you'd replace sys.stdout.write with DOM manipulation — appending text to an element. For React, update state incrementally. The key is flushing output immediately rather than buffering.
The renderer is the contract between SSE and your UI
A bad renderer concatenates every token into a state variable and triggers a UI re-render on every chunk — at 50 tokens/sec, that's 50 re-renders per second, and React's reconciliation chokes. A good renderer batches into a frame budget (16ms) and only re-renders on a requestAnimationFrame tick.
Cancellation is the second contract. The user clicks 'Stop'. The renderer must (1) close the SSE stream so the server stops generating, (2) flush whatever's already been accumulated to the UI, (3) preserve partial output (don't blank it). cwkPippa's UI does exactly this — abort signal wired through to the SSE consumer, partial text preserved in JSONL even on abort.