feat(webui): anchor prompts while replies stream (#6679)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-16 17:58:49 +08:00
1 parent d3bb330f57
commit 92d23d2d2b
9 files changed
+907 -1554

No files matched your search

+101 -56
View File
@@ -55,7 +55,7 @@ interface ThreadViewportProps {
onRetryInitial?: () => void;
scrollToBottomSignal?: number;
activeTurnId?: string | null;
activeTurnStartedHere?: boolean;
submittedPromptTurnId?: string | null;
conversationKey?: string | null;
/** Override when message ownership changes after the selected conversation. */
messagesKey?: string | null;
@@ -117,6 +117,18 @@ function promptTopInset(scroller: HTMLElement): number {
return Number.isFinite(padding) ? padding : PROMPT_TOP_INSET_PX;
}
function submittedPromptInset(scroller: HTMLElement, prompt: HTMLElement): number {
const inset = promptTopInset(scroller);
const previous = prompt.previousElementSibling;
let previousUnit = previous;
while (previousUnit && !previousUnit.hasAttribute("data-thread-display-unit")) {
previousUnit = previousUnit.previousElementSibling;
}
if (!previous || !previousUnit) return inset;
const gap = prompt.getBoundingClientRect().top - previous.getBoundingClientRect().bottom;
return Math.max(0, Math.min(inset, gap));
}
function historyPrefetchDistance(scroller: HTMLElement): number {
return Math.min(
HISTORY_PREFETCH_MAX_PX,
@@ -284,7 +296,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
onRetryInitial,
scrollToBottomSignal = 0,
activeTurnId: liveTurnId = null,
activeTurnStartedHere = false,
submittedPromptTurnId = null,
conversationKey = null,
messagesKey = conversationKey,
conversationReady = true,
@@ -328,7 +340,12 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
composerLayoutChangeRef.current = onComposerLayoutChange;
const bottomRef = useRef<HTMLDivElement>(null);
const endGapRef = useRef<HTMLDivElement>(null);
const lastConversationKeyRef = useRef<string | null>(conversationKey);
const anchoredTurnIdRef = useRef<string | null>(null);
const anchoredPromptIdRef = useRef<string | null>(null);
const openingMessagesRef = useRef<UIMessage[] | null>(null);
const finishOpeningAfterLayoutRef = useRef(false);
const conversationIdentity = conversationKey ?? messagesKey;
const lastConversationKeyRef = useRef<string | null>(conversationIdentity);
const conversationHandoffPendingRef = useRef(false);
const conversationHandoffAnimationRef = useRef<Animation | null>(null);
const pendingConversationScrollRef = useRef(true);
@@ -420,14 +437,32 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
});
threadMotionRef.current = new ThreadMotionCoordinator({
camera,
measure: (promptId) => {
measure: (promptId, submitted = false) => {
const scrollEl = scrollRef.current;
const composerDock = composerDockRef.current;
if (!scrollEl) return null;
const composerHeight = composerDock
? composerDock.getBoundingClientRect().height || composerDock.offsetHeight
: 0;
const anchor = anchoredPromptIdRef.current
? findPromptElement(scrollEl, anchoredPromptIdRef.current) : null;
const content = messageContentRef.current;
if (content) {
// Reserve space in the content itself so layout maintains the minimum
// height even when a waiting indicator is replaced by a shorter reply.
if (anchor) {
const anchorOffset = anchor.getBoundingClientRect().top - content.getBoundingClientRect().top;
const fadeGap = endGapRef.current?.getBoundingClientRect().height ?? 0;
const height = Math.ceil(Math.max(0, anchorOffset + scrollEl.clientHeight - submittedPromptInset(scrollEl, anchor) - fadeGap - 1));
content.style.minHeight = `${height}px`;
} else {
content.style.removeProperty("min-height");
}
}
const prompt = promptId ? findPromptElement(scrollEl, promptId) : null;
const targetTop = prompt
? promptTop(scrollEl, prompt) - (submitted ? submittedPromptInset(scrollEl, prompt) : promptTopInset(scrollEl))
: null;
const scrollHeight = scrollEl.scrollHeight;
const clientHeight = scrollEl.clientHeight;
const maxScrollTop = Math.max(0, scrollHeight - clientHeight);
@@ -437,11 +472,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
clientHeight,
maxScrollTop,
composerHeight,
promptTop: prompt
? Math.min(
maxScrollTop,
Math.max(0, promptTop(scrollEl, prompt) - promptTopInset(scrollEl)),
)
promptTop: targetTop !== null
? Math.min(maxScrollTop, Math.max(0, submitted ? Math.ceil(targetTop) : targetTop))
: null,
};
},
@@ -450,6 +482,16 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
updateContentVisibility();
},
onGeometry: (geometry: ThreadMotionGeometry) => {
const frameHeight = viewportFrameRef.current?.clientHeight ?? 0;
if (finishOpeningAfterLayoutRef.current && geometry.clientHeight > 0
&& frameHeight > 0 && geometry.clientHeight <= frameHeight) {
finishOpeningAfterLayoutRef.current = false;
const motion = threadMotionRef.current;
if (motion?.snapshot().mode === "follow-latest") {
motion.jumpTo(geometry.maxScrollTop);
motion.finishOpeningLayout();
}
}
composerLayoutChangeRef.current?.();
if (Math.abs(composerDockHeightRef.current - geometry.composerHeight) >= 1) {
composerDockHeightRef.current = geometry.composerHeight;
@@ -722,8 +764,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
}, [navigation?.target]);
useEffect(() => {
if (activeTurnStartedHere && liveTurnId) navigation?.latest();
}, [activeTurnStartedHere, liveTurnId, navigation?.latest]);
if (submittedPromptTurnId) navigation?.latest();
}, [submittedPromptTurnId, navigation?.latest]);
const cancelAutoScroll = useCallback(() => {
threadMotionRef.current?.takeUserControl();
@@ -752,11 +794,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
setKeyboardInsetBottom((current) =>
Math.abs(current - next) < 1 ? current : next,
);
if (composerFocused) {
// Focusing the composer establishes a new reference frame at the
// latest message. This is one immediate positioning command; viewport
// events may issue a fresh command, but no command survives into a
// later render as a train of retry frames.
if (composerFocused && !isStreaming && !anchoredTurnIdRef.current) {
scrollToBottom(false, { force: true });
}
};
@@ -774,7 +812,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
document.removeEventListener("focusin", updateKeyboardInset);
document.removeEventListener("focusout", updateKeyboardInset);
};
}, [hasMessages, scrollToBottom]);
}, [hasMessages, isStreaming, scrollToBottom]);
useEffect(() => {
if (scrollToBottomSignal <= 0) return;
@@ -782,8 +820,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
}, [scrollToBottomSignal, scrollToBottom]);
useLayoutEffect(() => {
if (lastConversationKeyRef.current === conversationKey) return;
lastConversationKeyRef.current = conversationKey;
if (lastConversationKeyRef.current === conversationIdentity) return;
lastConversationKeyRef.current = conversationIdentity;
clearHistoryTouchTarget();
historyTouchRef.current = null;
historyInputRef.current = "other";
@@ -794,6 +832,11 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
pendingConversationScrollRef.current = true;
historyScrollAnchorRef.current = null;
restoreScrollAfterPrependRef.current = null;
anchoredTurnIdRef.current = null;
anchoredPromptIdRef.current = null;
openingMessagesRef.current = null;
finishOpeningAfterLayoutRef.current = false;
messageContentRef.current?.style.removeProperty("min-height");
threadMotionRef.current?.reset();
setNavigatingToBottom(false);
setShowHistoryExhausted(false);
@@ -811,50 +854,42 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
fill: "forwards",
},
);
}, [clearHistoryTouchTarget, conversationKey, hasMessages, resetHistoryHeader]);
}, [clearHistoryTouchTarget, conversationIdentity, hasMessages, resetHistoryHeader]);
useLayoutEffect(() => {
if (!conversationReady) {
threadMotionRef.current?.reset();
return;
}
if (!activeTurnId) {
threadMotionRef.current?.completeTurn();
return;
if (openingMessagesRef.current && openingMessagesRef.current !== messages) {
openingMessagesRef.current = null;
const frameHeight = viewportFrameRef.current?.clientHeight ?? 0;
const scrollHeight = scrollRef.current?.clientHeight ?? 0;
// The grid can briefly size the scrollport to the full transcript while
// transitioning from the welcome layout. Wait for usable geometry before
// ending the initial tail placement, even if a new message arrives first.
if (frameHeight > 0 && scrollHeight > frameHeight) {
finishOpeningAfterLayoutRef.current = true;
} else {
threadMotionRef.current?.finishOpeningLayout();
}
}
const promptIndex = messages.findIndex(
(message) => message.role === "user" && message.turnId === activeTurnId,
);
if (
activeTurnStartedHere
&& promptIndex >= 0
&& threadMotionRef.current?.snapshot().turnId !== activeTurnId
) {
// A turn submitted in this mounted viewport establishes a new prompt
// origin. A restored turn must first complete open-at-bottom instead.
threadMotionRef.current?.updateTurn(activeTurnId);
const turnId = submittedPromptTurnId ?? anchoredTurnIdRef.current;
const prompt = messages.find((message) => message.role === "user" && message.turnId === turnId);
anchoredPromptIdRef.current = prompt?.id ?? null;
if (submittedPromptTurnId && prompt && anchoredTurnIdRef.current !== submittedPromptTurnId) {
anchoredTurnIdRef.current = submittedPromptTurnId;
historyScrollAnchorRef.current = null;
restoreScrollAfterPrependRef.current = null;
pendingConversationScrollRef.current = false;
finishOpeningAfterLayoutRef.current = false;
resetHistoryHeader();
threadMotionRef.current?.anchorSubmittedPrompt(prompt.id);
} else if (prompt && anchoredTurnIdRef.current === turnId) {
threadMotionRef.current?.updateSubmittedPromptId(prompt.id);
}
const prompt = promptIndex >= 0 ? messages[promptIndex] : null;
const hasOutput = promptIndex >= 0
? messages
.slice(promptIndex + 1)
.some(
(message) =>
message.role !== "user"
&& (!message.turnId || message.turnId === activeTurnId),
)
: !activeTurnStartedHere && messages.some(
(message) =>
message.role !== "user" && message.turnId === activeTurnId,
);
threadMotionRef.current?.updateTurn({
id: activeTurnId,
promptId: prompt?.id ?? null,
hasOutput,
entry: activeTurnStartedHere ? "submitted" : "restored",
});
}, [activeTurnId, activeTurnStartedHere, conversationReady, messages]);
}, [activeTurnId, conversationReady, messages, resetHistoryHeader, submittedPromptTurnId]);
useLayoutEffect(() => {
const wasLoading = previousLoadingOlderRef.current;
@@ -906,12 +941,20 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
scrollToBottom(false, { force: true });
if (!hasMessages) return;
pendingConversationScrollRef.current = false;
if (activeTurnId && !submittedPromptTurnId) {
// Let the opened transcript's lazy layout settle at the tail, but stop
// as soon as a new message arrives or the reader takes control.
openingMessagesRef.current = messages;
threadMotionRef.current?.followOpeningLayout();
}
}, [
activeTurnId,
conversationKey,
conversationReady,
hasMessages,
messages,
scrollToBottom,
submittedPromptTurnId,
]);
useLayoutEffect(() => {
@@ -988,6 +1031,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
if (content) observer?.observe(content);
if (contentRegion) observer?.observe(contentRegion);
if (messageContent) observer?.observe(messageContent);
// The reserved min-height can hide reflow inside a short transcript.
if (messageContent?.firstElementChild) observer?.observe(messageContent.firstElementChild);
if (endGapRef.current) observer?.observe(endGapRef.current);
if (composerDock) observer?.observe(composerDock);
window.addEventListener("resize", invalidateGeometry);
@@ -995,7 +1040,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
observer?.disconnect();
window.removeEventListener("resize", invalidateGeometry);
};
}, [hasMessages, reconcileHistoryScrollAnchor, refreshLastMessageRow, updateContentVisibility]);
}, [hasMessages, messagesKey, reconcileHistoryScrollAnchor, refreshLastMessageRow, updateContentVisibility]);
useEffect(() => {
const el = scrollRef.current;
@@ -1293,7 +1338,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
hasVerticalOverflow ? "overflow-y-auto" : "overflow-hidden",
)}
>
<div ref={messageContentRef} className="w-full">
<div ref={messageContentRef} className="w-full shrink-0">
<DiffViewportContext.Provider value={diffViewport}>
<DiagramScope identity={conversationKey}>
<SubagentThreadMessages