diff --git a/webui/browser/answer-order-fixture.tsx b/webui/browser/answer-order-fixture.tsx index 8da973ad3..c2d0744b9 100644 --- a/webui/browser/answer-order-fixture.tsx +++ b/webui/browser/answer-order-fixture.tsx @@ -16,6 +16,16 @@ export function AnswerOrderFixture() { const [revision, setRevision] = useState(0); const [, setCompletedRevision] = useState(0); const onTurnEnd = useCallback(() => setCompletedRevision(revision), [revision]); + const fixtureSettings = new URLSearchParams(location.search).get("sendable") === "1" ? { + ...settings, + agent: { ...settings.agent, model_preset: "default" }, + model_presets: [{ + name: "default", label: "Default", active: true, is_default: true, + model: "gpt-5.4", provider: "openai", resolved_provider: "openai", + max_tokens: 8192, context_window_tokens: 200_000, temperature: 0.1, reasoning_effort: null, + }], + model_call_order: ["default"], + } : settings; useEffect(() => { client.connect(); return () => client.close(); @@ -29,7 +39,7 @@ export function AnswerOrderFixture() { {}} onTurnEnd={onTurnEnd} - settingsSnapshot={settings} messageCache={cache} + settingsSnapshot={fixtureSettings} messageCache={cache} /> ; diff --git a/webui/browser/thread-prompt-anchor.spec.ts b/webui/browser/thread-prompt-anchor.spec.ts new file mode 100644 index 000000000..d67e1f082 --- /dev/null +++ b/webui/browser/thread-prompt-anchor.spec.ts @@ -0,0 +1,242 @@ +import { expect, test, type Page, type WebSocketRoute } from "@playwright/test"; +import type { InboundEvent, ThreadProjectionEvent } from "../src/lib/types"; + +const chatId = "answer-order"; + +async function openThread( + page: Page, + withHistory: boolean, + immediateReply = false, + options: { shortHistory?: boolean; beforeSend?: () => Promise } = {}, +) { + const errors: string[] = []; + page.on("pageerror", (error) => errors.push(error.message)); + await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en")); + await page.route("**/api/**", (route) => route.fulfill({ status: 404, json: {} })); + await page.route("**/api/commands", (route) => route.fulfill({ json: { commands: [] } })); + const events: ThreadProjectionEvent[] = withHistory ? Array.from({ length: options.shortHistory ? 1 : 12 }, (_, index) => [ + { event: "user_message" as const, chat_id: chatId, turn_id: `old-${index}`, turn_seq: 1, text: `Earlier question ${index}`, starts_turn: true }, + { event: "message" as const, chat_id: chatId, turn_id: `old-${index}`, turn_seq: 2, text: (immediateReply ? `## Earlier answer ${index}\n\nFirst paragraph.\n\nSecond paragraph.\n\n` : `Earlier answer ${index}. `).repeat(options.shortHistory ? 1 : 8) }, + { event: "turn_end" as const, chat_id: chatId, turn_id: `old-${index}`, turn_seq: 3 }, + ]).flat() : []; + await page.route("**/api/sessions/*/webui-thread?*", (route) => { + const path = decodeURIComponent(new URL(route.request().url()).pathname); + return route.fulfill({ json: { + schemaVersion: 3, projection: "events", events: path.includes(`/sessions/websocket:${chatId}/`) ? events : [], + has_more: false, has_pending_tool_calls: false, + } }); + }); + let socket!: WebSocketRoute; + let attached = false; + const sent: Array<{ type: string; turn_id?: string }> = []; + await page.routeWebSocket("**/answer-order-socket", (route) => { + socket = route; + route.onMessage((raw) => { + const frame = JSON.parse(String(raw)) as { type: string; chat_id: string; turn_id?: string }; + if (frame.type === "attach") { + attached = true; + route.send(JSON.stringify({ event: "attached", chat_id: frame.chat_id })); + } else if (frame.type === "message") { + sent.push(frame); + if (immediateReply) { + const base = { chat_id: chatId, turn_id: frame.turn_id, stream_id: "fast" }; + route.send(JSON.stringify({ event: "delta", ...base, turn_seq: 1, text: "Immediate answer" })); + route.send(JSON.stringify({ event: "stream_end", ...base, turn_seq: 2 })); + route.send(JSON.stringify({ event: "turn_end", chat_id: chatId, turn_id: frame.turn_id, turn_seq: 3 })); + } + } + }); + }); + await page.goto("/browser/fixture.html?case=answer-order&sendable=1"); + await expect.poll(() => attached).toBe(true); + await expect(page.getByRole("status", { name: "Loading conversation…" })).toHaveCount(0); + const input = page.getByRole("textbox", { name: "Message input", exact: true }); + await input.fill("My anchored question"); + await options.beforeSend?.(); + await input.press("Enter"); + await expect.poll(() => sent.find((frame) => frame.turn_id)?.turn_id).toBeTruthy(); + const turnId = sent.find((frame) => frame.turn_id)!.turn_id!; + return { + errors, + turnId, + emit: (...frames: InboundEvent[]) => frames.forEach((frame) => socket.send(JSON.stringify(frame))), + }; +} + +test("moves the previous answer out of view smoothly when sending", async ({ page }) => { + await page.clock.install({ time: new Date("2026-01-01T00:00:00Z") }); + await page.setViewportSize({ width: 1440, height: 800 }); + await openThread(page, true, false, { + shortHistory: true, + beforeSend: async () => { + // Control animation time rather than requiring a minimum CI runner frame rate. + await page.clock.pauseAt(new Date("2026-01-01T00:01:00Z")); + await page.evaluate(() => { + const samples: number[] = []; + Object.assign(window, { __promptMotion: { samples } }); + document.querySelector("textarea")!.addEventListener("keydown", (event) => { + if (event.key !== "Enter") return; + const started = performance.now(); + const sample = () => { + const viewport = document.querySelector('[data-testid="thread-message-region"]'); + if (viewport) samples.push(viewport.scrollTop); + if (performance.now() - started < 400) requestAnimationFrame(sample); + }; + sample(); + }, { once: true }); + }); + }, + }); + await page.clock.runFor(400); + const positions = await page.evaluate(() => (window as unknown as { __promptMotion: { samples: number[] } }).__promptMotion.samples); + const distinctPositions = new Set(positions.map((position) => Math.round(position))); + expect(distinctPositions.size).toBeGreaterThan(3); + const viewport = page.getByTestId("thread-message-region"); + const prompt = viewport.locator("[data-user-prompt-id]").filter({ hasText: "My anchored question" }); + const geometry = await prompt.evaluate((node) => { + const viewport = node.closest('[data-testid="thread-message-region"]')!; + const previous = node.previousElementSibling!; + return { + previousBottom: previous.getBoundingClientRect().bottom - viewport.getBoundingClientRect().top, + promptTop: node.getBoundingClientRect().top - viewport.getBoundingClientRect().top, + }; + }); + expect(geometry.previousBottom).toBeLessThanOrEqual(0); + expect(geometry.promptTop).toBeGreaterThanOrEqual(0); + expect(geometry.promptTop).toBeLessThanOrEqual(48); +}); + +test("anchors the prompt with reduced motion enabled", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 800 }); + await page.emulateMedia({ reducedMotion: "reduce" }); + const { errors } = await openThread(page, true, false, { shortHistory: true }); + const viewport = page.getByTestId("thread-message-region"); + const prompt = viewport.locator("[data-user-prompt-id]").filter({ hasText: "My anchored question" }); + await expect.poll(() => prompt.evaluate((node) => { + const region = node.closest('[data-testid="thread-message-region"]')!; + return node.previousElementSibling!.getBoundingClientRect().bottom - region.getBoundingClientRect().top; + })).toBeLessThanOrEqual(0); + expect(errors).toEqual([]); +}); + +for (const width of [390, 1440]) for (const withHistory of [false, true]) { + test(`anchors a submitted prompt without following streamed text at ${width}px, history=${withHistory}`, async ({ page }) => { + await page.setViewportSize({ width, height: 800 }); + const { emit, errors, turnId } = await openThread(page, withHistory); + const viewport = page.getByTestId("thread-message-region"); + const prompt = viewport.locator("[data-user-prompt-id]").filter({ hasText: "My anchored question" }); + await expect(prompt).toHaveCount(1); + const promptOffset = () => prompt.evaluate((node) => { + const viewport = node.closest('[data-testid="thread-message-region"]')!; + return node.getBoundingClientRect().top - viewport.getBoundingClientRect().top; + }); + if (withHistory) { + await expect.poll(() => prompt.evaluate((node) => { + const viewport = node.closest('[data-testid="thread-message-region"]')!; + return node.previousElementSibling!.getBoundingClientRect().bottom - viewport.getBoundingClientRect().top; + })).toBeLessThanOrEqual(0); + } else { + await expect.poll(promptOffset).toBeCloseTo(48, 0); + } + if (width === 1440 && withHistory) { + const beforeResize = await viewport.evaluate((node) => node.scrollTop); + await page.setViewportSize({ width: 390, height: 800 }); + await expect.poll(promptOffset).toBeLessThanOrEqual(48); + expect(await promptOffset()).toBeGreaterThanOrEqual(0); + expect(await viewport.evaluate((node) => node.scrollTop)).toBeGreaterThan(beforeResize); + } + const initialOffset = await promptOffset(); + const initialTop = await viewport.evaluate((node) => node.scrollTop); + const base = { chat_id: chatId, turn_id: turnId, stream_id: "answer" }; + emit({ event: "delta", ...base, turn_seq: 1, text: "The short opening." }); + await expect(page.getByText("The short opening.", { exact: true })).toBeVisible(); + await expect.poll(promptOffset).toBeCloseTo(initialOffset, 0); + expect(await viewport.evaluate((node) => node.scrollTop)).toBeCloseTo(initialTop, 0); + + emit({ event: "delta", ...base, turn_seq: 2, text: `\n\n${"Long streamed answer line.\n\n".repeat(90)}END-FIRST-BATCH` }); + await expect(viewport).toContainText("END-FIRST-BATCH"); + expect(await viewport.evaluate((node) => node.scrollTop)).toBeCloseTo(initialTop, 0); + await expect.poll(promptOffset).toBeCloseTo(initialOffset, 0); + + await viewport.hover(); + await page.mouse.wheel(0, 360); + await expect.poll(() => viewport.evaluate((node) => node.scrollTop)).toBeGreaterThan(initialTop + 100); + const readingTop = await viewport.evaluate((node) => node.scrollTop); + emit({ event: "delta", ...base, turn_seq: 3, text: `\n\n${"More streamed text.\n\n".repeat(30)}END-SECOND-BATCH` }); + await expect(viewport).toContainText("END-SECOND-BATCH"); + expect(await viewport.evaluate((node) => node.scrollTop)).toBeCloseTo(readingTop, 0); + + await page.getByRole("button", { name: "Scroll to bottom" }).click(); + await expect.poll(() => viewport.evaluate((node) => node.scrollHeight - node.clientHeight - node.scrollTop)) + .toBeLessThanOrEqual(0.5); + const bottomTop = await viewport.evaluate((node) => node.scrollTop); + emit({ event: "delta", ...base, turn_seq: 4, text: `\n\n${"New text after navigation.\n\n".repeat(20)}END-THIRD-BATCH` }); + await expect(viewport).toContainText("END-THIRD-BATCH"); + expect(await viewport.evaluate((node) => node.scrollTop)).toBeCloseTo(bottomTop, 0); + emit({ event: "stream_end", ...base, turn_seq: 5 }); + emit({ event: "turn_end", chat_id: chatId, turn_id: turnId, turn_seq: 6 }); + await expect(page.getByRole("button", { name: "Stop response" })).toHaveCount(0); + expect(await viewport.evaluate((node) => node.scrollTop)).toBeCloseTo(bottomTop, 0); + expect(errors).toEqual([]); + }); +} + +test("keeps the prompt anchored through immediate completion and lazy history layout", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 800 }); + let releaseMarkdown!: () => void; + const markdownReady = new Promise((resolve) => { releaseMarkdown = resolve; }); + await page.route("**/src/components/MarkdownTextRenderer.tsx*", async (route) => { + await markdownReady; + await route.continue(); + }); + const { errors } = await openThread(page, true, true, { + shortHistory: true, + beforeSend: () => page.locator("[data-assistant-message]").click(), + }); + const viewport = page.getByTestId("thread-message-region"); + const prompt = viewport.locator("[data-user-prompt-id]").filter({ hasText: "My anchored question" }); + await expect(viewport).toContainText("Immediate answer"); + await expect(page.getByRole("button", { name: "Stop response" })).toHaveCount(0); + const precedingBottom = () => prompt.evaluate((node) => { + const viewport = node.closest('[data-testid="thread-message-region"]')!; + return node.previousElementSibling!.getBoundingClientRect().bottom - viewport.getBoundingClientRect().top; + }); + await expect.poll(precedingBottom).toBeLessThanOrEqual(0); + releaseMarkdown(); + await expect(viewport.getByRole("heading", { name: "Earlier answer 0" })).toBeAttached(); + await expect.poll(precedingBottom).toBeLessThanOrEqual(0); + await expect.poll(precedingBottom).toBeGreaterThan(-1); + await expect.poll(() => prompt.evaluate((node) => { + const offset = node.getBoundingClientRect().top + - node.closest('[data-testid="thread-message-region"]')!.getBoundingClientRect().top; + return offset >= 0 && offset <= 48; + })).toBe(true); + expect(errors).toEqual([]); +}); + +test("does not apply a previous conversation's anchor after switching away and back", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 800 }); + const { emit, errors, turnId } = await openThread(page, true); + const viewport = page.getByTestId("thread-message-region"); + const base = { chat_id: chatId, turn_id: turnId, stream_id: "answer" }; + emit({ event: "delta", ...base, turn_seq: 1, text: `${"Long output before switching.\n\n".repeat(80)}BEFORE-SWITCH` }); + await expect(viewport).toContainText("BEFORE-SWITCH"); + await page.getByRole("button", { name: "Switch topic" }).click(); + await expect(page.getByText("My anchored question", { exact: true })).toHaveCount(0); + emit({ event: "delta", ...base, turn_seq: 2, text: "\n\nOutput while away." }); + await expect(page.getByText("Output while away.", { exact: true })).toHaveCount(0); + await page.getByRole("button", { name: "Switch topic" }).click(); + await expect(page.getByText("My anchored question", { exact: true })).toHaveCount(1); + await expect(viewport).toContainText("Output while away."); + await expect.poll(() => viewport.evaluate((node) => node.clientHeight)).toBeLessThan(800); + await expect.poll(() => page.locator(".thread-layout").evaluate((node) => + node.getAnimations().some((animation) => animation.playState === "running"), + )).toBe(false); + await expect.poll(() => viewport.evaluate((node) => node.scrollHeight - node.clientHeight - node.scrollTop)) + .toBeLessThanOrEqual(1); + const reopenedTop = await viewport.evaluate((node) => node.scrollTop); + emit({ event: "delta", ...base, turn_seq: 3, text: `\n\n${"Output after returning.\n\n".repeat(30)}AFTER-RETURN` }); + await expect(viewport).toContainText("AFTER-RETURN"); + expect(await viewport.evaluate((node) => node.scrollTop)).toBeCloseTo(reopenedTop, 0); + expect(errors).toEqual([]); +}); diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index b20166a31..f221920dd 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -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(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>(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(), [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 ?
: null} onComposerLayoutChange={alignSidebar} activeTurnId={viewportTurnId} - activeTurnStartedHere={activeTurnStartedHere} + submittedPromptTurnId={submittedViewportTurnId} conversationKey={historyKey} conversationReady={messagesReady} onVisibleMessagesChange={reportVisibleMessages} diff --git a/webui/src/components/thread/ThreadViewport.tsx b/webui/src/components/thread/ThreadViewport.tsx index e7528c87e..dba570d4a 100644 --- a/webui/src/components/thread/ThreadViewport.tsx +++ b/webui/src/components/thread/ThreadViewport.tsx @@ -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(null); const endGapRef = useRef(null); - const lastConversationKeyRef = useRef(conversationKey); + const anchoredTurnIdRef = useRef(null); + const anchoredPromptIdRef = useRef(null); + const openingMessagesRef = useRef(null); + const finishOpeningAfterLayoutRef = useRef(false); + const conversationIdentity = conversationKey ?? messagesKey; + const lastConversationKeyRef = useRef(conversationIdentity); const conversationHandoffPendingRef = useRef(false); const conversationHandoffAnimationRef = useRef(null); const pendingConversationScrollRef = useRef(true); @@ -420,14 +437,32 @@ export const ThreadViewport = forwardRef { + 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 { + 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 { - 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 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 { if (scrollToBottomSignal <= 0) return; @@ -782,8 +820,8 @@ export const ThreadViewport = forwardRef { - 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 { 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 { @@ -988,6 +1031,8 @@ export const ThreadViewport = forwardRef { const el = scrollRef.current; @@ -1293,7 +1338,7 @@ export const ThreadViewport = forwardRef -
+
} - />, - ); - + it.each([48, 12])("anchors within a %i px preceding gap despite an early layout scroll event", (gap) => { + const clock = controlAnimationFrames(); + const { container, rerender } = render(); const scroller = getScroller(container); - Object.defineProperties(scroller, { - scrollHeight: { configurable: true, value: 1200 }, - clientHeight: { configurable: true, value: 500 }, - scrollTop: { configurable: true, writable: true, value: 700 }, - scrollTo: { configurable: true, value: scrollTo }, - }); - const prompt = container.querySelector('[data-user-prompt-id="u2"]'); - expect(prompt).not.toBeNull(); - Object.defineProperty(prompt, "offsetTop", { - configurable: true, - value: 420, - }); - scrollTo.mockClear(); - jumpTo.mockClear(); - - await act(async () => { - rerender( - composer
} - activeTurnId="turn-2" - activeTurnStartedHere - />, - ); - }); - await flushAnimationFrame(); - - expect(jumpTo).toHaveBeenCalledWith(700); - expect(screen.getByTestId("thread-message-region")).toHaveClass("justify-start"); - }); - - it("keeps automatic ownership when layout emits a scroll before its measurement frame", async () => { - const jumpTo = vi.spyOn(ThreadCameraController.prototype, "jumpTo"); - const threaded: UIMessage[] = [ - { id: "u1", role: "user", content: "old question", turnId: "turn-1", createdAt: 1 }, - { id: "a1", role: "assistant", content: "old answer", turnId: "turn-1", createdAt: 2 }, - { id: "u2", role: "user", content: "new question", turnId: "turn-2", createdAt: 3 }, - ]; - const { container, rerender } = render( - composer
} - />, - ); - const scroller = getScroller(container); - Object.defineProperties(scroller, { - scrollHeight: { configurable: true, value: 1_200 }, - clientHeight: { configurable: true, value: 500 }, - scrollTop: { configurable: true, writable: true, value: 700 }, - }); - const prompt = container.querySelector('[data-user-prompt-id="u2"]'); - expect(prompt).not.toBeNull(); - Object.defineProperty(prompt, "offsetTop", { - configurable: true, - value: 420, - }); - jumpTo.mockClear(); - - await act(async () => { - rerender( - composer} - activeTurnId="turn-2" - activeTurnStartedHere - />, - ); - }); - - Object.defineProperty(scroller, "scrollHeight", { - configurable: true, - value: 1_280, - }); - act(() => { - scroller.dispatchEvent(new Event("scroll")); - }); - - expect(screen.queryByRole("button", { name: "Scroll to bottom" })) - .not.toBeInTheDocument(); - await flushAnimationFrame(); - expect(jumpTo).toHaveBeenCalledWith(780); - expect(scroller.scrollTop).toBe(780); - }); - - it("lets the first prompt supersede a pending empty-conversation camera command", async () => { - const jumpTo = vi.spyOn(ThreadCameraController.prototype, "jumpTo"); - const scrollTo = vi.fn(); - const firstPrompt: UIMessage = { - id: "u-first", - role: "user", - content: "first question", - turnId: "turn-first", - createdAt: 1, - }; - const { container, rerender } = render( - composer} - conversationKey={null} - />, - ); - const scroller = getScroller(container); - Object.defineProperties(scroller, { - scrollHeight: { configurable: true, value: 1200 }, - clientHeight: { configurable: true, value: 500 }, - scrollTop: { configurable: true, writable: true, value: 700 }, - scrollTo: { configurable: true, value: scrollTo }, - }); - scrollTo.mockClear(); - jumpTo.mockClear(); - - await act(async () => { - rerender( - composer} - conversationKey="chat-a" - conversationReady={false} - activeTurnId="turn-first" - activeTurnStartedHere - />, - ); - }); - const threadScroller = getScroller(container); - Object.defineProperties(threadScroller, { - scrollHeight: { configurable: true, value: 1200 }, - clientHeight: { configurable: true, value: 500 }, - scrollTop: { configurable: true, writable: true, value: 0 }, - scrollTo: { configurable: true, value: scrollTo }, - }); - jumpTo.mockClear(); - await act(async () => { - rerender( - composer} - conversationKey="chat-a" - conversationReady - activeTurnId="turn-first" - activeTurnStartedHere - />, - ); - }); - await flushAnimationFrame(); - - expect(jumpTo).toHaveBeenCalledTimes(1); - expect(jumpTo).toHaveBeenCalledWith(700); - }); - - it("anchors the latest user prompt even when assistant output is already present", async () => { - const jumpTo = vi.spyOn(ThreadCameraController.prototype, "jumpTo"); - const threaded: UIMessage[] = [ - { id: "u1", role: "user", content: "old question", turnId: "turn-1", createdAt: 1 }, - { id: "a1", role: "assistant", content: "old answer", turnId: "turn-1", createdAt: 2 }, - { id: "u2", role: "user", content: "new question", turnId: "turn-2", createdAt: 3 }, - { id: "a2", role: "assistant", content: "fast answer", turnId: "turn-2", createdAt: 4 }, - ]; - const viewportRef = createRef(); - const scrollTo = vi.fn(); - const { container, rerender } = render( - composer} - />, - ); - - const scroller = getScroller(container); - Object.defineProperties(scroller, { - scrollHeight: { configurable: true, value: 1904 }, - clientHeight: { configurable: true, value: 500 }, - scrollTop: { configurable: true, writable: true, value: 1404 }, - scrollTo: { configurable: true, value: scrollTo }, - }); - const prompt = container.querySelector('[data-user-prompt-id="u2"]'); - expect(prompt).not.toBeNull(); - Object.defineProperty(prompt, "offsetTop", { - configurable: true, - value: 1420, - }); - viewportRef.current?.cancelAutoScroll(); - scrollTo.mockClear(); - jumpTo.mockClear(); - - await act(async () => { - rerender( - composer} - activeTurnId="turn-2" - activeTurnStartedHere - />, - ); - }); - await flushAnimationFrame(); - - expect(jumpTo).toHaveBeenCalledWith(1372); - }); - - it("drives the camera from a message commit when canonical replay replaces the prompt DOM id", async () => { - const resizeObserver = stubResizeObserver(); - const followTo = vi.spyOn(ThreadCameraController.prototype, "followTo") - .mockReturnValue("started"); - - try { - const optimistic: UIMessage[] = [ - { - id: "optimistic-user", - role: "user", - content: "new question", - turnId: "turn-stable", - createdAt: 1, - }, - { - id: "optimistic-answer", - role: "assistant", - content: "answer", - turnId: "turn-stable", - isStreaming: true, - createdAt: 2, - }, - ]; - const { container, rerender } = render( - composer} - />, - ); - const scroller = getScroller(container); - Object.defineProperties(scroller, { - scrollHeight: { configurable: true, value: 2_000 }, - clientHeight: { configurable: true, value: 500 }, - scrollTop: { configurable: true, writable: true, value: 1_500 }, - scrollTo: { - configurable: true, - value: ({ top }: ScrollToOptions) => { - if (typeof top === "number") scroller.scrollTop = top; - }, - }, - }); - const optimisticPrompt = container.querySelector( - '[data-user-prompt-id="optimistic-user"]', - ); - expect(optimisticPrompt).not.toBeNull(); - Object.defineProperty(optimisticPrompt, "offsetTop", { - configurable: true, - value: 1_420, - }); - - await act(async () => { - rerender( - composer} - activeTurnId="turn-stable" - />, - ); - }); - followTo.mockClear(); - - await act(async () => { - rerender( - composer} - activeTurnId="turn-stable" - />, - ); - }); - await flushAnimationFrame(); - // Streaming React commits only invalidate geometry. The next display - // frame measures once and issues the follow command. - expect(followTo).toHaveBeenCalledWith(1_500); - - followTo.mockClear(); - Object.defineProperty(scroller, "scrollHeight", { - configurable: true, - value: 2_120, - }); - const messageContent = screen.getByTestId("thread-message-region").firstElementChild; - const contentObserver = resizeObserver.observers.find( - (observer) => observer.elements.includes(messageContent!), - ); - expect(contentObserver).toBeDefined(); - - act(() => { - contentObserver!.callback([], contentObserver!); - }); - await flushAnimationFrame(); - - // ResizeObserver remains the asynchronous reflow fallback. - expect(followTo).toHaveBeenCalledWith(1_620); - } finally { - followTo.mockRestore(); - resizeObserver.restore(); - } - }); - - it("settles observed streamed layout growth before paint", async () => { - const resizeObserver = stubResizeObserver(); - const followTo = vi.spyOn(ThreadCameraController.prototype, "followTo") - .mockReturnValue("started"); - - try { - const threaded: UIMessage[] = [ - { id: "u1", role: "user", content: "old question", turnId: "turn-1", createdAt: 1 }, - { id: "a1", role: "assistant", content: "old answer", turnId: "turn-1", createdAt: 2 }, - { id: "u2", role: "user", content: "new question", turnId: "turn-2", createdAt: 3 }, - ]; - const answer: UIMessage = { - id: "a2", - role: "assistant", - content: "streaming answer", - turnId: "turn-2", - isStreaming: true, - createdAt: 4, - }; - const { container, rerender } = render( - composer} - />, - ); - - const scroller = getScroller(container); - Object.defineProperties(scroller, { - scrollHeight: { configurable: true, value: 1904 }, - clientHeight: { configurable: true, value: 500 }, - scrollTop: { configurable: true, writable: true, value: 1404 }, - }); - const prompt = container.querySelector('[data-user-prompt-id="u2"]'); - expect(prompt).not.toBeNull(); - Object.defineProperty(prompt, "offsetTop", { - configurable: true, - value: 1420, - }); - - await act(async () => { - rerender( - composer} - activeTurnId="turn-2" - activeTurnStartedHere - />, - ); - }); - await flushAnimationFrame(); - followTo.mockClear(); - - Object.defineProperty(scroller, "scrollHeight", { - configurable: true, - value: 1932, - }); - await act(async () => { - rerender( - composer} - activeTurnId="turn-2" - />, - ); - }); - await flushAnimationFrame(); - expect(followTo).toHaveBeenCalledTimes(1); - expect(followTo).toHaveBeenLastCalledWith(1432); - followTo.mockClear(); - - const messageRegion = screen.getByTestId("thread-message-region"); - const messageContent = messageRegion.firstElementChild; - expect(messageContent).not.toBeNull(); - const contentObserver = resizeObserver.observers.find( - (observer) => observer.elements.includes(messageContent!), - ); - expect(contentObserver).toBeDefined(); - - Object.defineProperty(scroller, "scrollHeight", { - configurable: true, - value: 1948, - }); - act(() => { - contentObserver!.callback([], contentObserver!); - }); - expect(followTo).toHaveBeenCalledTimes(1); - expect(followTo).toHaveBeenLastCalledWith(1448); - followTo.mockClear(); - - Object.defineProperty(scroller, "scrollHeight", { - configurable: true, - value: 2548, - }); - await act(async () => { - rerender( - composer} - />, - ); - }); - await flushAnimationFrame(); - expect(followTo).toHaveBeenLastCalledWith(2048); - followTo.mockClear(); - - scroller.scrollTop = 100; - act(() => { - dispatchUserScroll(scroller); - }); - Object.defineProperty(scroller, "scrollHeight", { - configurable: true, - value: 2560, - }); - act(() => { - contentObserver!.callback([], contentObserver!); - }); - await flushAnimationFrame(); - expect(followTo).not.toHaveBeenCalled(); - expect(scroller.scrollTop).toBe(100); - } finally { - followTo.mockRestore(); - resizeObserver.restore(); - } - }); - - it("keeps shallow wheel and touch scrolling user-owned until intent reverses", async () => { - const followTo = vi.spyOn(ThreadCameraController.prototype, "followTo"); - const threaded: UIMessage[] = [ - { id: "u1", role: "user", content: "old question", turnId: "turn-1", createdAt: 1 }, - { id: "a1", role: "assistant", content: "old answer", turnId: "turn-1", createdAt: 2 }, - { id: "u2", role: "user", content: "new question", turnId: "turn-2", createdAt: 3 }, - ]; - const answer: UIMessage = { - id: "a2", - role: "assistant", - content: "streaming answer", - turnId: "turn-2", - isStreaming: true, - createdAt: 4, - }; - const { container, rerender } = render( - composer} - />, - ); - const scroller = getScroller(container); - Object.defineProperties(scroller, { - scrollHeight: { configurable: true, value: 1_904 }, - clientHeight: { configurable: true, value: 500 }, - scrollTop: { configurable: true, writable: true, value: 1_404 }, - }); - const prompt = container.querySelector('[data-user-prompt-id="u2"]'); - expect(prompt).not.toBeNull(); - Object.defineProperty(prompt, "offsetTop", { - configurable: true, - value: 1_420, - }); + mockScrollGeometry(scroller, 1_200, 500, 700); + const prompt = container.querySelector('[data-user-prompt-id="u2"]')!; + mockPromptPosition(scroller, prompt, 420, gap); rerender( - composer} - activeTurnId="turn-2" - activeTurnStartedHere - />, + , ); - await flushAnimationFrame(); - followTo.mockClear(); + mockScrollGeometry(scroller, 1_280, 500, scroller.scrollTop); + fireEvent.scroll(scroller); + expect(screen.queryByRole("button", { name: "Scroll to bottom" })).not.toBeInTheDocument(); + clock.frame(0); + clock.frame(300); + expect(scroller.scrollTop).toBe(420 - gap); + expect(prompt.getBoundingClientRect().top).toBe(gap); + }); - mockMessageEnd(scroller); - act(() => { - fireEvent.wheel(scroller, { deltaY: -24 }); - scroller.scrollTop = 1_380; - scroller.dispatchEvent(new Event("scroll")); + it("lets the first prompt supersede a pending empty-conversation camera command", () => { + const clock = controlAnimationFrames(); + const firstPrompt = { ...submittedMessages[2], content: "first question\n".repeat(60) }; + const viewport = (ready: boolean) => ( + + ); + const { container, rerender } = render( + , + ); + mockScrollGeometry(getScroller(container), 1_200, 500, 700); + rerender(viewport(false)); + const scroller = getScroller(container); + mockScrollGeometry(scroller, 1_200, 500); + const prompt = container.querySelector('[data-user-prompt-id="u2"]')!; + mockPromptPosition(scroller, prompt, 0); + prompt.getBoundingClientRect = () => DOMRect.fromRect({ y: -scroller.scrollTop, width: 800, height: 1_200 }); + + rerender(viewport(true)); + clock.frame(0); + expect(scroller.scrollTop).toBe(0); + clock.frame(300); + expect(scroller.scrollTop).toBe(0); + }); + + it.each(["before measurement", "during animation"])("finishes anchoring when a quick turn completes %s", (timing) => { + const clock = controlAnimationFrames(); + const complete = [...submittedMessages, submittedAnswer]; + const { container, rerender } = render(); + const scroller = getScroller(container); + mockScrollGeometry(scroller, 1_200, 500, 700); + const positionPrompt = () => mockPromptPosition( + scroller, container.querySelector('[data-user-prompt-id="u2"]')!, 420, + ); + rerender( + , + ); + positionPrompt(); + if (timing === "during animation") { + clock.frame(0); + clock.frame(80); + } + rerender(); + positionPrompt(); + clock.frame(0); + clock.frame(300); + expect(scroller.scrollTop).toBe(372); + }); + + it.each(["before measurement", "during animation", "after settlement"])( + "anchors the canonical prompt when replay replaces its DOM id %s", + (timing) => { + const clock = controlAnimationFrames(); + const { container, rerender } = render(); + const scroller = getScroller(container); + mockScrollGeometry(scroller, 1_200, 500, 700); + mockPromptPosition(scroller, container.querySelector('[data-user-prompt-id="u2"]')!, 420); + const viewport = (prompt: UIMessage) => ( + + ); + rerender(viewport(submittedMessages[2])); + if (timing !== "before measurement") { + clock.frame(0); + clock.frame(timing === "during animation" ? 80 : 300); + } + + rerender(viewport({ ...submittedMessages[2], id: "canonical-user" })); + const canonical = container.querySelector('[data-user-prompt-id="canonical-user"]')!; + mockScrollGeometry(scroller, 1_300, 500, scroller.scrollTop); + mockPromptPosition(scroller, canonical, 520); + clock.frame(0); + clock.frame(300); + expect(scroller.scrollTop).toBe(472); + expect(canonical.getBoundingClientRect().top).toBe(48); + }, + ); + + it("preserves the prompt through output, composer growth and reflow until the reader takes control", () => { + const clock = controlAnimationFrames(); + const resizeObserver = stubResizeObserver(); + try { + const composer =