DEV Community

Cover image for What I got wrong adding a typewriter to a streaming AI chat UI
Stephen Color
Stephen Color

Posted on AI-assisted

What I got wrong adding a typewriter to a streaming AI chat UI

This is a follow-up to my earlier post, Streaming markdown in Flutter without the jitter. That one was about the parser side of StreamKit (flutter_streaming_markdown_kit, my zero-dependency streaming chat UI kit). This one is about the layer above it: the typewriter reveal, the two things I got wrong in 1.0.0, and why handing the reveal to a TTS clock in 1.1.0 changed the controller's design. I won't re-explain the parsing here.

First, why a typewriter exists at all. Providers don't push text at a reading-friendly pace; tokens arrive in uneven bursts. Paint the raw text as it lands and the answer visibly jumps. Reveal at a fixed reading speed and nothing else, and a fast model leaves you permanently behind. The controller has to smooth the stream without drifting far from it.

The 1.0.0 design

TypewriterController extends ChangeNotifier, takes a TickerProvider (vsync), and has two config values: charsPerSecond = 320 and maxBacklogSeconds = 0.9. It keeps a target string — everything pushed so far — and moves a visible cursor _shown toward that target on a vsync Ticker. The widget layer reads visibleText, which is target.substring(0, _shown). Because _shown is an integer index, the parser never sees a partial token; the visible string is always a prefix of the target.

The 1.0.0 surface was small: push(chunk), setText(text) (no animation, for history and restored sessions), skipToEnd(), clear(), and the getters target, visibleText, isTyping, isComplete and backlog.

The interesting part is the tick:

void _onTick(Duration elapsed) {
  var delta = (elapsed - _lastElapsed).inMicroseconds /
      Duration.microsecondsPerSecond;
  if (delta <= 0) delta = 1 / 60; // first tick, or a repeated timestamp
  _lastElapsed = elapsed;

  final remaining = _target.length - _shown;
  if (remaining == 0) return;

  final backlogSeconds = remaining / charsPerSecond;
  final rate = backlogSeconds > maxBacklogSeconds
      ? remaining / maxBacklogSeconds // spend the backlog over 0.9 s
      : charsPerSecond;

  var step = (rate * delta).round();
  if (step < 1) step = 1;
  if (step > remaining) step = remaining;

  _shown += step;
  notifyListeners();
}
Enter fullscreen mode Exit fullscreen mode

The backlog line is the one that matters. At a flat 320 characters per second a 600-character burst takes about 1.9 seconds to reveal; with the acceleration it lands in about 0.9, because the rate becomes remaining / maxBacklogSeconds instead of the fixed value. That worked well — until two things showed me what I had actually assumed.

Bug A: the "Streaming" label that outlived the stream

The parser sets MarkdownBlock.incomplete when a code fence has no closing backticks, and on a trailing block it could not finish. That flag is correct: it describes the data. The mistake was in CodeBlockView, which drew its "Streaming" label from incomplete alone.

While bytes are arriving, that is right. But a message can stop mid-code for reasons that have nothing to do with parsing: the user pressed Stop, the provider cut off, or the message was restored from history. In every one of those cases the fence is genuinely unclosed, so incomplete stays true forever — and the code block kept a permanent "Streaming" label over a stream that no longer existed.

1.1.0 gives the widget both facts instead of asking one flag to do two jobs:

// 1.0.0: the label read the parser flag alone.
if (block.incomplete)
  const Text('Streaming'),

// 1.1.0: the widget also receives the transport state.
if (block.incomplete && streaming)
  const Text('Streaming'),
Enter fullscreen mode Exit fullscreen mode

MarkdownBlockView and StreamingMarkdownView now pass the real stream state down to CodeBlockView. The partial code still renders exactly as before — only the label goes once the transport stops.

The lesson: incomplete describes the data (parsing could not finish), while streaming describes the transport (bytes are still arriving). A restored session has the first without the second. One boolean was silently doing both jobs, and the widget had no way to tell them apart.

The bigger miss: the reveal assumed it owned the clock

Bug A was about the stream ending. The deeper gap was about what happens when the stream is not the only clock in the room.

If the app speaks the reply with text-to-speech, or drives a caption track, the backlog acceleration actively fights you. With maxBacklogSeconds = 0.9 the screen is deliberately running ahead of a slow voice: exactly right when the eye is the consumer, exactly wrong when audio is the clock. The whole point of the acceleration is to spend down a backlog, and a voice-driven UI wants that backlog to exist and be revealed in step with the audio.

Nothing in 1.0.0 let an app take the clock over. So 1.1.0 added a small API for handing the reveal to one:

final typer = TypewriterController(
  vsync: this,
  charsPerSecond: 320,
  maxBacklogSeconds: 0.9,
);

// The audio player is the clock: each position update moves the cursor.
void onAudioPosition(Duration position) {
  typer.syncToPosition(
    position,
    charIndexAt: (p) => (p.inMilliseconds * charsPerMs).floor(),
  );
}

// Or, when you already know the character index:
typer.syncTo(1412);

// Or hold the reveal entirely, e.g. while playback is paused:
typer.pause();
typer.resume();
Enter fullscreen mode Exit fullscreen mode

The rules the tests now pin down:

pause() and resume() hold the cursor exactly where it is. Chunks that arrive while paused are buffered in target and revealed on resume; a push while paused does not start the ticker. Calling either twice is harmless.

skipToEnd() while paused shows everything and keeps the paused state, so the next push waits for a resume instead of suddenly animating.

syncTo(int charIndex) jumps the cursor to an exact character index without animating, clamped to 0..target.length so a rounding error at the end of the audio cannot throw. While paused the cursor moves and stays; while running, the remaining backlog animates from the new position at the usual speed.

syncToPosition(Duration position, {required int Function(Duration) charIndexAt}) is the same idea for players that only know an audio position. You supply the mapping, because the kit cannot know how fast your voice speaks. A revealedCharacters getter lets the driving code read back where the reveal is.

One related lifecycle fix shipped alongside: dispose() now stops an active ticker before disposing it, so disposing a controller mid-reveal no longer trips the "Ticker was active" assertion. That one cost me a confusing afternoon and should have been there from the start.

On tests: 1.0.0 had 65, 1.1.0 has 81. The 16 new ones cover the unclosed-fence label at CodeBlockView, StreamingMarkdownView and AssistantMessage level, both while streaming and after the stream stops; pause/resume buffering and repeated calls; skipToEnd while paused; and syncTo/syncToPosition exact jumps, clamping, backwards seeks, and syncing while paused or running. flutter analyze reports no issues.

What I would do differently

Two things.

Separate data state from transport state from the start. incomplete was never wrong; asking it to also mean "the stream is live" was. Any flag that crosses a layer boundary deserves a name that says which layer it belongs to.

And design the controller as if the ticker were one possible clock rather than the only one. pause, resume and syncTo are not TTS features bolted on; they are what the API looks like once you admit the reveal is driven by something the controller does not own. Had I framed it that way in 1.0.0, the voice case would have been a wiring exercise instead of a redesign.

The widgets, the changelog and the README are in the public showcase repo, github.com/StephenColor/flutter-streaming-markdown-kit. The full source — controller, parser, widgets and the 81 tests — is the commercial kit I sell on Gumroad for $2.90 and on Codester, one-off licence, unlimited apps.

Top comments (0)