Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(conversation): pin user message to viewport top & fold long user messages (#14056)

Inneied6330362c3a
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 7147b31a466..3eb6260d331 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -192,6 +192,8 @@
"messageAction.interruptedHint": "What should I do instead?",
"messageAction.reaction": "Add Reaction",
"messageAction.regenerate": "Regenerate",
+ "messageLongCollapse.collapse": "Show less",
+ "messageLongCollapse.expand": "Show more",
"messages.dm.sentTo": "Visible only to {{name}}",
"messages.dm.title": "DM",
"messages.modelCard.credit": "Credits",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 431d612b174..2b82c876e17 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -192,6 +192,8 @@
"messageAction.interruptedHint": "接下来需要做什么?",
"messageAction.reaction": "添加表情",
"messageAction.regenerate": "重新生成",
+ "messageLongCollapse.collapse": "收起",
+ "messageLongCollapse.expand": "展开全部",
"messages.dm.sentTo": "仅对 {{name}} 可见",
"messages.dm.title": "私信",
"messages.modelCard.credit": "积分",
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index 963e43de23f..4913f4a6ba9 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -36,9 +36,11 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
handleScrollOffset,
isSpacerMessage,
listData,
+ registerSpacerNode,
scrollShrinking,
spacerHeight,
spacerActive,
+ spacerLayoutVersion,
} = useConversationSpacer(dataSource);
const isAutoScrollEnabled = useAutoScrollEnabled();
@@ -147,8 +149,10 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
useScrollToUserMessage({
dataSourceLength: dataSource.length,
isSecondLastMessageFromUser,
+ scrollShrinking,
scrollToIndex: virtuaRef.current?.scrollToIndex ?? null,
spacerActive,
+ spacerLayoutVersion,
});
// Scroll to bottom on initial render
@@ -175,16 +179,23 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
>
{(messageId, index): ReactElement => {
if (isSpacerMessage(messageId)) {
+ // Only animate the collapse-to-zero (unmount). Any non-zero height
+ // change (initial mount, shrink as assistant grows) is applied
+ // instantly so virtua's scrollSize updates in a single frame and
+ // scrollToIndex can reach the user message without trailing behind
+ // a 200ms transition.
+ const shouldAnimate = !scrollShrinking && spacerHeight === 0;
return (
<WideScreenContainer key={messageId} style={{ position: 'relative' }}>
<div
aria-hidden
+ ref={registerSpacerNode}
style={{
height: spacerHeight,
pointerEvents: 'none',
- transition: scrollShrinking
- ? 'none'
- : `height ${CONVERSATION_SPACER_TRANSITION_MS}ms ease`,
+ transition: shouldAnimate
+ ? `height ${CONVERSATION_SPACER_TRANSITION_MS}ms ease`
+ : 'none',
width: '100%',
}}
/>
diff --git a/src/features/Conversation/ChatList/hooks/useConversationSpacer.ts b/src/features/Conversation/ChatList/hooks/useConversationSpacer.ts
index 6829f2d2f89..67a788e825a 100644
--- a/src/features/Conversation/ChatList/hooks/useConversationSpacer.ts
+++ b/src/features/Conversation/ChatList/hooks/useConversationSpacer.ts
@@ -45,10 +45,12 @@ export const useConversationSpacer = (dataSource: string[]) => {
const [naturalHeight, setNaturalHeight] = useState(0);
const [scrollReduction, setScrollReduction] = useState(0);
const [mounted, setMounted] = useState(false);
+ const [spacerLayoutVersion, setSpacerLayoutVersion] = useState(0);
const prevLengthRef = useRef(dataSource.length);
const removeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const resizeObserverRef = useRef<ResizeObserver | null>(null);
+ const spacerObserverRef = useRef<ResizeObserver | null>(null);
const userMessageIndexRef = useRef<number | null>(null);
const assistantMessageIndexRef = useRef<number | null>(null);
@@ -97,6 +99,11 @@ export const useConversationSpacer = (dataSource: string[]) => {
resizeObserverRef.current = null;
}, []);
+ const cleanupSpacerObserver = useCallback(() => {
+ spacerObserverRef.current?.disconnect();
+ spacerObserverRef.current = null;
+ }, []);
+
const scheduleUnmount = useCallback(() => {
clearRemoveTimer();
@@ -179,10 +186,32 @@ export const useConversationSpacer = (dataSource: string[]) => {
useEffect(() => {
return () => {
cleanupObserver();
+ cleanupSpacerObserver();
clearRemoveTimer();
if (scrollShrinkEndTimerRef.current) clearTimeout(scrollShrinkEndTimerRef.current);
};
- }, [cleanupObserver, clearRemoveTimer]);
+ }, [cleanupObserver, cleanupSpacerObserver, clearRemoveTimer]);
+
+ // Ref callback bound to this hook's own spacer node. Using a ref (rather than
+ // a document-wide querySelector) scopes observation to the spacer owned by
+ // this list instance — ConversationProvider supports multiple simultaneously
+ // mounted lists, so a global selector could attach to another panel's spacer
+ // and drive spacerLayoutVersion from unrelated layout changes.
+ const registerSpacerNode = useCallback(
+ (node: HTMLElement | null) => {
+ cleanupSpacerObserver();
+
+ if (!node || typeof ResizeObserver === 'undefined') return;
+
+ const observer = new ResizeObserver(() => {
+ setSpacerLayoutVersion((v) => v + 1);
+ });
+ observer.observe(node);
+ spacerObserverRef.current = observer;
+ setSpacerLayoutVersion((v) => v + 1);
+ },
+ [cleanupSpacerObserver],
+ );
useEffect(() => {
const newMessageCount = dataSource.length - prevLengthRef.current;
@@ -248,8 +277,10 @@ export const useConversationSpacer = (dataSource: string[]) => {
handleScrollOffset,
isSpacerMessage: (id: string) => id === CONVERSATION_SPACER_ID,
listData,
+ registerSpacerNode,
scrollShrinking: isScrollShrinking,
spacerActive: mounted,
spacerHeight: renderedHeight,
+ spacerLayoutVersion,
};
};
diff --git a/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.test.ts b/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.test.ts
index 49295f93e70..51c291184bf 100644
--- a/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.test.ts
@@ -3,6 +3,28 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useScrollToUserMessage } from './useScrollToUserMessage';
+type Props = {
+ dataSourceLength: number;
+ isSecondLastMessageFromUser: boolean;
+ scrollShrinking?: boolean;
+ spacerActive: boolean;
+ spacerLayoutVersion?: number;
+};
+
+const makeRender = (scrollToIndex: ReturnType<typeof vi.fn> | null, initialProps: Props) =>
+ renderHook(
+ (props: Props) =>
+ useScrollToUserMessage({
+ dataSourceLength: props.dataSourceLength,
+ isSecondLastMessageFromUser: props.isSecondLastMessageFromUser,
+ scrollShrinking: props.scrollShrinking,
+ scrollToIndex,
+ spacerActive: props.spacerActive,
+ spacerLayoutVersion: props.spacerLayoutVersion,
+ }),
+ { initialProps },
+ );
+
describe('useScrollToUserMessage', () => {
beforeEach(() => {
vi.useFakeTimers();
@@ -16,126 +38,290 @@ describe('useScrollToUserMessage', () => {
it('should retry scrolling to user message when 2 new messages are added and spacer is active', () => {
const scrollToIndex = vi.fn();
- const { rerender } = renderHook(
- ({ dataSourceLength, isSecondLastMessageFromUser, spacerActive }) =>
- useScrollToUserMessage({
- dataSourceLength,
- isSecondLastMessageFromUser,
- scrollToIndex,
- spacerActive,
- }),
- {
- initialProps: {
- dataSourceLength: 2,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- },
- },
- );
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 2,
+ isSecondLastMessageFromUser: false,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
- // User sends a new message (2 messages added: user + assistant, second-to-last is user)
- // spacerActive is already true (e.g. from previous message)
rerender({
dataSourceLength: 4,
isSecondLastMessageFromUser: true,
spacerActive: true,
+ spacerLayoutVersion: 0,
});
act(() => {
vi.runAllTimers();
});
+ // send-triggered retries + spacerActive follow-up fire in the same tick;
+ // executeScroll clears prior pending timers so only the last retry wave runs.
expect(scrollToIndex).toHaveBeenCalledTimes(3);
expect(scrollToIndex).toHaveBeenNthCalledWith(1, 2, { align: 'start', smooth: true });
- expect(scrollToIndex).toHaveBeenNthCalledWith(2, 2, { align: 'start', smooth: true });
- expect(scrollToIndex).toHaveBeenNthCalledWith(3, 2, { align: 'start', smooth: true });
});
it('should scroll immediately and re-scroll when spacer becomes active', () => {
const scrollToIndex = vi.fn();
- const { rerender } = renderHook(
- ({ dataSourceLength, isSecondLastMessageFromUser, spacerActive }) =>
- useScrollToUserMessage({
- dataSourceLength,
- isSecondLastMessageFromUser,
- scrollToIndex,
- spacerActive,
- }),
- {
- initialProps: {
- dataSourceLength: 2,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- },
- },
- );
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 2,
+ isSecondLastMessageFromUser: false,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
- // User sends a new message, spacer not yet active
rerender({
dataSourceLength: 4,
isSecondLastMessageFromUser: true,
spacerActive: false,
+ spacerLayoutVersion: 0,
});
act(() => {
vi.runAllTimers();
});
- // Should scroll immediately even without spacer (content may fill viewport)
expect(scrollToIndex).toHaveBeenCalledTimes(3);
expect(scrollToIndex).toHaveBeenNthCalledWith(1, 2, { align: 'start', smooth: true });
scrollToIndex.mockClear();
- // Spacer becomes active – should re-scroll with correct fill height
rerender({
dataSourceLength: 4,
isSecondLastMessageFromUser: true,
spacerActive: true,
+ spacerLayoutVersion: 0,
+ });
+
+ act(() => {
+ vi.runAllTimers();
+ });
+
+ expect(scrollToIndex).toHaveBeenCalledTimes(3);
+ expect(scrollToIndex).toHaveBeenNthCalledWith(1, 2, { align: 'start', smooth: true });
+ });
+
+ it('should re-scroll whenever spacerLayoutVersion bumps while active', () => {
+ const scrollToIndex = vi.fn();
+
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 2,
+ isSecondLastMessageFromUser: false,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
+
+ // user sends message; spacer becomes active
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: true,
+ spacerLayoutVersion: 0,
+ });
+
+ act(() => {
+ vi.runAllTimers();
+ });
+ scrollToIndex.mockClear();
+
+ // spacer DOM is measured; version bumps -> should re-fire scroll
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: true,
+ spacerLayoutVersion: 1,
});
act(() => {
vi.runAllTimers();
});
- // Follow-up scroll after spacer mounted
expect(scrollToIndex).toHaveBeenCalledTimes(3);
expect(scrollToIndex).toHaveBeenNthCalledWith(1, 2, { align: 'start', smooth: true });
});
+ it('should stop re-scrolling once the spacer unmounts', () => {
+ const scrollToIndex = vi.fn();
+
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 2,
+ isSecondLastMessageFromUser: false,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
+
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: true,
+ spacerLayoutVersion: 1,
+ });
+
+ act(() => {
+ vi.runAllTimers();
+ });
+ scrollToIndex.mockClear();
+
+ // spacer unmounts -> pending cleared
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: false,
+ spacerLayoutVersion: 1,
+ });
+
+ // a subsequent version bump with spacer gone must not re-scroll
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: false,
+ spacerLayoutVersion: 2,
+ });
+
+ act(() => {
+ vi.runAllTimers();
+ });
+
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('should cancel queued retry timers when user scrolls up before they fire', () => {
+ const scrollToIndex = vi.fn();
+
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 2,
+ isSecondLastMessageFromUser: false,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
+
+ // user sends message -> 0/32/96ms retry timers are scheduled but not fired yet
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: true,
+ spacerLayoutVersion: 0,
+ });
+
+ // user immediately starts scrolling up before any retry timer fires
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ scrollShrinking: true,
+ spacerActive: true,
+ spacerLayoutVersion: 0,
+ });
+
+ act(() => {
+ vi.runAllTimers();
+ });
+
+ // no queued retry should have yanked the viewport back
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('should cancel queued retry timers when spacer unmounts before they fire', () => {
+ const scrollToIndex = vi.fn();
+
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 2,
+ isSecondLastMessageFromUser: false,
+ spacerActive: true,
+ spacerLayoutVersion: 0,
+ });
+
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: true,
+ spacerLayoutVersion: 0,
+ });
+
+ // spacer unmounts before any retry timer fires
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
+
+ act(() => {
+ vi.runAllTimers();
+ });
+
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('should stop pinning when user starts shrinking the spacer manually', () => {
+ const scrollToIndex = vi.fn();
+
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 2,
+ isSecondLastMessageFromUser: false,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
+
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: true,
+ spacerLayoutVersion: 1,
+ });
+
+ act(() => {
+ vi.runAllTimers();
+ });
+ scrollToIndex.mockClear();
+
+ // user scrolls up -> scrollShrinking true, pending cleared
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ scrollShrinking: true,
+ spacerActive: true,
+ spacerLayoutVersion: 1,
+ });
+
+ // even if layout keeps ticking, we must not pin back to top
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ scrollShrinking: true,
+ spacerActive: true,
+ spacerLayoutVersion: 2,
+ });
+
+ act(() => {
+ vi.runAllTimers();
+ });
+
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
it('should scroll without spacer when spacer never mounts (content fills viewport)', () => {
const scrollToIndex = vi.fn();
- const { rerender } = renderHook(
- ({ dataSourceLength, isSecondLastMessageFromUser, spacerActive }) =>
- useScrollToUserMessage({
- dataSourceLength,
- isSecondLastMessageFromUser,
- scrollToIndex,
- spacerActive,
- }),
- {
- initialProps: {
- dataSourceLength: 2,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- },
- },
- );
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 2,
+ isSecondLastMessageFromUser: false,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
- // User sends a new message, spacer will never mount (height = 0)
rerender({
dataSourceLength: 4,
isSecondLastMessageFromUser: true,
spacerActive: false,
+ spacerLayoutVersion: 0,
});
act(() => {
vi.runAllTimers();
});
- // Should still scroll – no spacer needed when content fills viewport
expect(scrollToIndex).toHaveBeenCalledTimes(3);
expect(scrollToIndex).toHaveBeenNthCalledWith(1, 2, { align: 'start', smooth: true });
});
@@ -143,28 +329,18 @@ describe('useScrollToUserMessage', () => {
it('should scroll to correct index when multiple user messages are sent', () => {
const scrollToIndex = vi.fn();
- const { rerender } = renderHook(
- ({ dataSourceLength, isSecondLastMessageFromUser, spacerActive }) =>
- useScrollToUserMessage({
- dataSourceLength,
- isSecondLastMessageFromUser,
- scrollToIndex,
- spacerActive,
- }),
- {
- initialProps: {
- dataSourceLength: 4,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- },
- },
- );
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: false,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
- // User sends a new message (2 messages added)
rerender({
dataSourceLength: 6,
isSecondLastMessageFromUser: true,
spacerActive: true,
+ spacerLayoutVersion: 0,
});
act(() => {
@@ -179,28 +355,18 @@ describe('useScrollToUserMessage', () => {
it('should NOT scroll when only 1 new message is added (AI response)', () => {
const scrollToIndex = vi.fn();
- const { rerender } = renderHook(
- ({ dataSourceLength, isSecondLastMessageFromUser, spacerActive }) =>
- useScrollToUserMessage({
- dataSourceLength,
- isSecondLastMessageFromUser,
- scrollToIndex,
- spacerActive,
- }),
- {
- initialProps: {
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- },
- },
- );
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
- // AI adds another message (only 1 message added, not 2)
rerender({
dataSourceLength: 5,
isSecondLastMessageFromUser: false,
spacerActive: true,
+ spacerLayoutVersion: 0,
});
expect(scrollToIndex).not.toHaveBeenCalled();
@@ -209,37 +375,27 @@ describe('useScrollToUserMessage', () => {
it('should NOT scroll when multiple agents respond in group chat', () => {
const scrollToIndex = vi.fn();
- const { rerender } = renderHook(
- ({ dataSourceLength, isSecondLastMessageFromUser, spacerActive }) =>
- useScrollToUserMessage({
- dataSourceLength,
- isSecondLastMessageFromUser,
- scrollToIndex,
- spacerActive,
- }),
- {
- initialProps: {
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- },
- },
- );
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
- // First agent responds (1 message added)
rerender({
dataSourceLength: 5,
isSecondLastMessageFromUser: false,
spacerActive: true,
+ spacerLayoutVersion: 0,
});
expect(scrollToIndex).not.toHaveBeenCalled();
- // Second agent responds (1 message added)
rerender({
dataSourceLength: 6,
isSecondLastMessageFromUser: false,
spacerActive: true,
+ spacerLayoutVersion: 0,
});
expect(scrollToIndex).not.toHaveBeenCalled();
@@ -248,28 +404,18 @@ describe('useScrollToUserMessage', () => {
it('should NOT scroll when 2 messages added but second-to-last is not user', () => {
const scrollToIndex = vi.fn();
- const { rerender } = renderHook(
- ({ dataSourceLength, isSecondLastMessageFromUser, spacerActive }) =>
- useScrollToUserMessage({
- dataSourceLength,
- isSecondLastMessageFromUser,
- scrollToIndex,
- spacerActive,
- }),
- {
- initialProps: {
- dataSourceLength: 4,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- },
- },
- );
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: false,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
- // 2 messages added but both are from AI (e.g., system messages)
rerender({
dataSourceLength: 6,
isSecondLastMessageFromUser: false,
spacerActive: true,
+ spacerLayoutVersion: 0,
});
expect(scrollToIndex).not.toHaveBeenCalled();
@@ -280,28 +426,18 @@ describe('useScrollToUserMessage', () => {
it('should NOT scroll when length decreases (message deleted)', () => {
const scrollToIndex = vi.fn();
- const { rerender } = renderHook(
- ({ dataSourceLength, isSecondLastMessageFromUser, spacerActive }) =>
- useScrollToUserMessage({
- dataSourceLength,
- isSecondLastMessageFromUser,
- scrollToIndex,
- spacerActive,
- }),
- {
- initialProps: {
- dataSourceLength: 6,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- },
- },
- );
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 6,
+ isSecondLastMessageFromUser: true,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
- // Message deleted (length decreases)
rerender({
dataSourceLength: 4,
isSecondLastMessageFromUser: true,
spacerActive: true,
+ spacerLayoutVersion: 0,
});
expect(scrollToIndex).not.toHaveBeenCalled();
@@ -310,57 +446,37 @@ describe('useScrollToUserMessage', () => {
it('should NOT scroll when length stays the same', () => {
const scrollToIndex = vi.fn();
- const { rerender } = renderHook(
- ({ dataSourceLength, isSecondLastMessageFromUser, spacerActive }) =>
- useScrollToUserMessage({
- dataSourceLength,
- isSecondLastMessageFromUser,
- scrollToIndex,
- spacerActive,
- }),
- {
- initialProps: {
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- },
- },
- );
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
- // Length stays the same (content update, not new message)
rerender({
dataSourceLength: 4,
isSecondLastMessageFromUser: true,
spacerActive: true,
+ spacerLayoutVersion: 0,
});
expect(scrollToIndex).not.toHaveBeenCalled();
});
it('should handle null scrollToIndex gracefully', () => {
- const { rerender } = renderHook(
- ({ dataSourceLength, isSecondLastMessageFromUser, spacerActive }) =>
- useScrollToUserMessage({
- dataSourceLength,
- isSecondLastMessageFromUser,
- scrollToIndex: null,
- spacerActive,
- }),
- {
- initialProps: {
- dataSourceLength: 2,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- },
- },
- );
+ const { rerender } = makeRender(null, {
+ dataSourceLength: 2,
+ isSecondLastMessageFromUser: false,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
- // Should not throw when scrollToIndex is null
expect(() => {
rerender({
dataSourceLength: 4,
isSecondLastMessageFromUser: true,
spacerActive: true,
+ spacerLayoutVersion: 0,
});
}).not.toThrow();
});
@@ -374,10 +490,10 @@ describe('useScrollToUserMessage', () => {
isSecondLastMessageFromUser: true,
scrollToIndex,
spacerActive: true,
+ spacerLayoutVersion: 0,
}),
);
- // Should not scroll on initial render even if second-to-last message is from user
expect(scrollToIndex).not.toHaveBeenCalled();
});
});
diff --git a/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.ts b/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.ts
index 07f5f328fe8..644809ccb80 100644
--- a/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.ts
+++ b/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.ts
@@ -12,6 +12,11 @@ interface UseScrollToUserMessageOptions {
* (When sending a message, user + assistant messages are created as a pair)
*/
isSecondLastMessageFromUser: boolean;
+ /**
+ * User is manually shrinking the spacer (scrolled up). When true, stop pinning
+ * so we don't fight the user's scroll.
+ */
+ scrollShrinking?: boolean;
/**
* Function to scroll to a specific index
*/
@@ -25,6 +30,13 @@ interface UseScrollToUserMessageOptions {
* height is available.
*/
spacerActive: boolean;
+ /**
+ * A counter that increments each time the spacer DOM's real size changes
+ * (observed via ResizeObserver). Used as a layout-settled signal so we can
+ * re-fire scrollToIndex after virtua finishes measuring the spacer and
+ * scrollSize expands enough to let the user message reach the top.
+ */
+ spacerLayoutVersion?: number;
}
/**
@@ -33,17 +45,18 @@ interface UseScrollToUserMessageOptions {
* 2 new messages were added and the second-to-last is from user).
*
* Scrolls immediately on message send (works when content already fills the
- * viewport). If a conversation spacer mounts afterwards (adding fill height),
- * a follow-up scroll is fired so the user message lands correctly.
- *
- * This ensures that in group chat scenarios, when multiple agents are responding,
- * the view doesn't jump around as each agent starts speaking.
+ * viewport). When a conversation spacer mounts afterwards and its DOM is
+ * measured by virtua, scrollSize expands and we re-fire scroll so the user
+ * message lands correctly. The pending state clears when the spacer unmounts
+ * or the user starts scrolling manually.
*/
export function useScrollToUserMessage({
dataSourceLength,
isSecondLastMessageFromUser,
scrollToIndex,
+ scrollShrinking = false,
spacerActive,
+ spacerLayoutVersion = 0,
}: UseScrollToUserMessageOptions): void {
const prevLengthRef = useRef(dataSourceLength);
const timerIdsRef = useRef<number[]>([]);
@@ -91,18 +104,30 @@ export function useScrollToUserMessage({
const userMessageIndex = dataSourceLength - 2;
// Always scroll immediately – works when content already fills the viewport.
- // Also store the index so a follow-up scroll can fire once the spacer mounts.
+ // Also store the index so follow-up scrolls can fire as the spacer settles.
pendingScrollIndexRef.current = userMessageIndex;
executeScroll(userMessageIndex);
}
}, [dataSourceLength, isSecondLastMessageFromUser, scrollToIndex, executeScroll]);
- // Re-scroll when spacer mounts (provides the extra fill height)
+ // Clear pending scroll when the spacer unmounts or user scrolls manually so
+ // subsequent layout ticks don't keep pinning against the user's intent.
+ // Also cancel any already-scheduled retry timers — otherwise a pin wave
+ // fired just before the user scrolled up would still call scrollToIndex at
+ // 32/96ms and yank the viewport back down.
useEffect(() => {
- if (spacerActive && pendingScrollIndexRef.current !== null) {
- const index = pendingScrollIndexRef.current;
+ if (!spacerActive || scrollShrinking) {
pendingScrollIndexRef.current = null;
- executeScroll(index);
+ clearPendingPins();
}
- }, [spacerActive, executeScroll]);
+ }, [spacerActive, scrollShrinking, clearPendingPins]);
+
+ // Re-scroll whenever the spacer's real layout settles (version bumps) or the
+ // spacer becomes active. Skip when user is manually shrinking the spacer.
+ useEffect(() => {
+ if (!spacerActive || scrollShrinking) return;
+ const index = pendingScrollIndexRef.current;
+ if (index === null) return;
+ executeScroll(index);
+ }, [spacerActive, spacerLayoutVersion, scrollShrinking, executeScroll]);
}
diff --git a/src/features/Conversation/Messages/User/components/CollapsibleContent.tsx b/src/features/Conversation/Messages/User/components/CollapsibleContent.tsx
new file mode 100644
index 00000000000..2f5d970402f
--- /dev/null
+++ b/src/features/Conversation/Messages/User/components/CollapsibleContent.tsx
@@ -0,0 +1,147 @@
+'use client';
+
+import { createStaticStyles } from 'antd-style';
+import { ChevronDownIcon, ChevronUpIcon } from 'lucide-react';
+import {
+ memo,
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react';
+import { useTranslation } from 'react-i18next';
+
+const DEFAULT_MAX_HEIGHT = 280;
+const VIEWPORT_RATIO = 0.35;
+// Only collapse when the overflow is meaningful; avoids hiding a button for a
+// handful of extra pixels.
+const OVERFLOW_THRESHOLD = 32;
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ position: relative;
+ width: 100%;
+ `,
+ contentCollapsed: css`
+ overflow: hidden;
+
+ mask-image: linear-gradient(to bottom, #000 calc(100% - 48px), transparent);
+ mask-image: linear-gradient(to bottom, #000 calc(100% - 48px), transparent);
+ `,
+ contentExpanded: css`
+ overflow: visible;
+ `,
+ toggleButton: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ gap: 4px;
+ align-items: center;
+
+ block-size: 24px;
+ padding-inline: 10px;
+ border: none;
+ border-radius: 12px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillQuaternary};
+
+ transition:
+ color 150ms ${cssVar.motionEaseOut},
+ background 150ms ${cssVar.motionEaseOut};
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ toggleWrapper: css`
+ display: flex;
+ justify-content: center;
+ margin-block-start: 6px;
+ `,
+}));
+
+const computeThreshold = () => {
+ if (typeof window === 'undefined') return DEFAULT_MAX_HEIGHT;
+ return Math.min(DEFAULT_MAX_HEIGHT, Math.round(window.innerHeight * VIEWPORT_RATIO));
+};
+
+interface CollapsibleContentProps {
+ children: ReactNode;
+}
+
+/**
+ * Collapses long user message content to a bounded max-height with a gradient
+ * mask and a toggle button. Prevents very long user messages from pushing the
+ * AI response out of the viewport after auto-scroll pins the user message
+ * to the top.
+ */
+const CollapsibleContent = memo<CollapsibleContentProps>(({ children }) => {
+ const { t } = useTranslation('chat');
+ const contentRef = useRef<HTMLDivElement | null>(null);
+
+ const [maxHeight, setMaxHeight] = useState(() => computeThreshold());
+ const [naturalHeight, setNaturalHeight] = useState(0);
+ const [collapsed, setCollapsed] = useState(true);
+
+ // Measure content's natural (unconstrained) height. We read scrollHeight so
+ // the value is unaffected by our own max-height clamp.
+ useLayoutEffect(() => {
+ const el = contentRef.current;
+ if (!el) return;
+
+ const measure = () => {
+ setNaturalHeight(el.scrollHeight);
+ };
+ measure();
+
+ if (typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+
+ useEffect(() => {
+ if (typeof window === 'undefined') return;
+
+ const handleResize = () => setMaxHeight(computeThreshold());
+ window.addEventListener('resize', handleResize);
+ return () => window.removeEventListener('resize', handleResize);
+ }, []);
+
+ const shouldCollapse = naturalHeight > maxHeight + OVERFLOW_THRESHOLD;
+ const isCollapsed = shouldCollapse && collapsed;
+
+ const handleToggle = useCallback(() => {
+ setCollapsed((prev) => !prev);
+ }, []);
+
+ return (
+ <div className={styles.container}>
+ <div
+ className={isCollapsed ? styles.contentCollapsed : styles.contentExpanded}
+ ref={contentRef}
+ style={isCollapsed ? { maxHeight } : undefined}
+ >
+ {children}
+ </div>
+ {shouldCollapse && (
+ <div className={styles.toggleWrapper}>
+ <button className={styles.toggleButton} type="button" onClick={handleToggle}>
+ {collapsed ? <ChevronDownIcon size={14} /> : <ChevronUpIcon size={14} />}
+ {collapsed ? t('messageLongCollapse.expand') : t('messageLongCollapse.collapse')}
+ </button>
+ </div>
+ )}
+ </div>
+ );
+});
+
+CollapsibleContent.displayName = 'CollapsibleContent';
+
+export default CollapsibleContent;
diff --git a/src/features/Conversation/Messages/User/components/MessageContent.tsx b/src/features/Conversation/Messages/User/components/MessageContent.tsx
index a1fb88a5d62..1e12bd98bc7 100644
--- a/src/features/Conversation/Messages/User/components/MessageContent.tsx
+++ b/src/features/Conversation/Messages/User/components/MessageContent.tsx
@@ -6,6 +6,7 @@ import { cleanSpeakerTag } from '@/store/chat/utils/cleanSpeakerTag';
import { type UIChatMessage } from '@/types/index';
import { useMarkdown } from '../useMarkdown';
+import CollapsibleContent from './CollapsibleContent';
import FileListViewer from './FileListViewer';
import ImageFileListViewer from './ImageFileListViewer';
import PageSelections from './PageSelections';
@@ -21,16 +22,18 @@ const UserMessageContent = memo<UIChatMessage>(
const hasEditorData =
editorData && typeof editorData === 'object' && Object.keys(editorData).length > 0;
+ const textBody = hasEditorData ? (
+ <RichTextMessage editorState={editorData} />
+ ) : (
+ displayContent && <MarkdownMessage {...markdownProps}>{displayContent}</MarkdownMessage>
+ );
+
return (
<Flexbox gap={8} id={id}>
{pageSelections && pageSelections.length > 0 && (
<PageSelections selections={pageSelections} />
)}
- {hasEditorData ? (
- <RichTextMessage editorState={editorData} />
- ) : (
- displayContent && <MarkdownMessage {...markdownProps}>{displayContent}</MarkdownMessage>
- )}
+ {textBody && <CollapsibleContent>{textBody}</CollapsibleContent>}
{imageList && imageList?.length > 0 && <ImageFileListViewer items={imageList} />}
{videoList && videoList?.length > 0 && <VideoFileListViewer items={videoList} />}
{fileList && fileList?.length > 0 && <FileListViewer items={fileList} />}
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index a2cd213262e..381efd0b713 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -204,6 +204,8 @@ export default {
'messageAction.expand': 'Expand Message',
'messageAction.reaction': 'Add Reaction',
'messageAction.regenerate': 'Regenerate',
+ 'messageLongCollapse.collapse': 'Show less',
+ 'messageLongCollapse.expand': 'Show more',
'messages.dm.sentTo': 'Visible only to {{name}}',
'messages.dm.title': 'DM',
'messages.modelCard.credit': 'Credits',
diff --git a/vite.config.ts b/vite.config.ts
index 958ed529f37..eb83f70663f 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -1,4 +1,4 @@
-import { execFile } from 'node:child_process';
+import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
@@ -50,7 +50,10 @@ const resolveCommandExecutable = (cmd: string) => {
}
};
-const openExternalBrowser = async (url: string) => {
+const openExternalBrowser = async (
+ url: string,
+ logger?: { warn: (msg: string) => void },
+): Promise<boolean> => {
const command =
process.platform === 'win32'
? {
@@ -62,16 +65,33 @@ const openExternalBrowser = async (url: string) => {
cmd: process.platform === 'darwin' ? 'open' : 'xdg-open',
};
- return new Promise<boolean>((resolve) => {
- const executable = resolveCommandExecutable(command.cmd);
- if (!executable) {
- resolve(false);
- return;
- }
+ const executable = resolveCommandExecutable(command.cmd);
+ if (!executable) {
+ logger?.warn(`openExternalBrowser: ${command.cmd} not found on PATH`);
+ return false;
+ }
+ return new Promise<boolean>((resolve) => {
try {
- execFile(executable, command.args, (error) => resolve(!error));
- } catch {
+ const child = spawn(executable, command.args, {
+ detached: true,
+ stdio: 'ignore',
+ });
+ let settled = false;
+ const done = (ok: boolean, reason?: string) => {
+ if (settled) return;
+ settled = true;
+ if (!ok && reason) logger?.warn(`openExternalBrowser: ${reason}`);
+ resolve(ok);
+ };
+ child.once('error', (err) => done(false, (err as Error).message));
+ child.once('spawn', () => {
+ child.unref();
+ done(true);
+ });
+ setTimeout(() => done(true), 200);
+ } catch (e) {
+ logger?.warn(`openExternalBrowser: ${(e as Error).message}`);
resolve(false);
}
});
@@ -129,7 +149,7 @@ export default defineConfig({
const proxyUrl = getProxyUrl();
if (!proxyUrl) return;
- const opened = await openExternalBrowser(proxyUrl);
+ const opened = await openExternalBrowser(proxyUrl, server.config.logger);
if (!opened) {
server.config.logger.warn(`Failed to open Debug Proxy automatically: ${proxyUrl}`);