Skip to content

Fix chat scroll restoration across thread switches - #145

Merged
juliusmarminge merged 3 commits into
mainfrom
t3code/fix-thread-scroll-restoration
Mar 2, 2026
Merged

juliusmarminge merged 3 commits into
mainfrom
t3code/fix-thread-scroll-restoration

Conversation

@juliusmarminge

@juliusmarminge juliusmarminge commented Mar 2, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Stabilize scroll position when switching between threads by using stable row IDs in the virtualizer, preventing measurement leaks across thread switches
  • Always keep tail rows (last 8) unvirtualized to improve scroll stability near the bottom of the chat
  • Add attachment preview handoff mechanism to prevent image flicker when optimistic messages transition to server-confirmed messages
  • Schedule auto-scroll via requestAnimationFrame for smoother behavior
  • Track composer form height changes with ResizeObserver to maintain scroll position when the textarea grows/shrinks
  • Improve timeline message height estimation based on text length and attachments

Test plan

  • Switch between threads rapidly and verify scroll position stays at the bottom when expected
  • Send messages with image attachments and verify no flicker when the message transitions from optimistic to confirmed
  • Expand/collapse the composer textarea and verify scroll stays pinned to bottom
  • Scroll up mid-conversation, switch threads, then switch back - verify scroll position is reasonable
  • Verify virtualized content still renders correctly with stable row IDs

🤖 Generated with Claude Code


Note

Medium Risk
Changes core chat scrolling/virtualization behavior and blob URL lifecycle for image previews, which could introduce UI regressions (jumping scroll, incorrect measurements, or leaked/revoked previews) despite being frontend-only.

Overview
Improves chat sticky-bottom behavior when switching threads and during dynamic layout changes by scheduling bottom scroll via requestAnimationFrame, re-sticking shortly after thread switches, and reacting to composer height changes via ResizeObserver.

Hardens MessagesTimeline virtualization to avoid scroll/measurement leakage across threads by using stable row keys, keeping the last 8 rows unvirtualized, using content-based height estimates, and remeasuring on image load/error. Also adds a TTL-based attachment preview handoff so blob image previews don’t flicker when optimistic user messages are replaced by server-confirmed messages.

Written by Cursor Bugbot for commit 61a8ca2. This will update automatically on new commits. Configure here.

Note

Restore chat bottom stickiness across thread switches and implement rAF-based auto-scroll with a 96ms fallback, an 8-row unvirtualized tail, and a 5000ms attachment preview handoff in ChatView and MessagesTimeline

Add rAF-scheduled bottom scrolling with a timer fallback, transfer blob: image previews from optimistic to server messages with TTL, and update virtualization to keep the last 8 rows unvirtualized and measure rows using an estimator; wire image load/error to schedule re-measure and reset MessagesTimeline per thread.

📍Where to Start

Start with the auto-scroll and preview handoff logic in ChatView within ChatView.tsx, then review virtualization changes in MessagesTimeline in the same file.

Macroscope summarized 61a8ca2.

- Keep auto-scroll pinned to bottom during thread changes, composer resize, and streaming updates
- Improve virtualized timeline measurement/keying to prevent stale height reuse between threads
- Hand off blob image preview URLs from optimistic to server messages to avoid flicker/revocation races
@coderabbitai

coderabbitai Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch t3code/fix-thread-scroll-restoration

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

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Filtered preview URL array misaligns with attachment indices
    • Changed collectUserMessageBlobPreviewUrls to push undefined for skipped attachments instead of omitting them, preserving positional correspondence with the full attachments array, and updated all type signatures and length guards accordingly.

Create PR

Or push these changes by commenting:

@cursor push 8963dcf4b4
Preview (8963dcf4b4)
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -257,14 +257,20 @@
   }
 }
 
-function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
+function collectUserMessageBlobPreviewUrls(message: ChatMessage): (string | undefined)[] {
   if (message.role !== "user" || !message.attachments) {
     return [];
   }
-  const previewUrls: string[] = [];
+  const previewUrls: (string | undefined)[] = [];
   for (const attachment of message.attachments) {
-    if (attachment.type !== "image") continue;
-    if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
+    if (
+      attachment.type !== "image" ||
+      !attachment.previewUrl ||
+      !attachment.previewUrl.startsWith("blob:")
+    ) {
+      previewUrls.push(undefined);
+      continue;
+    }
     previewUrls.push(attachment.previewUrl);
   }
   return previewUrls;
@@ -505,7 +511,7 @@
   const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
   const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
   const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
-    Record<string, string[]>
+    Record<string, (string | undefined)[]>
   >({});
   const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useState<
     Record<string, string>
@@ -518,7 +524,7 @@
   const composerFormHeightRef = useRef(0);
   const composerCommandInputRef = useRef<HTMLInputElement>(null);
   const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
-  const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
+  const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, (string | undefined)[]>>({});
   const attachmentPreviewHandoffTimeoutByMessageIdRef = useRef<Record<string, number>>({});
   const sendInFlightRef = useRef(false);
   const dragDepthRef = useRef(0);
@@ -657,8 +663,9 @@
     attachmentPreviewHandoffByMessageIdRef.current = {};
     setAttachmentPreviewHandoffByMessageId({});
   }, []);
-  const handoffAttachmentPreviews = useCallback((messageId: MessageId, previewUrls: string[]) => {
-    if (previewUrls.length === 0) return;
+  const handoffAttachmentPreviews = useCallback(
+    (messageId: MessageId, previewUrls: (string | undefined)[]) => {
+    if (!previewUrls.some(Boolean)) return;
 
     const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
     for (const previewUrl of previousPreviewUrls) {
@@ -705,7 +712,7 @@
               return message;
             }
             const handoffPreviewUrls = attachmentPreviewHandoffByMessageId[message.id];
-            if (!handoffPreviewUrls || handoffPreviewUrls.length === 0) {
+            if (!handoffPreviewUrls || !handoffPreviewUrls.some(Boolean)) {
               return message;
             }
 
@@ -1414,7 +1421,7 @@
     setOptimisticUserMessages((existing) => existing.filter((message) => !serverIds.has(message.id)));
     for (const removedMessage of removedMessages) {
       const previewUrls = collectUserMessageBlobPreviewUrls(removedMessage);
-      if (previewUrls.length > 0) {
+      if (previewUrls.some(Boolean)) {
         handoffAttachmentPreviews(removedMessage.id, previewUrls);
         continue;
       }

Comment thread apps/web/src/components/ChatView.tsx Resolved
collectUserMessageBlobPreviewUrls returns a compact array (image+blob only).
Consumer now indexes by image position, not full attachment index, so
blob URLs apply to the correct server attachments when some are skipped.

Made-with: Cursor

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Redundant workLogCount effect duplicates timelineEntries effect
    • Removed the redundant workLogCount effect and its unused variable since timelineEntries already depends on workLogEntries via useMemo, making the workLogCount effect dead code.

Create PR

Or push these changes by commenting:

@cursor push 85b49d6de6
Preview (85b49d6de6)
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -1284,7 +1284,6 @@
 
   // Auto-scroll on new messages
   const messageCount = timelineMessages.length;
-  const workLogCount = workLogEntries.length;
   const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
     const scrollContainer = messagesScrollRef.current;
     if (!scrollContainer) return;
@@ -1358,11 +1357,6 @@
     if (phase !== "running") return;
     if (!shouldAutoScrollRef.current) return;
     scheduleStickToBottom();
-  }, [phase, scheduleStickToBottom, workLogCount]);
-  useEffect(() => {
-    if (phase !== "running") return;
-    if (!shouldAutoScrollRef.current) return;
-    scheduleStickToBottom();
   }, [phase, scheduleStickToBottom, timelineEntries]);
 
   useEffect(() => {

Comment thread apps/web/src/components/ChatView.tsx Resolved
timelineEntries is derived from workLogEntries; the timelineEntries
effect already runs when work log changes. Dropped duplicate effect
and unused workLogCount variable.

Made-with: Cursor
@juliusmarminge
juliusmarminge merged commit 5c09614 into main Mar 2, 2026
3 checks passed

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Mixed height measurement APIs cause spurious change detection
    • Changed the ResizeObserver callback to use entry.borderBoxSize[0]?.blockSize (with contentRect fallback) so both the initial seed and subsequent measurements use border-box dimensions consistently.

Create PR

Or push these changes by commenting:

@cursor push cffc3013cd
Preview (cffc3013cd)
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -1335,7 +1335,7 @@
       const [entry] = entries;
       if (!entry) return;
 
-      const nextHeight = entry.contentRect.height;
+      const nextHeight = entry.borderBoxSize[0]?.blockSize ?? entry.contentRect.height;
       const previousHeight = composerFormHeightRef.current;
       composerFormHeightRef.current = nextHeight;

const [entry] = entries;
if (!entry) return;

const nextHeight = entry.contentRect.height;

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.

Mixed height measurement APIs cause spurious change detection

Low Severity

The initial height is stored via getBoundingClientRect().height (border-box size, including padding and border) but the ResizeObserver callback reads entry.contentRect.height (content-box size, excluding padding and border). If the composer form element ever acquires padding or a border (from CSS changes or user-agent styles), the first observer callback will always detect a spurious height "change" and trigger scheduleStickToBottom(), because the two measurement APIs return different values for the same element. Using entry.borderBoxSize[0].blockSize (or consistently using contentRect for the initial seed) would keep the comparison consistent.

Fix in Cursor Fix in Web

TomCohenDev pushed a commit to TomCohenDev/t3code that referenced this pull request Oct 18, 2026
…pired-arrow-sessions

fix(server): an expired machine arrow ends the sessions it granted
TomCohenDev pushed a commit to TomCohenDev/t3code that referenced this pull request Oct 18, 2026
- Client sessions end when an arrow expires: the old level side reads the
  level the sessions got, through the helper of pingdotgg#145 (MM-912).
- A portal set up before app invites reports the missing /client app, so
  "Set up approvals" shows again (MM-1208).
- Invites last 15 minutes and have "Cancel invite" in the client panel and
  the dialog (MM-913).
- Token removal treats a Cloudflare 404 as done, and removal decides by the
  stored token id (MM-915).
- Redeem reads the client again after the Cloudflare calls and deletes the
  new token when the client is gone or a pause cut its arrows.
- The /enroll Bypass app covers /enroll/client, so the extra bypass app is
  gone. README, spec and fork docs updated.
HaukeSchnau referenced this pull request in HaukeSchnau/t3code Nov 9, 2026
CodeRabbit on #145: the wake command's stderr was read without a limit and
shown to clients in the host's failure message. Now a 4 KiB tail goes to the
error for logs, clients see a fixed summary, and a changed wake command is
compared element by element.
gmackie pushed a commit to gmackie/t3code that referenced this pull request Nov 21, 2026
…in GMACKO Nightly' (pingdotgg#145) from T3CODE-125-git-auth into custom-local
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