Skip to content

feat(platform): persistent chat, scroll-intent, typewriter, and system message tags - #836

Merged
larryro merged 4 commits into
mainfrom
feat/chat-persistent-scroll-intent
Mar 23, 2026
Merged

larryro merged 4 commits into
mainfrom
feat/chat-persistent-scroll-intent

Conversation

@larryro

@larryro larryro commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR consolidates several interlocking chat UX improvements: persistent component mounting, scroll-intent-based auto-scrolling, constant-rate typewriter, structured system message tags, and GFM table streaming support.

Persistent ChatInterface & route consolidation

  • Lift ChatInterface from leaf routes into the parent chat layout so it stays mounted across thread navigation — eliminates unmount/remount flicker and preserves pending message state
  • Child routes ($threadId.tsx, index.tsx) now render null; threadId is read via useMatch
  • New chat button clears state (clearChatState) before navigating

Scroll-intent auto-scrolling

  • Replace ad-hoc scrollTo() calls with an assistant-ui-style scroll-intent pattern
  • scrollingToBottomBehaviorRef tracks desired behavior: 'auto' (smooth on send), 'instant' (on thread load), null (idle)
  • ResizeObserver fires synchronously before paint for flicker-free scroll pinning; MutationObserver catches DOM changes that don't trigger resize
  • Passive scroll listener clears the ref when scroll settles
  • Smart min-height computation: fills viewport for short user messages, skips for tall ones (CLAMP_THRESHOLD = 160px)

Constant-rate typewriter

  • Simplify from adaptive acceleration (sqrt-curve CPS scaling) to fixed 20 CPS for a steadier, more predictable reading experience
  • Remove computeEffectiveCPS() and ~150 lines of acceleration logic from useStreamBuffer

Structured system message tags

  • New shared SYSTEM_MSG_TAG constant map and parseSystemMessageTag() parser replacing hardcoded prefix checks
  • Five display variants: pill, success, warning, error, info — each with contextual colors, icons, and ARIA roles
  • CollapsibleSystemMessage now uses CVA-based variant styling with semantic icons (CheckCircle2, AlertTriangle, XCircle, Info)
  • Backend messages updated: human input responses use [HUMAN_INPUT_RESPONSE] tag format; interruption/timeout use [RESPONSE_INTERRUPTED]/[TIMEOUT_RECOVERY]

GFM table auto-completion

  • New remendTable() in remendMarkdown handles incomplete tables during streaming: appends separator for header-only, closes partial data rows
  • Column count inferred from header for correct separator generation

Agent tool messaging

  • Remove all positional language ("below your message", "appears BELOW") from approval card references across 9 agent tool files
  • Add dynamic instruction in create_agent_config.ts to suppress position mentions when approval-card tools are present

Automation assistant alignment

  • Migrate automation assistant message list to the same system message tag parsing as main chat
  • Replace isHumanInputResponse boolean with systemMessageDisplay + systemMessageBody

Test plan

  • system-message-tags.test.ts — tag parsing, display mapping, all known tags, unknown fallback (114 lines)
  • use-message-processing.test.ts — all display variants: pill, success, warning, error, info (122+ lines)
  • use-pending-messages.test.ts — stale pending message handling, pending thread ID matching
  • remend-markdown.test.ts — table completion, fence remedying, link/image syntax
  • Manual: smooth auto-scroll on new assistant messages, stops when user scrolls up
  • Manual: no flicker on route changes between chat threads
  • Manual: system messages render with correct variant styling and icons
  • Manual: streaming tables render correctly mid-stream

@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.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@coderabbitai

coderabbitai Bot commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR refactors chat auto-scroll behavior, layout handling, and routing. The chat interface now uses a unified scrollingToBottomRef mechanism to manage scroll-to-bottom intent across ResizeObserver, MutationObserver, and explicit scroll events, setting the flag during thread loads and message sends. The chat messages component adds response area min-height clamping, removes pending-to-real message swap scroll logic, introduces stable key reuse for pending→real transitions to prevent DOM flicker, and disables browser overflow anchoring. Message bubbles gain synchronous initial overflow detection and debounced recalculation. Routing is restructured to render ChatInterface directly in the parent chat route with Suspense, moving it from the nested $threadId route, while both nested and index routes are reduced to no-ops.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ⚠️ Warning The title mentions 'persistent chat, scroll-intent, typewriter, and system message tags' but the actual changes focus on persistent ChatInterface, scroll-intent auto-scrolling, message key stabilization, and layout optimizations. The title references 'typewriter' and 'system message tags' which are not evident in the provided changeset. Update the title to accurately reflect the main changes: 'feat(platform): persistent chat interface and scroll-intent auto-scrolling' or similar, removing references to unimplemented features like typewriter and system message tags.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/chat-persistent-scroll-intent

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 (1)
services/platform/app/features/chat/components/chat-messages.tsx (1)

171-189: ⚠️ Potential issue | 🟠 Major

Recompute minHeight when the last user message itself resizes.

computeResponseMinHeight() reads lastUserMessageRef.current, but this observer only watches the container and sticky footer. Expanding/collapsing the last user message—or any async height change inside it—leaves responseArea.style.minHeight stale until a window/footer resize, which brings back the empty-gap layout this PR is trying to remove.

♻️ Proposed fix
-  useEffect(() => {
+  useEffect(() => {
     const container = containerRef.current;
     const responseArea = responseAreaRef.current;
     if (!container || !responseArea) return;
+    const lastUser = lastUserMessageRef.current;
 
     const update = () => {
       const next = `${computeResponseMinHeight(container, responseArea, lastUserMessageRef.current)}px`;
       if (prevMinHeightRef.current === next) return;
       prevMinHeightRef.current = next;
       responseArea.style.minHeight = next;
     };
 
     const ro = new ResizeObserver(update);
     ro.observe(container);
     const footer = container.querySelector('[class*="sticky"]');
     if (footer instanceof HTMLElement) ro.observe(footer);
+    if (lastUser instanceof HTMLElement) ro.observe(lastUser);
 
     return () => ro.disconnect();
-  }, [containerRef, lastUserMessageRef]);
+  }, [containerRef, lastUserMessageRef, lastUserMessageKey]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@services/platform/app/features/chat/components/chat-messages.tsx` around
lines 171 - 189, The ResizeObserver currently watches container and sticky
footer but not the last user message, so computeResponseMinHeight(container,
responseArea, lastUserMessageRef.current) can become stale; update the effect
(useEffect) to also observe lastUserMessageRef.current (check it's an
HTMLElement) with the same ResizeObserver (ro.observe(lastUserMessageEl)) and
ensure it is observed/cleaned up on teardown and reattached when
lastUserMessageRef.current changes so responseAreaRef.style.minHeight updates
when the last user message resizes.
🤖 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/components/chat-interface.tsx`:
- Around line 207-243: The onScroll handler currently clears
scrollingToBottomRef when the component's own scroll reaches bottom; change
onScroll to accept the scroll event and only clear scrollingToBottomRef.current
when the scroll was user-initiated (e.g., event?.isTrusted === true) and the
user has scrolled away from bottom or has subsequently reached bottom by their
own action; do not clear the ref for programmatic scrolls triggered by
onContentChange. Keep the explicit follow-mode toggle logic separate so follow
mode is only disabled by a user scroll away and can be re-enabled only when the
user explicitly requests it (wire this to the existing follow toggle control
that sets scrollingToBottomRef.current).

In `@services/platform/app/features/chat/components/chat-messages.tsx`:
- Around line 138-141: prevPendingKeyRef currently holds a pending-* key
indefinitely and can be reused across unrelated messages/threads, causing
MessageBubble state leaks (isExpanded/isOverflowing); update the logic around
prevPendingKeyRef to scope it to a single pending→real swap by clearing or
resetting it as soon as the pending message is replaced with its resolved key
and whenever the thread/messages change: detect the swap (e.g., in the same
place that replaces a pending key with its real key or in a useEffect that
watches messages/lastMessage) and set prevPendingKeyRef.current = null (or
update it to the new resolved key mapping) so a stale pending-* value cannot be
reused for subsequent non-pending messages; reference prevPendingKeyRef, the
pending-* key generation, and the MessageBubble/ChatInterface update path when
applying this fix.

---

Outside diff comments:
In `@services/platform/app/features/chat/components/chat-messages.tsx`:
- Around line 171-189: The ResizeObserver currently watches container and sticky
footer but not the last user message, so computeResponseMinHeight(container,
responseArea, lastUserMessageRef.current) can become stale; update the effect
(useEffect) to also observe lastUserMessageRef.current (check it's an
HTMLElement) with the same ResizeObserver (ro.observe(lastUserMessageEl)) and
ensure it is observed/cleaned up on teardown and reattached when
lastUserMessageRef.current changes so responseAreaRef.style.minHeight updates
when the last user message resizes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 34a744dc-d5c7-4601-ad8f-aa5627046de4

📥 Commits

Reviewing files that changed from the base of the PR and between 07a0b2f and d937bf1.

📒 Files selected for processing (6)
  • services/platform/app/features/chat/components/chat-interface.tsx
  • services/platform/app/features/chat/components/chat-messages.tsx
  • services/platform/app/features/chat/components/message-bubble.tsx
  • services/platform/app/routes/dashboard/$id/chat.tsx
  • services/platform/app/routes/dashboard/$id/chat/$threadId.tsx
  • services/platform/app/routes/dashboard/$id/chat/index.tsx

Comment on lines +138 to +141
const prevMinHeightRef = useRef('');
// Tracks the pending key so the last user message keeps a stable React key
// across the pending→real swap (prevents DOM teardown/rebuild flicker).
const prevPendingKeyRef = useRef<string | null>(null);

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.

⚠️ Potential issue | 🟠 Major

Bound the pending-key reuse to a single pending→real swap.

prevPendingKeyRef never gets cleared or tied to a specific resolved key. Once it captures one pending-* key, every later non-pending last user message can inherit that stale React key. With ChatInterface now staying mounted across thread changes, that can reuse MessageBubble state across unrelated messages/threads and leak UI state like isExpanded or isOverflowing.

Also applies to: 225-234

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@services/platform/app/features/chat/components/chat-messages.tsx` around
lines 138 - 141, prevPendingKeyRef currently holds a pending-* key indefinitely
and can be reused across unrelated messages/threads, causing MessageBubble state
leaks (isExpanded/isOverflowing); update the logic around prevPendingKeyRef to
scope it to a single pending→real swap by clearing or resetting it as soon as
the pending message is replaced with its resolved key and whenever the
thread/messages change: detect the swap (e.g., in the same place that replaces a
pending key with its real key or in a useEffect that watches
messages/lastMessage) and set prevPendingKeyRef.current = null (or update it to
the new resolved key mapping) so a stale pending-* value cannot be reused for
subsequent non-pending messages; reference prevPendingKeyRef, the pending-* key
generation, and the MessageBubble/ChatInterface update path when applying this
fix.

@larryro larryro changed the title feat(platform): persistent ChatInterface and scroll-intent auto-scrolling feat(platform): persistent chat, scroll-intent, typewriter, and system message tags Mar 23, 2026
larryro added 4 commits March 23, 2026 21:43
…ling

Lift ChatInterface from child routes into the chat layout so it stays
mounted across route changes (no unmount/remount flicker). Child routes
now render null; threadId is read via useMatch.

Replace ad-hoc scroll-to-bottom logic with an assistant-ui-style
scroll-intent pattern: a ref tracks intent, ResizeObserver + MutationObserver
keep the container pinned to bottom until the user scrolls away.
Adds CLAMP_THRESHOLD to skip min-height for tall user messages,
stable React keys across pending→real message swaps, and synchronous
useLayoutEffect overflow check in MessageBubble.
…variants

Introduce a shared SYSTEM_MSG_TAG constant map and parser to replace
hardcoded prefix checks for system messages. CollapsibleSystemMessage
now renders with contextual styling (success/warning/error/info) based
on the parsed tag. Agent config gains an instruction to avoid
referencing approval card position in chat.
…table completion

Simplify typewriter to a fixed 20 CPS (removing adaptive acceleration)
for a steadier reading experience. Refine scroll-intent to carry the
desired ScrollBehavior ('auto' on send, 'instant' on thread init) so
the container uses smooth scrolling for new messages. Add GFM table
auto-completion to remendMarkdown so partially streamed tables render
correctly.
…refactor

Remove unused SystemMsgTag export (Knip) and rewrite adaptive-CPS tests
to match the constant-rate algorithm introduced in a848692.
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