Repository navigation
feat(platform): refactor chat stream buffer and typewriter rendering - #510
Conversation
Rewrite use-stream-buffer with improved chunking, jitter smoothing, and adaptive speed. Replace CSS mask-based character reveal with ref-based DOM slicing in typewriter-text and incremental-markdown. Add tests for the stream buffer hook. Remove unused streaming CSS from globals.
Greptile SummaryRefactored chat streaming from adaptive speed to constant-rate buffering (50 CPS) with improved architecture:
Issue found: Confidence Score: 3/5
|
| Filename | Overview |
|---|---|
| services/platform/app/features/chat/hooks/use-stream-buffer.ts | Refactored from adaptive speed to constant-rate buffering; simplified logic by removing ring buffer and metrics tracking; well-tested with comprehensive unit tests |
| services/platform/app/features/chat/components/typewriter-text.tsx | Updated to use constant-rate config; simplified cursor visibility logic to show throughout streaming phase; clean integration with refactored hook |
| services/platform/app/features/chat/components/incremental-markdown.tsx | Replaced CSS mask approach with ref-based DOM slicing for cursor positioning; refs are mutated during render which violates React rules; removed dual-layer layout stabilization |
| services/platform/app/features/chat/hooks/tests/use-stream-buffer.test.ts | New comprehensive test suite covering streaming scenarios, buffering, rate-matching, and reduced motion; includes proper rAF mocking for animation testing |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
Start[Text chunk arrives] --> Buffer[Add to buffer]
Buffer --> CheckInit{Initial buffer<br/>threshold met?}
CheckInit -->|No| Wait[Wait for more chunks]
Wait --> Start
CheckInit -->|Yes| StartReveal[Start revealing]
StartReveal --> RAF[requestAnimationFrame loop]
RAF --> CheckBuffer{Buffer empty?}
CheckBuffer -->|Yes + streaming| RAF
CheckBuffer -->|Yes + ended| Done[Stop animation]
CheckBuffer -->|No| Reveal[Reveal chars at constant 50 CPS]
Reveal --> WordBound[Snap to word boundary]
WordBound --> UpdateDOM[Update displayLength state<br/>throttled 50ms]
UpdateDOM --> Split[Split at anchor position]
Split --> StableMD[StableMarkdown<br/>memoized]
Split --> StreamMD[StreamingMarkdown<br/>re-parsed with cursor]
StreamMD --> RAF
Last reviewed commit: be507b3
| const revealedLenRef = useRef(revealedContent.length); | ||
| revealedLenRef.current = revealedContent.length; | ||
| const revealedTextRef = useRef(revealedContent); | ||
| revealedTextRef.current = revealedContent; |
There was a problem hiding this comment.
refs are mutated during render (lines 151 and 153), which violates React rules and can cause unpredictable behavior. These assignments happen during the render phase, not in an effect or event handler.
Move these to a useEffect or restructure to avoid mutating refs during render:
| const revealedLenRef = useRef(revealedContent.length); | |
| revealedLenRef.current = revealedContent.length; | |
| const revealedTextRef = useRef(revealedContent); | |
| revealedTextRef.current = revealedContent; | |
| const revealedLenRef = useRef(revealedContent.length); | |
| const revealedTextRef = useRef(revealedContent); | |
| useEffect(() => { | |
| revealedLenRef.current = revealedContent.length; | |
| revealedTextRef.current = revealedContent; | |
| }, [revealedContent]); |
There was a problem hiding this comment.
This is an intentional "latest value ref" pattern and the suggestion would introduce a bug.
The CursorWrapper functions (lines 179-183) are called by react-markdown during the render phase to detect cursor position. They read revealedLenRef.current and revealedTextRef.current synchronously during render. If we move the ref assignments to useEffect (which runs after render), the wrappers would read stale values from the previous render, causing the cursor to appear at the wrong position for one frame on every update.
The current pattern is safe here because:
- The refs hold values derived deterministically from props (
revealedContent), not DOM state - If a concurrent render is discarded, the next render re-sets the refs to the correct values
- Double-rendering in Strict Mode sets the same value twice (idempotent)
The existing comment on line 148-149 explains the intent: these refs exist specifically so the useMemo'd cursor wrappers can read fresh values without being recreated on every ~50ms text update.
If you agree with the changes and no further modifications are needed, please resolve this conversation.
📝 WalkthroughWalkthroughThis pull request refactors the streaming text rendering system in the chat interface from an adaptive buffer model to a constant-rate model. Changes include: removing the Estimated code review effort🎯 3 (Moderate) | ⏱️ ~28 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Tip Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
services/platform/app/features/chat/components/incremental-markdown.tsx (1)
230-237:⚠️ Potential issue | 🟡 MinorMissing
componentsprop comparison in memo equality check.The
StreamingMarkdownmemo equality function comparescontent,revealedLength, andshowCursor, but omitscomponents. If a parent passes different custom markdown components, the memoized component won't re-render, potentially using stale component mappings.🔧 Proposed fix
(prevProps, nextProps) => { // Re-render when revealed length, content, or cursor state changes return ( prevProps.content === nextProps.content && prevProps.revealedLength === nextProps.revealedLength && - prevProps.showCursor === nextProps.showCursor + prevProps.showCursor === nextProps.showCursor && + prevProps.components === nextProps.components ); },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@services/platform/app/features/chat/components/incremental-markdown.tsx` around lines 230 - 237, The memo equality function for StreamingMarkdown only checks content, revealedLength, and showCursor and thus ignores changes to the components prop; update the equality callback (the arrow function used in React.memo for StreamingMarkdown) to also compare prevProps.components and nextProps.components (e.g., include prevProps.components === nextProps.components in the logical AND) so the component re-renders when a different components mapping is passed.services/platform/app/features/chat/components/typewriter-text.tsx (1)
173-181:⚠️ Potential issue | 🟡 MinorMemo should compare
componentsprop for correctness, though current usage is stable.The memo equality function omits the
componentsprop from comparison. While this doesn't cause issues in practice—markdownComponentsis a static module-level constant imported into all callers—the custom equality function should compare all props that affect rendering for defensive coding. Ifcomponentswere to change withouttext,isStreaming, orclassNamechanging, the memoization would incorrectly skip re-renders. Consider addingcomponentsto the comparison:prevProps.components === nextProps.components &&🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@services/platform/app/features/chat/components/typewriter-text.tsx` around lines 173 - 181, The custom memo equality for the TypewriterText wrapper currently only compares text, isStreaming, and className; update the equality function used with memo (the second argument to memo for TypewriterText) to also compare prevProps.components === nextProps.components so that changes to the components prop (passed into TypewriterTextComponent) will trigger re-renders; locate the TypewriterText memo block and add the components comparison alongside the existing text/isStreaming/className checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@services/platform/app/features/chat/hooks/__tests__/use-stream-buffer.test.ts`:
- Around line 168-173: The test currently skips the rate comparison when delta1
or delta2 equals zero; replace the conditional check with explicit assertions so
stalled animations fail the test: in the test using variables delta1 and delta2
assert expect(delta1).toBeGreaterThan(0) and expect(delta2).toBeGreaterThan(0)
first (so zeros cause a test failure), then perform the existing fuzzy rate
comparisons (expect(delta2).toBeGreaterThan(delta1 * 0.2) and
expect(delta2).toBeLessThan(delta1 * 1.8)); update the test containing
delta1/delta2 to remove the if-block and add these explicit expectations.
- Around line 188-194: The assertion uses a hardcoded expected length (43) which
is fragile; change the expect to derive expected value from the test's source
string instead (e.g., replace expect(result.current.displayLength).toBe(43) with
expect(result.current.displayLength).toBe(text.length or the actual test string
variable used in this spec), keeping other assertions about rafCallbacks and
advanceFrames the same so the test tracks the test data instead of a magic
number.
---
Outside diff comments:
In `@services/platform/app/features/chat/components/incremental-markdown.tsx`:
- Around line 230-237: The memo equality function for StreamingMarkdown only
checks content, revealedLength, and showCursor and thus ignores changes to the
components prop; update the equality callback (the arrow function used in
React.memo for StreamingMarkdown) to also compare prevProps.components and
nextProps.components (e.g., include prevProps.components ===
nextProps.components in the logical AND) so the component re-renders when a
different components mapping is passed.
In `@services/platform/app/features/chat/components/typewriter-text.tsx`:
- Around line 173-181: The custom memo equality for the TypewriterText wrapper
currently only compares text, isStreaming, and className; update the equality
function used with memo (the second argument to memo for TypewriterText) to also
compare prevProps.components === nextProps.components so that changes to the
components prop (passed into TypewriterTextComponent) will trigger re-renders;
locate the TypewriterText memo block and add the components comparison alongside
the existing text/isStreaming/className checks.
…ssertions - Update setup-turbo action to use Node 24 (matching packageManager npm@11) - Regenerate lockfile with npm 11 for cross-platform optional dep entries - Hoist jsdom to root devDependencies so vitest can resolve it - Fix off-by-one character count in stream buffer test assertions
b6d6ed5 to
55d7c93
Compare
Summary
use-stream-bufferhook with improved chunking, jitter smoothing, and adaptive playback speed for smoother streaming outputtypewriter-textandincremental-markdownfor better performanceoverflow-anchor:noneto chat container to prevent scroll jumps during streamingTest plan
use-stream-buffertests:npm test --workspace=@tale/platform🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
Performance
Chores