Skip to content

feat(platform): refactor chat stream buffer and typewriter rendering - #510

Merged
larryro merged 4 commits into
mainfrom
feat/chat-stream-buffer-improvements
Feb 22, 2026
Merged

larryro merged 4 commits into
mainfrom
feat/chat-stream-buffer-improvements

Conversation

@larryro

@larryro larryro commented Feb 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Rewrote use-stream-buffer hook with improved chunking, jitter smoothing, and adaptive playback speed for smoother streaming output
  • Replaced CSS mask-based character reveal with ref-based DOM slicing in typewriter-text and incremental-markdown for better performance
  • Added overflow-anchor:none to chat container to prevent scroll jumps during streaming
  • Added comprehensive tests for the stream buffer hook
  • Removed unused streaming CSS from globals

Test plan

  • Verify chat streaming renders smoothly without visual glitches
  • Confirm scroll position stays stable during streaming (no anchor jumps)
  • Check typewriter effect works correctly for code blocks, markdown, and plain text
  • Run use-stream-buffer tests: npm test --workspace=@tale/platform

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • Performance

    • Optimized text streaming animation with improved buffering strategy for smoother character reveal.
    • Enhanced scroll behavior during real-time message updates.
    • Improved cursor visibility handling in streaming text.
  • Chores

    • Updated intl-messageformat dependency.

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-apps

greptile-apps Bot commented Feb 22, 2026

Copy link
Copy Markdown

Greptile Summary

Refactored chat streaming from adaptive speed to constant-rate buffering (50 CPS) with improved architecture:

  • Stream buffer: Simplified from complex adaptive rate with ring buffer metrics to straightforward constant-rate draining with initial buffering threshold
  • Rendering: Replaced CSS mask-based character reveal with ref-based DOM slicing in StreamingMarkdown component
  • Scroll stability: Added overflow-anchor:none to chat container to prevent scroll jumps
  • Tests: Added comprehensive test suite for the stream buffer hook

Issue found: incremental-markdown.tsx mutates refs during render phase (lines 151, 153), which violates React's rules and should be moved to useEffect

Confidence Score: 3/5

  • Safe to merge with one fix required for React rules compliance
  • The refactor simplifies the streaming architecture significantly and adds good test coverage. However, there's a React rules violation (mutating refs during render) in incremental-markdown.tsx that should be fixed to prevent potential runtime issues. The rest of the changes are well-structured and properly tested.
  • services/platform/app/features/chat/components/incremental-markdown.tsx - fix ref mutation during render

Important Files Changed

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
Loading

Last reviewed commit: be507b3

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

8 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment on lines +150 to +153
const revealedLenRef = useRef(revealedContent.length);
revealedLenRef.current = revealedContent.length;
const revealedTextRef = useRef(revealedContent);
revealedTextRef.current = revealedContent;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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]);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. The refs hold values derived deterministically from props (revealedContent), not DOM state
  2. If a concurrent render is discarded, the next render re-sets the refs to the correct values
  3. 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.

@coderabbitai

coderabbitai Bot commented Feb 22, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This 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 isStreaming prop from IncrementalMarkdown and updating its rendering from a dual-layer (hidden reference + visible reveal) to a single-layer approach using a dynamic components map for cursor injection; reworking the useStreamBuffer hook to use fixed-rate character reveal (targetCPS lowered from 120 to 50) with initial buffering via initialBufferChars instead of adaptive parameters (minBufferWords, catchUpMultiplier); removing the MetricsRingBuffer and per-frame speed calculations; updating typewriter-text.tsx to align with the new hook signature; removing streaming text layout stabilization CSS from globals.css; adding overflow-anchor:none to chat-interface.tsx; and introducing a comprehensive test suite for useStreamBuffer. A minor dependency version bump for intl-messageformat is also included.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~28 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: refactoring the chat stream buffer and typewriter rendering components with performance improvements.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/chat-stream-buffer-improvements

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 | 🟡 Minor

Missing components prop comparison in memo equality check.

The StreamingMarkdown memo equality function compares content, revealedLength, and showCursor, but omits components. 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 | 🟡 Minor

Memo should compare components prop for correctness, though current usage is stable.

The memo equality function omits the components prop from comparison. While this doesn't cause issues in practice—markdownComponents is a static module-level constant imported into all callers—the custom equality function should compare all props that affect rendering for defensive coding. If components were to change without text, isStreaming, or className changing, the memoization would incorrectly skip re-renders. Consider adding components to 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
@larryro
larryro force-pushed the feat/chat-stream-buffer-improvements branch from b6d6ed5 to 55d7c93 Compare February 22, 2026 11:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant