feat(webui): anchor prompts while replies stream (#6679)
This commit is contained in:
1 parent
d3bb330f57
commit
92d23d2d2b
9 files changed
+907
-1554
No files matched your search
@@ -483,7 +483,7 @@ export function ThreadShell({
|
||||
dismissed: boolean;
|
||||
} | null>(null);
|
||||
const sandboxNotice = useSandboxNotice(client, chatId, webuiCapabilities.includes("webui.sandbox-settings.v1"));
|
||||
const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState<string | null>(null);
|
||||
const [submittedViewportTurn, setSubmittedViewportTurn] = useState<{ chatId: string; turnId: string } | null>(null);
|
||||
const { state: previewState, openFile, resolveFile, selectTab, closeTab, close: closePreview, setWidth: setFilePreviewWidth } =
|
||||
useFilePreviewState(previewSessionKey, filePreviewStore);
|
||||
const [contextSidebarOpen, setContextSidebarOpen] = useState(false);
|
||||
@@ -568,7 +568,6 @@ export function ThreadShell({
|
||||
const sessionKeyByChatIdRef = useRef<Map<string, string>>(new Map());
|
||||
const handleTurnEnd = useCallback(() => {
|
||||
if (chatId) activeViewportTurnByChatIdRef.current.delete(chatId);
|
||||
setSubmittedViewportTurnId(null);
|
||||
onTurnEnd?.();
|
||||
}, [chatId, onTurnEnd]);
|
||||
const {
|
||||
@@ -652,7 +651,7 @@ export function ThreadShell({
|
||||
filePreviewCloseTimerRef.current = null;
|
||||
}
|
||||
setClosingPreview(null);
|
||||
setSubmittedViewportTurnId(null);
|
||||
setSubmittedViewportTurn(null);
|
||||
}, [previewSessionKey]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -722,15 +721,12 @@ export function ThreadShell({
|
||||
?? historyActiveTurnId
|
||||
?? restoredViewportTurnId
|
||||
: null;
|
||||
const activeTurnStartedHere =
|
||||
viewportTurnId !== null && viewportTurnId === submittedViewportTurnId;
|
||||
const submittedViewportTurnId = submittedViewportTurn?.chatId === chatId
|
||||
? submittedViewportTurn.turnId : null;
|
||||
useEffect(() => {
|
||||
if (!chatId || !messagesReady || turnActive) return;
|
||||
activeViewportTurnByChatIdRef.current.delete(chatId);
|
||||
setSubmittedViewportTurnId((current) =>
|
||||
current === rememberedViewportTurnId ? null : current,
|
||||
);
|
||||
}, [chatId, messagesReady, rememberedViewportTurnId, turnActive]);
|
||||
}, [chatId, messagesReady, turnActive]);
|
||||
const filePreviewAvailabilityCache = useMemo(
|
||||
() => new Map<string, FilePreviewAvailabilityCacheEntry>(),
|
||||
[previewSessionKey],
|
||||
@@ -970,7 +966,7 @@ export function ThreadShell({
|
||||
const submitted = send(pending.content, pending.images, pending.options);
|
||||
if (submitted && !submitted.sideChannel) {
|
||||
activeViewportTurnByChatIdRef.current.set(chatId, submitted.turnId);
|
||||
setSubmittedViewportTurnId(submitted.turnId);
|
||||
setSubmittedViewportTurn({ chatId, turnId: submitted.turnId });
|
||||
}
|
||||
if (submitted?.delivery) {
|
||||
void submitted.delivery.then(() => pending.finish?.(true), (error: unknown) => {
|
||||
@@ -1009,7 +1005,7 @@ export function ThreadShell({
|
||||
);
|
||||
if (submitted && !submitted.sideChannel) {
|
||||
activeViewportTurnByChatIdRef.current.set(chatId, submitted.turnId);
|
||||
setSubmittedViewportTurnId(submitted.turnId);
|
||||
setSubmittedViewportTurn({ chatId, turnId: submitted.turnId });
|
||||
}
|
||||
onPendingFirstMessageConsumed?.(pendingFirstMessage.id);
|
||||
}, [
|
||||
@@ -1084,7 +1080,7 @@ export function ThreadShell({
|
||||
&& options?.continueActiveTurn !== true
|
||||
) {
|
||||
activeViewportTurnByChatIdRef.current.set(chatId, submitted.turnId);
|
||||
setSubmittedViewportTurnId(submitted.turnId);
|
||||
setSubmittedViewportTurn({ chatId, turnId: submitted.turnId });
|
||||
}
|
||||
return submitted?.delivery ? submitted.delivery.then(() => true) : submitted !== null;
|
||||
},
|
||||
@@ -1515,7 +1511,7 @@ export function ThreadShell({
|
||||
composer={inlineComposer ? <div ref={setLocalComposerHost} /> : null}
|
||||
onComposerLayoutChange={alignSidebar}
|
||||
activeTurnId={viewportTurnId}
|
||||
activeTurnStartedHere={activeTurnStartedHere}
|
||||
submittedPromptTurnId={submittedViewportTurnId}
|
||||
conversationKey={historyKey}
|
||||
conversationReady={messagesReady}
|
||||
onVisibleMessagesChange={reportVisibleMessages}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -94,20 +94,6 @@ export class ThreadCameraController {
|
||||
this.write(viewport, this.target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatic follow is a layout constraint, not navigation. Resolve it in
|
||||
* the geometry frame so streamed content and viewport resizing cannot build
|
||||
* up hidden travel below the visible tail.
|
||||
*/
|
||||
followTo(top: number): ThreadCameraFollowResult | null {
|
||||
const viewport = this.getViewport();
|
||||
if (!viewport) return null;
|
||||
this.cancel();
|
||||
this.target = Math.max(0, top);
|
||||
this.write(viewport, this.target);
|
||||
return "settled";
|
||||
}
|
||||
|
||||
navigateTo(top: number): ThreadCameraFollowResult | null {
|
||||
return this.moveTo(top);
|
||||
}
|
||||
|
||||
@@ -7,17 +7,12 @@ type ThreadMotionMode =
|
||||
| "idle"
|
||||
| "follow-latest"
|
||||
| "anchor-prompt"
|
||||
| "follow-output"
|
||||
| "follow-completion"
|
||||
| "reading-prompt"
|
||||
| "navigating-latest"
|
||||
| "navigating-history"
|
||||
| "browsing-history";
|
||||
|
||||
type AutomaticThreadMotionMode =
|
||||
| "idle"
|
||||
| "follow-latest"
|
||||
| "anchor-prompt"
|
||||
| "follow-output";
|
||||
type AutomaticThreadMotionMode = "idle" | "follow-latest";
|
||||
|
||||
type ThreadMotionEvent =
|
||||
| "navigate-latest"
|
||||
@@ -26,7 +21,6 @@ type ThreadMotionEvent =
|
||||
| "user-scroll"
|
||||
| "boundary-scroll"
|
||||
| "composer-input"
|
||||
| "turn-completed"
|
||||
| "resume-follow";
|
||||
|
||||
type ThreadMotionTransition = ThreadMotionMode | "current-automatic-mode";
|
||||
@@ -52,19 +46,14 @@ const THREAD_MOTION_TRANSITIONS: Readonly<
|
||||
"navigate-latest": "navigating-latest",
|
||||
"navigate-history": "navigating-history",
|
||||
"user-scroll": "browsing-history",
|
||||
"turn-completed": "follow-completion",
|
||||
"boundary-scroll": "browsing-history",
|
||||
},
|
||||
"follow-output": {
|
||||
"reading-prompt": {
|
||||
"navigate-latest": "navigating-latest",
|
||||
"navigate-history": "navigating-history",
|
||||
"user-scroll": "browsing-history",
|
||||
"turn-completed": "follow-completion",
|
||||
},
|
||||
"follow-completion": {
|
||||
"navigate-latest": "navigating-latest",
|
||||
"navigate-history": "navigating-history",
|
||||
"user-scroll": "browsing-history",
|
||||
"composer-input": "idle",
|
||||
"boundary-scroll": "browsing-history",
|
||||
"resume-follow": "current-automatic-mode",
|
||||
},
|
||||
"navigating-latest": {
|
||||
"navigate-latest": "navigating-latest",
|
||||
@@ -100,18 +89,8 @@ export interface ThreadMotionGeometry {
|
||||
promptTop: number | null;
|
||||
}
|
||||
|
||||
interface ThreadMotionTurn {
|
||||
id: string | null;
|
||||
promptId: string | null;
|
||||
hasOutput: boolean;
|
||||
entry?: "submitted" | "restored";
|
||||
}
|
||||
|
||||
interface ThreadMotionSnapshot {
|
||||
mode: ThreadMotionMode;
|
||||
turnId: string | null;
|
||||
promptPositioned: boolean;
|
||||
measurementPending: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadMotionScheduler {
|
||||
@@ -123,7 +102,6 @@ type ThreadMotionCamera = Pick<
|
||||
ThreadCameraController,
|
||||
| "cancel"
|
||||
| "dispose"
|
||||
| "followTo"
|
||||
| "isFollowing"
|
||||
| "jumpTo"
|
||||
| "navigateTo"
|
||||
@@ -133,7 +111,7 @@ type ThreadMotionCamera = Pick<
|
||||
|
||||
interface ThreadMotionCoordinatorOptions {
|
||||
camera: ThreadMotionCamera;
|
||||
measure: (promptId: string | null) => ThreadMotionGeometry | null;
|
||||
measure: (promptId: string | null, submitted?: boolean) => ThreadMotionGeometry | null;
|
||||
onGeometry?: (geometry: ThreadMotionGeometry) => void;
|
||||
onAutoFollow?: () => void;
|
||||
onLatestNavigationSettled?: () => void;
|
||||
@@ -164,17 +142,12 @@ export class ThreadMotionCoordinator {
|
||||
private readonly onAutoFollow?: ThreadMotionCoordinatorOptions["onAutoFollow"];
|
||||
private readonly onLatestNavigationSettled?: () => void;
|
||||
private readonly scheduler: ThreadMotionScheduler;
|
||||
private turn: ThreadMotionTurn = {
|
||||
id: null,
|
||||
promptId: null,
|
||||
hasOutput: false,
|
||||
};
|
||||
private turnId: string | null = null;
|
||||
private mode: ThreadMotionMode = "idle";
|
||||
private historyNavigationPromptId: string | null = null;
|
||||
private promptPositioned = false;
|
||||
private submittedPromptId: string | null = null;
|
||||
private measurementFrameId: number | null = null;
|
||||
private geometryDirty = false;
|
||||
private composerInputDuringTurn = false;
|
||||
// Only input toward latest may resume follow; layout can also return a
|
||||
// reading position to the tail without the user scrolling forward.
|
||||
private resumeFollowArmed = false;
|
||||
@@ -189,55 +162,44 @@ export class ThreadMotionCoordinator {
|
||||
}
|
||||
|
||||
snapshot(): ThreadMotionSnapshot {
|
||||
return {
|
||||
mode: this.mode,
|
||||
turnId: this.turn.id,
|
||||
promptPositioned: this.promptPositioned,
|
||||
measurementPending: this.measurementFrameId !== null,
|
||||
};
|
||||
return { mode: this.mode };
|
||||
}
|
||||
|
||||
updateTurn(turn: ThreadMotionTurn): void {
|
||||
if (!turn.id) {
|
||||
this.completeTurn();
|
||||
return;
|
||||
}
|
||||
|
||||
const isNewTurn = this.turn.id !== turn.id;
|
||||
this.turn = turn;
|
||||
if (isNewTurn) {
|
||||
this.camera.reset();
|
||||
this.composerInputDuringTurn = false;
|
||||
this.resumeFollowArmed = false;
|
||||
this.promptPositioned = turn.entry === "restored";
|
||||
this.mode = this.promptPositioned && turn.hasOutput
|
||||
? "follow-output"
|
||||
: "anchor-prompt";
|
||||
} else if (!this.isHistoryMode() && this.promptPositioned) {
|
||||
this.mode = turn.hasOutput ? "follow-output" : "anchor-prompt";
|
||||
updateTurn(turnId: string | null): void {
|
||||
if (this.turnId === turnId) return;
|
||||
this.turnId = turnId;
|
||||
// Opening a running conversation still positions its initial history once,
|
||||
// but subsequent output must not keep pulling the reader to the tail.
|
||||
if (turnId && this.mode === "follow-latest") {
|
||||
this.camera.cancel();
|
||||
this.mode = "idle";
|
||||
}
|
||||
this.invalidateGeometry();
|
||||
}
|
||||
|
||||
completeTurn(): void {
|
||||
if (!this.turn.id) {
|
||||
this.invalidateGeometry();
|
||||
return;
|
||||
}
|
||||
// Protocol completion can share a React commit with the last large text
|
||||
// batch and begins the run-drawer exit. Keep camera ownership through
|
||||
// those final layout changes; only a new turn, explicit user navigation,
|
||||
// or input for the next prompt may end completion follow.
|
||||
this.transition("turn-completed");
|
||||
if (
|
||||
this.composerInputDuringTurn
|
||||
&& this.transition("composer-input")
|
||||
) {
|
||||
this.camera.cancel();
|
||||
}
|
||||
this.turn = { id: null, promptId: null, hasOutput: false };
|
||||
this.composerInputDuringTurn = false;
|
||||
this.promptPositioned = false;
|
||||
followOpeningLayout(): void {
|
||||
if (this.mode !== "idle") return;
|
||||
this.mode = "follow-latest";
|
||||
this.invalidateGeometry();
|
||||
}
|
||||
|
||||
finishOpeningLayout(): void {
|
||||
if (this.mode !== "follow-latest") return;
|
||||
this.camera.cancel();
|
||||
this.mode = "idle";
|
||||
}
|
||||
|
||||
anchorSubmittedPrompt(promptId: string): void {
|
||||
this.camera.reset();
|
||||
this.resumeFollowArmed = false;
|
||||
this.submittedPromptId = promptId;
|
||||
this.mode = "anchor-prompt";
|
||||
this.invalidateGeometry();
|
||||
}
|
||||
|
||||
updateSubmittedPromptId(promptId: string): void {
|
||||
if (!this.isPromptMode() || this.submittedPromptId === promptId) return;
|
||||
this.submittedPromptId = promptId;
|
||||
this.invalidateGeometry();
|
||||
}
|
||||
|
||||
@@ -257,10 +219,6 @@ export class ThreadMotionCoordinator {
|
||||
}
|
||||
|
||||
handleComposerInput(): void {
|
||||
// Input and protocol completion can arrive in either order. Remember
|
||||
// editing that starts just before turn_end so the completion drawer
|
||||
// cannot reacquire the camera a few milliseconds later.
|
||||
if (this.turn.id) this.composerInputDuringTurn = true;
|
||||
if (!this.transition("composer-input")) return;
|
||||
this.camera.cancel();
|
||||
}
|
||||
@@ -331,7 +289,9 @@ export class ThreadMotionCoordinator {
|
||||
}
|
||||
|
||||
cameraSettled(): void {
|
||||
if (this.mode === "navigating-latest") {
|
||||
if (this.mode === "anchor-prompt") {
|
||||
this.finishPromptAnchor();
|
||||
} else if (this.mode === "navigating-latest") {
|
||||
this.settleLatestNavigation();
|
||||
this.onLatestNavigationSettled?.();
|
||||
}
|
||||
@@ -393,12 +353,11 @@ export class ThreadMotionCoordinator {
|
||||
}
|
||||
this.geometryDirty = false;
|
||||
this.camera.reset();
|
||||
this.turn = { id: null, promptId: null, hasOutput: false };
|
||||
this.composerInputDuringTurn = false;
|
||||
this.turnId = null;
|
||||
this.resumeFollowArmed = false;
|
||||
this.mode = "idle";
|
||||
this.historyNavigationPromptId = null;
|
||||
this.promptPositioned = false;
|
||||
this.submittedPromptId = null;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
@@ -415,10 +374,7 @@ export class ThreadMotionCoordinator {
|
||||
}
|
||||
|
||||
private automaticMode(): AutomaticThreadMotionMode {
|
||||
if (!this.turn.id) return "follow-latest";
|
||||
return this.promptPositioned && this.turn.hasOutput
|
||||
? "follow-output"
|
||||
: "anchor-prompt";
|
||||
return this.turnId ? "idle" : "follow-latest";
|
||||
}
|
||||
|
||||
private transition(event: ThreadMotionEvent): boolean {
|
||||
@@ -434,22 +390,19 @@ export class ThreadMotionCoordinator {
|
||||
return true;
|
||||
}
|
||||
|
||||
private followGeometry(geometry: ThreadMotionGeometry): void {
|
||||
const target = geometry.maxScrollTop;
|
||||
const result = this.camera.followTo(target);
|
||||
if (
|
||||
result
|
||||
&& Math.abs(target - geometry.scrollTop) > GEOMETRY_EPSILON_PX
|
||||
) {
|
||||
this.onAutoFollow?.();
|
||||
}
|
||||
}
|
||||
|
||||
private settleLatestNavigation(): void {
|
||||
if (!this.transition("navigation-settled")) return;
|
||||
this.invalidateGeometry();
|
||||
}
|
||||
|
||||
private isPromptMode(): boolean {
|
||||
return this.mode === "anchor-prompt" || this.mode === "reading-prompt";
|
||||
}
|
||||
|
||||
private finishPromptAnchor(): void {
|
||||
this.mode = "reading-prompt";
|
||||
}
|
||||
|
||||
private readonly flushGeometry = (): void => {
|
||||
this.measurementFrameId = null;
|
||||
if (!this.geometryDirty) return;
|
||||
@@ -458,10 +411,8 @@ export class ThreadMotionCoordinator {
|
||||
const navigationPromptId = this.mode === "navigating-history"
|
||||
? this.historyNavigationPromptId
|
||||
: null;
|
||||
const needsPromptGeometry =
|
||||
navigationPromptId !== null
|
||||
|| (!this.isHistoryMode() && this.turn.id !== null && !this.promptPositioned);
|
||||
const geometry = this.measure(navigationPromptId ?? (needsPromptGeometry ? this.turn.promptId : null));
|
||||
const promptId = navigationPromptId ?? (this.isPromptMode() ? this.submittedPromptId : null);
|
||||
const geometry = this.measure(promptId, this.isPromptMode());
|
||||
if (!geometry) return;
|
||||
this.observeUserScroll();
|
||||
this.onGeometry?.(geometry);
|
||||
@@ -480,53 +431,22 @@ export class ThreadMotionCoordinator {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.mode === "follow-completion") {
|
||||
this.followGeometry(geometry);
|
||||
return;
|
||||
}
|
||||
if (this.mode === "follow-latest") {
|
||||
if (geometry.maxScrollTop - geometry.scrollTop > GEOMETRY_EPSILON_PX) {
|
||||
this.camera.jumpTo(geometry.maxScrollTop);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.isHistoryMode() || !this.turn.id) return;
|
||||
if (!this.turn.promptId && this.turn.entry !== "restored") {
|
||||
this.mode = "anchor-prompt";
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.promptPositioned) {
|
||||
if (geometry.promptTop === null) {
|
||||
this.mode = "anchor-prompt";
|
||||
return;
|
||||
if (geometry.promptTop !== null) {
|
||||
if (this.mode === "anchor-prompt") {
|
||||
const result = this.camera.navigateTo(geometry.promptTop);
|
||||
if (!result || result === "settled") this.finishPromptAnchor();
|
||||
} else if (this.mode === "reading-prompt"
|
||||
&& Math.abs(geometry.promptTop - geometry.scrollTop) > GEOMETRY_EPSILON_PX) {
|
||||
// Preserve the prompt's screen position through reflow above it, not the
|
||||
// old scrollTop. Output growing below the prompt leaves this unchanged.
|
||||
this.camera.jumpTo(geometry.promptTop);
|
||||
}
|
||||
// Before output exists, the real lower scroll boundary is the only
|
||||
// position with zero hidden downward travel. Once output exists, first
|
||||
// establish the prompt origin; automatic follow below then resolves the
|
||||
// current tail in this same authoritative geometry frame.
|
||||
this.camera.jumpTo(
|
||||
this.turn.hasOutput ? geometry.promptTop : geometry.maxScrollTop,
|
||||
);
|
||||
this.promptPositioned = true;
|
||||
} else if (
|
||||
!this.turn.hasOutput
|
||||
&& Math.abs(geometry.maxScrollTop - geometry.scrollTop)
|
||||
> GEOMETRY_EPSILON_PX
|
||||
) {
|
||||
// Hero docking, the run drawer, fonts, and responsive chrome can all
|
||||
// change document height while the model is still silent. Every
|
||||
// authoritative geometry frame reasserts the real lower boundary so no
|
||||
// stale downward scroll pocket survives a layout transition.
|
||||
this.camera.jumpTo(geometry.maxScrollTop);
|
||||
}
|
||||
|
||||
if (!this.turn.hasOutput) {
|
||||
this.mode = "anchor-prompt";
|
||||
return;
|
||||
}
|
||||
|
||||
this.mode = "follow-output";
|
||||
this.followGeometry(geometry);
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user