Repository navigation
perf(mecatui): render the streaming answer's markdown incrementally - #2642
Conversation
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]>
|
Two optional test-adequacy improvements from review. Neither should block merging:
These are regression-coverage suggestions, not observed implementation defects. |
# Conflicts: # cmd/mecatui/ui/render.go
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]>
|
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:
Both fail when the reuse they guard is removed (checked by mutation). I also merged main to resolve the |
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.
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.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
Before | After
Real binary: one streamed answer through
mecated+mecatui connectA 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 realmecatui connectrenders it in tmux at 120×40. CPU ismecatui's own process time for the turn (ps -o cputime). Three alternating runs per binary; the scripts are at the end.mecatuiCPU, beforemecatuiCPU, afterThe 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.Stripper row), whole-sourcenormalizeEmojiWidth, and terminal diffing. Those are follow-ups.Benchmarks (new,
stream_markdown_bench_test.go), benchstat,-count 10, Apple M3 ProEach op streams one whole answer in 32-byte deltas through the real Model (
appendAssistant+refreshViewper delta).StreamMarkdownHeadingRunsis 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
task lint): 0 issues in the root module and every other module exceptenvironment/microvm, where gosec flagslaunch_ownership_darwin.go:754(darwin-only, untouched, also reported onorigin/main)task test): not run separately; the race suite below is a supersettask test:race):cmd/mecatui/uipasses. 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 cleanorigin/maincheckout. After the review fixes,task lintandgo test -race ./cmd/mecatui/...were re-run on the final commits: same lint result, and everycmd/mecatuipackage passes except the same two root-package tests that fail onorigin/main(TestConnectUsesSavedServerCAForLazyTLSRPC,TestStartupCompatibilityEmbeddedRejected)go run ./cmd/mecademo): tool call, permission ask and approval, resultByte 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.TestStreamMarkdownWidthChangeMidStream(resize 120→70 halfway through an answer) andTestStreamMarkdownForgottenOnRebuild(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.
TestStreamMarkdownResetsOnRevision(same-length rewrite of a settled heading)TestStreamMarkdownCoalescedRewriteOfSettledBlockTestStreamMarkdownWidthChangeMidStreamTestStreamMarkdownSettlesFinishedBlocks(a tail-only delta must render exactly one block)TestStreamMarkdownHeadingRunsStayLinearTestStreamMarkdownForgottenOnRebuildTestAssistantRailMatchesLipglossTestAssistantRailReusesUnchangedLines(growing the last line must render exactly one line)TestStreamMarkdownReusesRendererSetup(same instance across deltas, a block change and a rebuild)TestStreamMarkdownReusesRendererSetupChanges
cmd/mecatui/ui/stream_markdown.gocmd/mecatui/ui/assistant_rail.gocmd/mecatui/ui/render.gomarkdownAtandrenderAssistantSnapshotFresh;glamourWrapWidthandassistantRailStyleextracted; comments correctedcmd/mecatui/ui/block_cache.goresetBlockCachesforgets the stream and rail statecmd/mecatui/ui/stream_markdown_test.go,assistant_rail_test.go,stream_markdown_bench_test.gocmd/mecatui/ui/transcript_theme_test.gogo.modUser-facing change
Lower CPU while an answer streams, especially for long answers. No visual change.
Special notes for reviewers
stream_markdown.gomirrorsglamour.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;TestStreamMarkdownMatchesFullRendercatches drift for syntax in its corpus.38;5;Ncodes for that reason; everything else is compared byte for byte.origin/mainwas merged into this branch; the only conflict was themarkdownAtdoc comment, now describing both the single markdown entry andmarkdownStreamed.Reproduction scripts (real binary)
fake_openai.py PORT ANSWER_FILE CHUNK_BYTES DELAY_MSserves the stream;run.sh MECATED MECATUI LABEL ANSWER_FILE OUTDIRappendslabel,wall_ms,cpu_mstoOUTDIR/results.csv. The answer file isstrings.Repeat(streamAnswerSection, 6)from the benchmark plus a finalEND-OF-STREAMED-ANSWERmarker.Benchmarks:
go test ./cmd/mecatui/ui/ -run '^$' -bench StreamMarkdown -benchmem -count 10, on this branch and onorigin/mainwithstream_markdown_bench_test.gocopied in.🤖 Generated with Claude Code