Skip to content

perf(mecatui): render the streaming answer's markdown incrementally - #2642

Merged
peppescg merged 5 commits into
mainfrom
perf/2410-incremental-stream-markdown
Nov 2, 2026
Merged

peppescg merged 5 commits into
mainfrom
perf/2410-incremental-stream-markdown

Conversation

@peppescg

@peppescg peppescg commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

While an answer streamed, mecatui re-rendered the whole growing assistant block on every flushed frame: glamour over the full markdown, then lipgloss over the full body to draw the left rail. Each frame cost more than the last.

  • Incremental markdown (stream_markdown.go). The live block is parsed with the same goldmark setup glamour uses and split at its top-level blocks. Finished blocks render once and are cached; each frame re-renders only the open tail and appends it. The cached prefix is kept only while the source before the split is unchanged and its blocks keep their kinds and source spans, which catches setext underlines, lazy continuation, definition lists and growing lists. Headings, code blocks, HTML blocks and thematic breaks end their output mid-line, so a split is never tried right after one; each run of blocks renders once, when it settles, so a frame renders at most the tail plus one run. Answers with link reference definitions always render in full. A block's first render is a plain full render, so resizes and rebuilds don't pay for splitting, and a conversation rebuild forgets the streaming state.
  • Incremental rail (assistant_rail.go). lipgloss renders the rail's multi-line body as each line rendered alone, padded to the widest line. The rail now renders only lines that changed since the previous frame and pads them itself.

Both produce exactly the bytes of the full render; no goldens change.

Issue relationship

Closes #2410

Type of change

  • Other (describe): performance (CPU, allocations)

Before | After

Real binary: one streamed answer through mecated + mecatui connect

A loopback fake of the OpenAI Responses API streams a ~7.4 KB markdown answer (headings, nested lists, Go fence, table, quote, emoji) in 32-byte deltas every 30 ms to mecated serve --openai --openai-base-url …; a real mecatui connect renders it in tmux at 120×40. CPU is mecatui's own process time for the turn (ps -o cputime). Three alternating runs per binary; the scripts are at the end.

Stream wall time mecatui CPU, before mecatui CPU, after
7.4 KB answer ~9.5 s 4.64 / 4.71 / 4.68 s (~49% busy) 2.02 / 2.01 / 2.05 s (~21% busy)
40 heading + code sections, no prose ~2.9 s 0.67 / 0.70 / 0.69 s 0.57 / 0.60 / 0.57 s

The final screens of the before and after runs are identical apart from the port in the header, for both answers.

The whole process uses 2.3× less CPU; the render path itself is ~6× cheaper (below). What remains per frame is outside markdown and the rail: the viewport's line-width scan in SetContentLines, provenance rows (ansi.Strip per row), whole-source normalizeEmojiWidth, and terminal diffing. Those are follow-ups.

Benchmarks (new, stream_markdown_bench_test.go), benchstat, -count 10, Apple M3 Pro

Each op streams one whole answer in 32-byte deltas through the real Model (appendAssistant + refreshView per delta).

                             │   before    │                after                │
                             │   sec/op    │   sec/op     vs base                │
StreamMarkdownAnswer-12        3364.0m ± 3%   580.1m ± 1%  -82.76% (p=0.000 n=10)
StreamMarkdownHeadingRuns-12    267.5m ± 1%   209.5m ± 1%  -21.67% (p=0.000 n=10)

                             │    B/op     │     B/op      vs base               │
StreamMarkdownAnswer-12        2476.6Mi ± 0%   401.3Mi ± 0%  -83.80% (p=0.000 n=10)
StreamMarkdownHeadingRuns-12    235.9Mi ± 0%   108.3Mi ± 0%  -54.10% (p=0.000 n=10)

                             │  allocs/op  │  allocs/op   vs base                │
StreamMarkdownAnswer-12        120.703M ± 0%   9.064M ± 0%  -92.49% (p=0.000 n=10)
StreamMarkdownHeadingRuns-12     3.521M ± 0%   3.501M ± 0%   -0.58% (p=0.000 n=10)

StreamMarkdownHeadingRuns is the shape where nothing can settle (every block ends mid-line); it guards against the settle loop going quadratic, which an earlier revision of this branch did (~40× slower per frame on 40 sections) before review caught it.

Test plan

Baseline checks

  • Linting (task lint): 0 issues in the root module and every other module except environment/microvm, where gosec flags launch_ownership_darwin.go:754 (darwin-only, untouched, also reported on origin/main)
  • Fast offline test suite (task test): not run separately; the race suite below is a superset
  • Pre-review race suite (task test:race): cmd/mecatui/ui passes. 28 tests fail locally in untouched packages (cmd/mecated, cmd/mecatui, internal/app, internal/adapter/{forker,server}, internal/executionexecutor, environment/microvm/gitexec, deploy/mecatl-execution-kind); every one of them fails the same way on a clean origin/main checkout. After the review fixes, task lint and go test -race ./cmd/mecatui/... were re-run on the final commits: same lint result, and every cmd/mecatui package passes except the same two root-package tests that fail on origin/main (TestConnectUsesSavedServerCAForLazyTLSRPC, TestStartupCompatibilityEmbeddedRejected)
  • Offline demo (go run ./cmd/mecademo): tool call, permission ask and approval, result

Byte identity:

  • TestStreamMarkdownMatchesFullRender: 18 fixtures at widths 24 and 100, each streamed three ways (one rune per frame, one line per frame, and uneven deltas of 1–97 bytes that add several lines at once, as coalesced frames do); every frame equals a fresh glamour render. Fixtures: tight, loose, nested and ordered lists; open and closed ``` and ~~~ fences; fences and a table inside list items; a fence inside a quote; tables; blockquotes with lazy continuation; ATX and setext headings; heading runs; heading + fence runs; thematic breaks; HTML; tabs; indented code; definition lists; link references; task lists; emoji (VS16, ZWJ, flag, keycap); CJK; CRLF.
  • TestAssistantRailMatchesLipgloss: the rail equals lipgloss over the whole body for edge cases (empty, CRLF, lone CR, tabs, wide runes) and every streamed frame of the corpus, with collapsed and expanded reasoning above it.
  • Through the real Model: TestStreamMarkdownWidthChangeMidStream (resize 120→70 halfway through an answer) and TestStreamMarkdownForgottenOnRebuild (resetSession, then an answer of the same shape at the same index) both equal a fresh render.

Mutation testing: each guard was broken on purpose and the named test fails.

Guard broken Failing test
Source-before-split check removed TestStreamMarkdownResetsOnRevision (same-length rewrite of a settled heading)
Block-span comparison removed TestStreamMarkdownCoalescedRewriteOfSettledBlock
State kept across a width change TestStreamMarkdownWidthChangeMidStream
Prefix never reused TestStreamMarkdownSettlesFinishedBlocks (a tail-only delta must render exactly one block)
Old settle loop (retry the whole pending run) TestStreamMarkdownHeadingRunsStayLinear
No reset on rebuild TestStreamMarkdownForgottenOnRebuild
Rail keeps CRLF TestAssistantRailMatchesLipgloss
Rail re-renders every line TestAssistantRailReusesUnchangedLines (growing the last line must render exactly one line)
goldmark/ANSI renderer rebuilt on every call TestStreamMarkdownReusesRendererSetup (same instance across deltas, a block change and a rebuild)
Renderer kept across a width change TestStreamMarkdownReusesRendererSetup

Changes

File Change
cmd/mecatui/ui/stream_markdown.go Incremental markdown for conversation assistant blocks
cmd/mecatui/ui/assistant_rail.go Per-line rail with line reuse
cmd/mecatui/ui/render.go Hooks in markdownAt and renderAssistantSnapshotFresh; glamourWrapWidth and assistantRailStyle extracted; comments corrected
cmd/mecatui/ui/block_cache.go resetBlockCaches forgets the stream and rail state
cmd/mecatui/ui/stream_markdown_test.go, assistant_rail_test.go, stream_markdown_bench_test.go Byte-identity, cost and lifecycle tests; benchmarks
cmd/mecatui/ui/transcript_theme_test.go The conversation path primes the stream renderer instead of the glamour cache
go.mod goldmark moves from indirect to direct (same version)

User-facing change

Lower CPU while an answer streams, especially for long answers. No visual change.

Special notes for reviewers

  • Reviewed with a panel (spec, standards, test adequacy, architecture, reuse, duplication, perf, security) before opening. It found the quadratic settle loop (fixed in the third commit, now guarded by a test and a benchmark), the missing reset on rebuild, four guards no test could fail, and stale comments; all addressed.
  • stream_markdown.go mirrors glamour.NewTermRenderer's goldmark setup (GFM, DefinitionList, auto heading IDs, ANSI renderer at priority 1000) because glamour exposes no AST or partial-render API. A glamour upgrade must re-check it; TestStreamMarkdownMatchesFullRender catches drift for syntax in its corpus.
  • Pre-existing nondeterminism: chroma's terminal256 formatter breaks nearest-colour ties by map order, so two full renders of the same code block can pick different 256-colour indexes (the aztec string colour flips between 72 and 78). The markdown tests mask 38;5;N codes for that reason; everything else is compared byte for byte.
  • Not split: the inside of a single top-level block. One long code fence or list still re-renders in full each frame (no regression, little gain).
  • After perf(mecatui): release settled answers' markdown from the render cache #2641 landed, origin/main was merged into this branch; the only conflict was the markdownAt doc comment, now describing both the single markdown entry and markdownStreamed.
Reproduction scripts (real binary)

fake_openai.py PORT ANSWER_FILE CHUNK_BYTES DELAY_MS serves the stream; run.sh MECATED MECATUI LABEL ANSWER_FILE OUTDIR appends label,wall_ms,cpu_ms to OUTDIR/results.csv. The answer file is strings.Repeat(streamAnswerSection, 6) from the benchmark plus a final END-OF-STREAMED-ANSWER marker.

import json, sys, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

PORT, ANSWER = int(sys.argv[1]), open(sys.argv[2], encoding="utf-8").read()
CHUNK, DELAY = int(sys.argv[3]), int(sys.argv[4]) / 1000.0

def chunks(text, n):
    data, i = text.encode("utf-8"), 0
    while i < len(data):
        j = min(i + n, len(data))
        while j < len(data) and (data[j] & 0xC0) == 0x80:
            j += 1
        yield data[i:j].decode("utf-8")
        i = j

class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.0"
    def log_message(self, *args): pass
    def do_GET(self):
        body = json.dumps({"data": [{"id": "gpt-5", "object": "model"}]}).encode()
        self.send_response(200); self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
    def do_POST(self):
        self.rfile.read(int(self.headers.get("Content-Length", "0")))
        self.send_response(200); self.send_header("Content-Type", "text/event-stream"); self.end_headers()
        seq = 0
        def event(kind, payload):
            nonlocal seq
            self.wfile.write(f"event: {kind}\ndata: {json.dumps({'type': kind, 'sequence_number': seq, **payload})}\n\n".encode())
            self.wfile.flush(); seq += 1
        for part in chunks(ANSWER, CHUNK):
            event("response.output_text.delta", {"delta": part}); time.sleep(DELAY)
        event("response.completed", {"response": {"status": "completed", "usage": {"input_tokens": 10, "output_tokens": 2000}}})

ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
#!/bin/sh
set -eu
MECATED=$1 MECATUI=$2 LABEL=$3 ANSWER=$4 OUT=$5
HERE=$(cd "$(dirname "$0")" && pwd)
WORK=$(mktemp -d "${TMPDIR:-/tmp}/proof2410.XXXXXX")
mkdir -p "$WORK/home" "$WORK/config" "$WORK/data" "$WORK/state" "$WORK/cache" "$WORK/ws" "$OUT"
export HOME="$WORK/home" XDG_CONFIG_HOME="$WORK/config" XDG_DATA_HOME="$WORK/data" \
	XDG_STATE_HOME="$WORK/state" XDG_CACHE_HOME="$WORK/cache"
LPORT=$((18950 + $$ % 20)); DPORT=$((18980 + $$ % 20)); SESSION="proof2410-$$"
python3 -I "$HERE/fake_openai.py" "$LPORT" "$ANSWER" 32 30 &
FPID=$!
OPENAI_API_KEY=fixture-key "$MECATED" serve --openai --model=gpt-5 \
	--openai-base-url "http://127.0.0.1:$LPORT/v1" --toolhive-llm=false --product-metrics=false \
	--grpc-addr "127.0.0.1:$DPORT" --http-addr "" --metrics-addr "" --workspace "$WORK/ws" \
	>"$WORK/mecated.log" 2>&1 &
DPID=$!
trap 'tmux kill-session -t "$SESSION" 2>/dev/null || true; kill $DPID $FPID 2>/dev/null || true' EXIT
until nc -z 127.0.0.1 "$DPORT" 2>/dev/null; do sleep 0.05; done
tmux new-session -d -s "$SESSION" -x 120 -y 40 \
	"cd '$WORK/ws' && '$MECATUI' connect 127.0.0.1:$DPORT --tls=false 2>'$WORK/mecatui.err'"
sleep 3
UIPID=$(pgrep -n -f "$MECATUI connect 127.0.0.1:$DPORT")
pane() { tmux capture-pane -p -t "$SESSION"; }
cpu() { ps -o cputime= -p "$UIPID" | tr -d ' ' | awk -F'[:.]' '{ if (NF==3) print ($1*60+$2)*1000+$3*10; else print (($1*60+$2)*60+$3)*1000+$4*10 }'; }
ms() { python3 -I -c 'import time; print(int(time.time()*1000))'; }
before=$(cpu); start=$(ms)
tmux send-keys -t "$SESSION" "explain the change" Enter
until pane | grep -q "END-OF-STREAMED-ANSWER"; do sleep 0.05; done
sleep 1
echo "$LABEL,$(($(ms) - start)),$(($(cpu) - before))" >>"$OUT/results.csv"
pane >"$OUT/final-$LABEL.txt"

Benchmarks: go test ./cmd/mecatui/ui/ -run '^$' -bench StreamMarkdown -benchmem -count 10, on this branch and on origin/main with stream_markdown_bench_test.go copied in.

🤖 Generated with Claude Code

peppescg and others added 3 commits November 1, 2026 17:54
While an answer streamed, every flushed delta ran the whole growing
assistant block back through glamour, so each delta cost more than the
last.

Parse the live block with the same goldmark setup glamour uses and split
it at its top-level blocks: finished blocks render once and are cached,
and each frame re-renders only the open tail. The cached prefix is kept
only while the source before the split is unchanged and its blocks keep
their kinds and source spans; answers with link reference definitions,
a different block, a width change, or a non-append revision render in
full. The output is byte-identical to a full render, pinned by a property
test that streams a fixture corpus one rune at a time.

Refs #2410

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With markdown incremental, lipgloss drawing the rail over the whole
assistant body became the largest per-frame cost of a streaming answer.

The rail has no width, background, or right border, so lipgloss renders
a multi-line body as each line rendered alone, padded to the widest line.
Render it that way and keep the previous frame's railed lines, so only
lines that changed are rendered. A property test pins the output to
lipgloss over the whole body.

Refs #2410

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Headings, fenced and indented code, HTML blocks, and thematic breaks end
their glamour output mid-line, so they can never end a settled prefix. The
settle loop re-rendered the whole pending run at every rejected candidate,
which made a run of them cost O(n^2) block renders on every frame: an
answer of 40 heading-plus-code sections took about a second per frame.
Skip split points after those kinds without rendering, render each run
once when it settles, and stop settling for the frame if a run still ends
mid-line, so a frame renders at most the tail plus one run.

The streaming state is keyed by block index, so forget it, and the rail's
reused lines, when a conversation is rebuilt. The rail now owns its style
and turns CRLF into LF the way lipgloss does, so its output equals
lipgloss for any body.

Tests now count rendered blocks per frame, stream the corpus in whole
lines and uneven deltas as coalesced frames do, rewrite a settled block at
the same length, and drive a resize and a rebuild through the real Model.
Comments that still described the old single glamour entry point are
corrected.

Refs #2410

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@peppescg peppescg added the tui mecatui terminal UI (rendering, keybindings, footer, panes, scrollback) label Nov 1, 2026
@peppescg peppescg self-assigned this Nov 1, 2026
@jbeda

jbeda commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Two optional test-adequacy improvements from review. Neither should block merging:

  1. Make the rail-reuse test prove reuse, not just output equality. In TestAssistantRailReusesUnchangedLines (cmd/mecatui/ui/assistant_rail_test.go:55), comparing the saved and current strings would still pass if every line were rendered again. A render counter (or equivalent observation) could assert that growing only the last line renders exactly one line.

  2. Protect renderer-setup reuse with an assertion. The streaming tests check output and block-render counts, but don't directly detect rebuilding the Goldmark/ANSI renderer on every frame (cmd/mecatui/ui/stream_markdown.go:128). An identity or construction-count assertion across same-width deltas and block changes would guard that performance property. Rebuilding when the width changes is acceptable; this is not a request to retain renderers for previously used widths.

These are regression-coverage suggestions, not observed implementation defects.

peppescg and others added 2 commits November 2, 2026 10:05
The rail-reuse test compared a saved railed line with the current one,
which stays equal even if every line is rendered again. Count lines the
rail renders and assert that growing only the last line renders one.

Nothing guarded the goldmark/ANSI renderer being built once per wrap
width. Assert it is the same instance across same-width deltas, a block
change, and a conversation rebuild, and a new one after a width change.

Both assertions were checked to fail when the reuse they guard is
removed.

Refs #2410

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@peppescg

peppescg commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, both were real gaps: the rail test compared strings that stay equal even if every line is re-rendered, and nothing guarded the renderer setup. Added in 28e54e8:

  1. assistantRail counts the lines it renders; TestAssistantRailReusesUnchangedLines now asserts that growing only the last line renders exactly one.
  2. TestStreamMarkdownReusesRendererSetup asserts the goldmark/ANSI renderer is the same instance across same-width deltas, a block change and a conversation rebuild, and a new one after a width change.

Both fail when the reuse they guard is removed (checked by mutation). I also merged main to resolve the markdownAt doc-comment conflict with #2641.

@peppescg
peppescg merged commit 9bfaa27 into main Nov 2, 2026
45 checks passed
@peppescg
peppescg deleted the perf/2410-incremental-stream-markdown branch November 2, 2026 09:50
@toolhive-release-app toolhive-release-app Bot mentioned this pull request Nov 18, 2026
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tui mecatui terminal UI (rendering, keybindings, footer, panes, scrollback)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

mecatui: render the streaming answer's markdown incrementally

2 participants