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
@@ -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() {
|
||||
<ThreadShell
|
||||
session={{ key: `websocket:${chatId}`, channel: "websocket", chatId, createdAt: null, updatedAt: null, preview: "" }}
|
||||
title={chatId} onToggleSidebar={() => {}} onTurnEnd={onTurnEnd}
|
||||
settingsSnapshot={settings} messageCache={cache}
|
||||
settingsSnapshot={fixtureSettings} messageCache={cache}
|
||||
/>
|
||||
</main>
|
||||
</ClientProvider>;
|
||||
|
||||
@@ -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<void> } = {},
|
||||
) {
|
||||
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<HTMLElement>('[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<void>((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([]);
|
||||
});
|
||||
@@ -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);
|
||||
};
|
||||
}
|
||||
@@ -80,11 +80,11 @@ describe("ThreadCameraController", () => {
|
||||
expect(camera.isFollowing()).toBe(false);
|
||||
});
|
||||
|
||||
it("pins automatic follow in the geometry frame without camera debt", () => {
|
||||
it("jumps to a target and cancels any earlier navigation", () => {
|
||||
const { camera, viewport, frames } = cameraHarness();
|
||||
|
||||
expect(camera.followTo(60)).toBe("settled");
|
||||
|
||||
camera.navigateTo(1_000);
|
||||
expect(frames).toHaveLength(1);
|
||||
camera.jumpTo(60);
|
||||
expect(viewport.scrollTop).toBe(60);
|
||||
expect(frames).toHaveLength(0);
|
||||
expect(camera.isFollowing()).toBe(false);
|
||||
@@ -104,19 +104,6 @@ describe("ThreadCameraController", () => {
|
||||
expect(viewport.scrollTop).toBe(180);
|
||||
});
|
||||
|
||||
it("pins repeated automatic targets without accumulating lag", () => {
|
||||
const { camera, viewport, frames } = cameraHarness();
|
||||
|
||||
camera.followTo(80);
|
||||
expect(viewport.scrollTop).toBe(80);
|
||||
camera.followTo(140);
|
||||
expect(viewport.scrollTop).toBe(140);
|
||||
camera.followTo(220);
|
||||
expect(viewport.scrollTop).toBe(220);
|
||||
expect(frames).toHaveLength(0);
|
||||
expect(camera.isFollowing()).toBe(false);
|
||||
});
|
||||
|
||||
it("separates external movement from camera writes and layout clamping", () => {
|
||||
const { camera, viewport } = cameraHarness();
|
||||
viewport.scrollHeight = 2_000;
|
||||
|
||||
@@ -39,11 +39,11 @@ function motionHarness(initial?: Partial<ThreadMotionGeometry>) {
|
||||
dispose: vi.fn(),
|
||||
observeScroll: vi.fn(() => 0),
|
||||
reset: vi.fn(() => { cameraFollowing = false; }),
|
||||
jumpTo: vi.fn(),
|
||||
followTo: vi.fn(() => "settled" as const),
|
||||
jumpTo: vi.fn((top: number) => { geometry = { ...geometry, scrollTop: top }; }),
|
||||
isFollowing: vi.fn(() => cameraFollowing),
|
||||
navigateTo: vi.fn(() => {
|
||||
cameraFollowing = nextNavigationResult === "started";
|
||||
navigateTo: vi.fn((top: number) => {
|
||||
cameraFollowing = nextNavigationResult !== "settled";
|
||||
if (!cameraFollowing) geometry = { ...geometry, scrollTop: top };
|
||||
return nextNavigationResult;
|
||||
}),
|
||||
};
|
||||
@@ -73,6 +73,13 @@ function motionHarness(initial?: Partial<ThreadMotionGeometry>) {
|
||||
const setCameraFollowing = (following: boolean) => {
|
||||
cameraFollowing = following;
|
||||
};
|
||||
const settleCamera = () => {
|
||||
if (cameraFollowing) {
|
||||
geometry = { ...geometry, scrollTop: camera.navigateTo.mock.lastCall![0] };
|
||||
}
|
||||
cameraFollowing = false;
|
||||
coordinator.cameraSettled();
|
||||
};
|
||||
const setNextNavigationResult = (result: ThreadCameraFollowResult) => {
|
||||
nextNavigationResult = result;
|
||||
};
|
||||
@@ -87,469 +94,184 @@ function motionHarness(initial?: Partial<ThreadMotionGeometry>) {
|
||||
scheduler,
|
||||
advanceFrame,
|
||||
setCameraFollowing,
|
||||
settleCamera,
|
||||
setGeometry,
|
||||
setNextNavigationResult,
|
||||
};
|
||||
}
|
||||
|
||||
describe("ThreadMotionCoordinator", () => {
|
||||
it("coalesces discrete invalidations into one authoritative geometry frame", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
frames,
|
||||
measure,
|
||||
scheduler,
|
||||
advanceFrame,
|
||||
} = motionHarness();
|
||||
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: true,
|
||||
});
|
||||
it("coalesces anchoring, ignores output below the prompt, and corrects reflow above it", () => {
|
||||
const { camera, coordinator, measure, scheduler, advanceFrame, setGeometry, settleCamera } = motionHarness();
|
||||
coordinator.updateTurn("turn-1");
|
||||
coordinator.anchorSubmittedPrompt("prompt-1");
|
||||
coordinator.invalidateGeometry();
|
||||
coordinator.invalidateGeometry();
|
||||
|
||||
expect(scheduler.request).toHaveBeenCalledTimes(1);
|
||||
expect(frames).toHaveLength(1);
|
||||
expect(measure).not.toHaveBeenCalled();
|
||||
|
||||
expect(scheduler.request).toHaveBeenCalledOnce();
|
||||
advanceFrame();
|
||||
expect(camera.navigateTo.mock.calls).toEqual([[404]]);
|
||||
expect(camera.jumpTo).not.toHaveBeenCalled();
|
||||
|
||||
expect(measure).toHaveBeenCalledTimes(1);
|
||||
expect(measure).toHaveBeenCalledWith("prompt-1");
|
||||
expect(camera.jumpTo).toHaveBeenCalledWith(404);
|
||||
expect(camera.followTo).toHaveBeenCalledWith(1_400);
|
||||
expect(coordinator.snapshot()).toMatchObject({
|
||||
mode: "follow-output",
|
||||
promptPositioned: true,
|
||||
measurementPending: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("reconciles observed layout growth before the next paint", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
frames,
|
||||
scheduler,
|
||||
advanceFrame,
|
||||
setGeometry,
|
||||
} = motionHarness();
|
||||
|
||||
coordinator.resumeAutoFollow();
|
||||
advanceFrame();
|
||||
camera.jumpTo.mockClear();
|
||||
scheduler.cancel.mockClear();
|
||||
|
||||
setGeometry({ scrollTop: 1_400, scrollHeight: 2_054 });
|
||||
settleCamera();
|
||||
expect(coordinator.snapshot().mode).toBe("reading-prompt");
|
||||
setGeometry({ scrollHeight: 2_200 });
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
expect(camera.jumpTo).not.toHaveBeenCalled();
|
||||
|
||||
coordinator.updateTurn(null);
|
||||
setGeometry({ scrollHeight: 2_400, promptTop: 620 });
|
||||
coordinator.reconcileObservedGeometry();
|
||||
|
||||
expect(camera.jumpTo).toHaveBeenCalledWith(1_554);
|
||||
expect(scheduler.cancel).toHaveBeenCalledTimes(1);
|
||||
expect(frames).toHaveLength(0);
|
||||
expect(coordinator.snapshot()).toMatchObject({ measurementPending: false });
|
||||
expect(measure).toHaveBeenLastCalledWith("prompt-1", true);
|
||||
expect(camera.jumpTo).toHaveBeenCalledWith(620);
|
||||
expect(camera.navigateTo).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("pins repeated output growth on each authoritative geometry frame", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
setGeometry,
|
||||
} = motionHarness();
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: true,
|
||||
});
|
||||
it("corrects reflow after a submitted prompt settles without animation", () => {
|
||||
const { camera, coordinator, advanceFrame, setGeometry, setNextNavigationResult } = motionHarness({ promptTop: 400 });
|
||||
setNextNavigationResult("settled");
|
||||
coordinator.anchorSubmittedPrompt("prompt-1");
|
||||
advanceFrame();
|
||||
camera.cancel.mockClear();
|
||||
camera.followTo.mockClear();
|
||||
|
||||
setGeometry({ scrollTop: 1_400, scrollHeight: 1_928 });
|
||||
coordinator.invalidateGeometry();
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
setGeometry({ scrollTop: 1_410, scrollHeight: 1_944 });
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
|
||||
expect(camera.followTo.mock.calls).toEqual([[1_428], [1_444]]);
|
||||
expect(camera.cancel).not.toHaveBeenCalled();
|
||||
setGeometry({ promptTop: 520 });
|
||||
coordinator.reconcileObservedGeometry();
|
||||
expect(camera.jumpTo).toHaveBeenCalledWith(520);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"geometry-before-completion",
|
||||
"completion-before-geometry",
|
||||
] as const)("keeps following final layout for %s ordering", (ordering) => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
setGeometry,
|
||||
} = motionHarness();
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: true,
|
||||
});
|
||||
it.each(["before the frame", "during animation", "at the scroll boundary", "after settlement"])(
|
||||
"preserves user takeover through layout growth and completion %s",
|
||||
(timing) => {
|
||||
const { camera, coordinator, advanceFrame, setGeometry, settleCamera } = motionHarness(
|
||||
timing === "at the scroll boundary" ? { scrollTop: 0, promptTop: 0 } : undefined,
|
||||
);
|
||||
coordinator.updateTurn("turn-1");
|
||||
coordinator.anchorSubmittedPrompt("prompt-1");
|
||||
if (timing !== "before the frame") advanceFrame();
|
||||
if (timing === "at the scroll boundary" || timing === "after settlement") settleCamera();
|
||||
camera.navigateTo.mockClear();
|
||||
if (timing === "at the scroll boundary") coordinator.handleUserScrollIntent(false);
|
||||
else coordinator.takeUserControl();
|
||||
setGeometry({ scrollHeight: 2_100, promptTop: 700 });
|
||||
coordinator.updateTurn(null);
|
||||
advanceFrame();
|
||||
settleCamera();
|
||||
expect(camera.navigateTo).not.toHaveBeenCalled();
|
||||
expect(camera.jumpTo).not.toHaveBeenCalled();
|
||||
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
||||
},
|
||||
);
|
||||
|
||||
it("does not resume streaming follow when the reader reaches the tail", () => {
|
||||
const { camera, coordinator, onAutoFollow, advanceFrame, setGeometry, settleCamera } = motionHarness();
|
||||
coordinator.updateTurn("turn-1");
|
||||
coordinator.anchorSubmittedPrompt("prompt-1");
|
||||
advanceFrame();
|
||||
camera.cancel.mockClear();
|
||||
camera.followTo.mockClear();
|
||||
|
||||
const applyFinalGeometry = () => {
|
||||
setGeometry({
|
||||
scrollTop: 1_400,
|
||||
scrollHeight: 2_400,
|
||||
});
|
||||
coordinator.invalidateGeometry();
|
||||
};
|
||||
if (ordering === "geometry-before-completion") applyFinalGeometry();
|
||||
coordinator.completeTurn();
|
||||
if (ordering === "completion-before-geometry") applyFinalGeometry();
|
||||
|
||||
expect(coordinator.snapshot().mode).toBe("follow-completion");
|
||||
expect(camera.cancel).not.toHaveBeenCalled();
|
||||
advanceFrame();
|
||||
expect(camera.followTo).toHaveBeenLastCalledWith(1_900);
|
||||
|
||||
setGeometry({
|
||||
scrollTop: 1_900,
|
||||
scrollHeight: 2_450,
|
||||
});
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
expect(camera.followTo).toHaveBeenLastCalledWith(1_950);
|
||||
});
|
||||
|
||||
it("releases completion follow when composer editing begins", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
setGeometry,
|
||||
} = motionHarness();
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: true,
|
||||
});
|
||||
advanceFrame();
|
||||
coordinator.completeTurn();
|
||||
camera.jumpTo.mockClear();
|
||||
camera.followTo.mockClear();
|
||||
camera.cancel.mockClear();
|
||||
|
||||
coordinator.handleComposerInput();
|
||||
setGeometry({
|
||||
scrollTop: 1_400,
|
||||
scrollHeight: 1_940,
|
||||
composerHeight: 160,
|
||||
});
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
|
||||
expect(camera.cancel).toHaveBeenCalledTimes(1);
|
||||
expect(camera.jumpTo).not.toHaveBeenCalled();
|
||||
expect(camera.followTo).not.toHaveBeenCalled();
|
||||
settleCamera();
|
||||
coordinator.handleUserScrollIntent(true);
|
||||
coordinator.handleUserScrollIntent(true, true);
|
||||
expect(coordinator.observeScroll(true)).toBe("automatic");
|
||||
expect(onAutoFollow).toHaveBeenCalledTimes(1);
|
||||
expect(coordinator.snapshot().mode).toBe("idle");
|
||||
});
|
||||
|
||||
it("remembers composer editing that begins before turn completion", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
setGeometry,
|
||||
} = motionHarness();
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: true,
|
||||
});
|
||||
advanceFrame();
|
||||
camera.followTo.mockClear();
|
||||
camera.cancel.mockClear();
|
||||
|
||||
coordinator.handleComposerInput();
|
||||
expect(coordinator.snapshot().mode).toBe("follow-output");
|
||||
|
||||
coordinator.completeTurn();
|
||||
setGeometry({
|
||||
scrollTop: 1_400,
|
||||
scrollHeight: 1_940,
|
||||
composerHeight: 160,
|
||||
});
|
||||
advanceFrame();
|
||||
|
||||
expect(camera.cancel).toHaveBeenCalledTimes(1);
|
||||
expect(camera.followTo).not.toHaveBeenCalled();
|
||||
expect(coordinator.snapshot().mode).toBe("idle");
|
||||
});
|
||||
|
||||
it("keeps turn identity stable when canonical replay replaces DOM ids", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
measure,
|
||||
advanceFrame,
|
||||
setGeometry,
|
||||
} = motionHarness();
|
||||
coordinator.updateTurn({
|
||||
id: "turn-stable",
|
||||
promptId: "optimistic-prompt",
|
||||
hasOutput: true,
|
||||
});
|
||||
advanceFrame();
|
||||
camera.jumpTo.mockClear();
|
||||
measure.mockClear();
|
||||
|
||||
setGeometry({ scrollHeight: 2_020, promptTop: 120 });
|
||||
coordinator.updateTurn({
|
||||
id: "turn-stable",
|
||||
promptId: "canonical-prompt",
|
||||
hasOutput: true,
|
||||
});
|
||||
advanceFrame();
|
||||
|
||||
expect(measure).toHaveBeenCalledWith(null);
|
||||
expect(camera.jumpTo).not.toHaveBeenCalled();
|
||||
expect(camera.followTo).toHaveBeenLastCalledWith(1_520);
|
||||
});
|
||||
|
||||
it("continues from the bottom when a running turn is restored before prompt identity", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
} = motionHarness({
|
||||
scrollTop: 1_400,
|
||||
});
|
||||
|
||||
coordinator.updateTurn({
|
||||
id: "turn-restored",
|
||||
promptId: null,
|
||||
hasOutput: true,
|
||||
entry: "restored",
|
||||
});
|
||||
advanceFrame();
|
||||
|
||||
expect(camera.jumpTo).not.toHaveBeenCalled();
|
||||
expect(camera.followTo).toHaveBeenCalledWith(1_400);
|
||||
expect(coordinator.snapshot()).toMatchObject({
|
||||
mode: "follow-output",
|
||||
promptPositioned: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("continues measuring while browsing history but does not steal the viewport", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
onGeometry,
|
||||
advanceFrame,
|
||||
setGeometry,
|
||||
} = motionHarness();
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: true,
|
||||
});
|
||||
advanceFrame();
|
||||
camera.followTo.mockClear();
|
||||
onGeometry.mockClear();
|
||||
|
||||
coordinator.takeUserControl();
|
||||
setGeometry({ scrollTop: 200, scrollHeight: 2_100 });
|
||||
camera.navigateTo.mockClear();
|
||||
setGeometry({ scrollHeight: 2_400 });
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
expect(camera.jumpTo).not.toHaveBeenCalled();
|
||||
expect(camera.navigateTo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
expect(onGeometry).toHaveBeenCalledTimes(1);
|
||||
expect(camera.followTo).not.toHaveBeenCalled();
|
||||
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
||||
|
||||
it("stops idle tail following when a running turn is restored", () => {
|
||||
const { camera, coordinator, advanceFrame, setGeometry } = motionHarness();
|
||||
coordinator.resumeAutoFollow();
|
||||
advanceFrame();
|
||||
expect(camera.followTo).toHaveBeenCalledWith(1_600);
|
||||
expect(camera.jumpTo).toHaveBeenCalledWith(1_400);
|
||||
camera.jumpTo.mockClear();
|
||||
coordinator.updateTurn("restored-turn");
|
||||
setGeometry({ scrollTop: 1_400, scrollHeight: 2_000 });
|
||||
advanceFrame();
|
||||
expect(camera.jumpTo).not.toHaveBeenCalled();
|
||||
expect(coordinator.snapshot().mode).toBe("idle");
|
||||
});
|
||||
|
||||
it("keeps an explicitly resumed idle thread pinned to its latest bottom without animating", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
setGeometry,
|
||||
} = motionHarness();
|
||||
it("settles restored transcript layout at the tail until new output arrives", () => {
|
||||
const { camera, coordinator, advanceFrame, setGeometry } = motionHarness();
|
||||
coordinator.updateTurn("restored-turn");
|
||||
coordinator.followOpeningLayout();
|
||||
setGeometry({ scrollTop: 1_400, scrollHeight: 2_000 });
|
||||
advanceFrame();
|
||||
expect(camera.jumpTo).toHaveBeenCalledWith(1_500);
|
||||
coordinator.finishOpeningLayout();
|
||||
camera.jumpTo.mockClear();
|
||||
setGeometry({ scrollTop: 1_500, scrollHeight: 2_200 });
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
expect(camera.jumpTo).not.toHaveBeenCalled();
|
||||
expect(coordinator.snapshot().mode).toBe("idle");
|
||||
});
|
||||
|
||||
it("lets user input take control while restored transcript layout is settling", () => {
|
||||
const { camera, coordinator, advanceFrame, setGeometry } = motionHarness();
|
||||
coordinator.updateTurn("restored-turn");
|
||||
coordinator.followOpeningLayout();
|
||||
coordinator.takeUserControl();
|
||||
coordinator.finishOpeningLayout();
|
||||
setGeometry({ scrollHeight: 2_000 });
|
||||
advanceFrame();
|
||||
expect(camera.jumpTo).not.toHaveBeenCalled();
|
||||
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
||||
});
|
||||
|
||||
it("keeps an explicitly resumed idle thread pinned as its layout grows", () => {
|
||||
const { camera, coordinator, scheduler, frames, advanceFrame, setGeometry } = motionHarness();
|
||||
coordinator.resumeAutoFollow();
|
||||
advanceFrame();
|
||||
expect(camera.jumpTo).toHaveBeenLastCalledWith(1_400);
|
||||
expect(coordinator.snapshot().mode).toBe("follow-latest");
|
||||
|
||||
camera.jumpTo.mockClear();
|
||||
setGeometry({
|
||||
scrollTop: 1_400,
|
||||
scrollHeight: 2_000,
|
||||
});
|
||||
scheduler.cancel.mockClear();
|
||||
setGeometry({ scrollTop: 1_400, scrollHeight: 2_054 });
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
|
||||
expect(camera.jumpTo).toHaveBeenCalledWith(1_500);
|
||||
expect(camera.followTo).not.toHaveBeenCalled();
|
||||
|
||||
coordinator.reconcileObservedGeometry();
|
||||
expect(camera.jumpTo).toHaveBeenCalledWith(1_554);
|
||||
expect(scheduler.cancel).toHaveBeenCalledTimes(1);
|
||||
expect(frames).toHaveLength(0);
|
||||
coordinator.takeUserControl();
|
||||
camera.jumpTo.mockClear();
|
||||
setGeometry({
|
||||
scrollTop: 300,
|
||||
scrollHeight: 2_100,
|
||||
});
|
||||
setGeometry({ scrollTop: 300, scrollHeight: 2_100 });
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
|
||||
expect(camera.jumpTo).not.toHaveBeenCalled();
|
||||
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
||||
});
|
||||
|
||||
it("treats scroll events as observations until explicit user intent takes control", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
setGeometry,
|
||||
} = motionHarness({
|
||||
scrollTop: 700,
|
||||
scrollHeight: 1_200,
|
||||
clientHeight: 500,
|
||||
maxScrollTop: 700,
|
||||
});
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: false,
|
||||
});
|
||||
it("retargets explicit latest navigation while moving, then stops following", () => {
|
||||
const { camera, coordinator, advanceFrame, setCameraFollowing, setGeometry } = motionHarness();
|
||||
coordinator.updateTurn("turn-1");
|
||||
coordinator.anchorSubmittedPrompt("prompt-1");
|
||||
advanceFrame();
|
||||
coordinator.takeUserControl();
|
||||
camera.navigateTo.mockClear();
|
||||
coordinator.navigateLatestTo(1_400);
|
||||
setGeometry({ scrollTop: 900, scrollHeight: 2_100 });
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
expect(camera.navigateTo.mock.calls).toEqual([[1_400], [1_600]]);
|
||||
setCameraFollowing(false);
|
||||
expect(coordinator.observeScroll(true)).toBe("navigation");
|
||||
expect(coordinator.snapshot().mode).toBe("idle");
|
||||
camera.jumpTo.mockClear();
|
||||
|
||||
setGeometry({
|
||||
scrollTop: 700,
|
||||
scrollHeight: 1_280,
|
||||
});
|
||||
expect(coordinator.observeScroll(false)).toBe("automatic");
|
||||
expect(coordinator.snapshot().mode).toBe("anchor-prompt");
|
||||
setGeometry({ scrollTop: 1_600, scrollHeight: 2_300 });
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
expect(camera.jumpTo).toHaveBeenCalledWith(780);
|
||||
|
||||
coordinator.takeUserControl();
|
||||
expect(coordinator.observeScroll(true)).toBe("user");
|
||||
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
||||
|
||||
expect(coordinator.observeScroll(false)).toBe("user");
|
||||
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
||||
|
||||
coordinator.handleUserScrollIntent(true, true);
|
||||
expect(coordinator.observeScroll(true)).toBe("automatic");
|
||||
expect(coordinator.snapshot().mode).toBe("anchor-prompt");
|
||||
expect(camera.jumpTo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resumes shallow history browsing when user intent turns toward latest", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
} = motionHarness({
|
||||
scrollTop: 1_400,
|
||||
});
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: true,
|
||||
});
|
||||
advanceFrame();
|
||||
camera.followTo.mockClear();
|
||||
|
||||
coordinator.handleUserScrollIntent(true);
|
||||
expect(coordinator.observeScroll(true)).toBe("user");
|
||||
advanceFrame();
|
||||
expect(camera.followTo).not.toHaveBeenCalled();
|
||||
|
||||
coordinator.handleUserScrollIntent(true, true);
|
||||
expect(coordinator.observeScroll(true)).toBe("automatic");
|
||||
expect(coordinator.snapshot().mode).toBe("follow-output");
|
||||
advanceFrame();
|
||||
expect(camera.followTo).toHaveBeenCalledWith(1_400);
|
||||
});
|
||||
|
||||
it("resumes shallow history browsing from forward intent at the boundary", () => {
|
||||
const {
|
||||
advanceFrame,
|
||||
coordinator,
|
||||
onAutoFollow,
|
||||
} = motionHarness({
|
||||
scrollTop: 1_400,
|
||||
});
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: true,
|
||||
});
|
||||
advanceFrame();
|
||||
|
||||
coordinator.handleUserScrollIntent(true);
|
||||
expect(coordinator.observeScroll(true)).toBe("user");
|
||||
|
||||
coordinator.handleUserScrollIntent(false, true);
|
||||
expect(coordinator.snapshot().mode).toBe("follow-output");
|
||||
expect(onAutoFollow).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("preserves history browsing when an active turn is cleared", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
} = motionHarness();
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: true,
|
||||
});
|
||||
advanceFrame();
|
||||
coordinator.takeUserControl();
|
||||
camera.followTo.mockClear();
|
||||
|
||||
coordinator.updateTurn({
|
||||
id: null,
|
||||
promptId: null,
|
||||
hasOutput: false,
|
||||
});
|
||||
advanceFrame();
|
||||
|
||||
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
||||
expect(camera.followTo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps history navigation independent from active turn completion", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
setGeometry,
|
||||
} = motionHarness();
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: true,
|
||||
});
|
||||
it("keeps history navigation in control through turn completion", () => {
|
||||
const { camera, coordinator, advanceFrame, setGeometry } = motionHarness();
|
||||
coordinator.updateTurn("turn-1");
|
||||
coordinator.anchorSubmittedPrompt("prompt-1");
|
||||
advanceFrame();
|
||||
setGeometry({ promptTop: 900 });
|
||||
coordinator.navigateHistoryToPrompt("prompt-2");
|
||||
camera.cancel.mockClear();
|
||||
|
||||
coordinator.completeTurn();
|
||||
|
||||
coordinator.updateTurn(null);
|
||||
expect(camera.cancel).not.toHaveBeenCalled();
|
||||
expect(coordinator.snapshot().mode).toBe("navigating-history");
|
||||
});
|
||||
@@ -624,134 +346,6 @@ describe("ThreadMotionCoordinator", () => {
|
||||
expect(coordinator.snapshot().mode).toBe("follow-latest");
|
||||
});
|
||||
|
||||
it("retargets smooth latest navigation before resuming automatic follow", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
setCameraFollowing,
|
||||
setGeometry,
|
||||
} = motionHarness();
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: true,
|
||||
});
|
||||
advanceFrame();
|
||||
coordinator.takeUserControl();
|
||||
camera.followTo.mockClear();
|
||||
camera.navigateTo.mockClear();
|
||||
|
||||
expect(coordinator.navigateLatestTo(1_400)).toBe("started");
|
||||
expect(coordinator.snapshot().mode).toBe("navigating-latest");
|
||||
|
||||
setGeometry({
|
||||
scrollTop: 900,
|
||||
scrollHeight: 2_100,
|
||||
});
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
|
||||
expect(camera.navigateTo.mock.calls).toEqual([[1_400], [1_600]]);
|
||||
expect(camera.followTo).not.toHaveBeenCalled();
|
||||
|
||||
setGeometry({ scrollTop: 1_600 });
|
||||
setCameraFollowing(false);
|
||||
expect(coordinator.observeScroll(true)).toBe("navigation");
|
||||
expect(coordinator.snapshot().mode).toBe("follow-output");
|
||||
|
||||
advanceFrame();
|
||||
expect(camera.followTo).toHaveBeenCalledWith(1_600);
|
||||
});
|
||||
|
||||
it("keeps latest navigation through completion and final layout growth", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
setCameraFollowing,
|
||||
setGeometry,
|
||||
} = motionHarness();
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: true,
|
||||
});
|
||||
advanceFrame();
|
||||
coordinator.takeUserControl();
|
||||
coordinator.navigateLatestTo(1_400);
|
||||
camera.followTo.mockClear();
|
||||
camera.navigateTo.mockClear();
|
||||
|
||||
coordinator.completeTurn();
|
||||
setGeometry({
|
||||
scrollTop: 1_000,
|
||||
scrollHeight: 2_300,
|
||||
});
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
|
||||
expect(camera.navigateTo).toHaveBeenCalledWith(1_800);
|
||||
expect(camera.followTo).not.toHaveBeenCalled();
|
||||
expect(coordinator.snapshot().mode).toBe("navigating-latest");
|
||||
|
||||
setGeometry({ scrollTop: 1_800 });
|
||||
setCameraFollowing(false);
|
||||
expect(coordinator.observeScroll(true)).toBe("navigation");
|
||||
expect(coordinator.snapshot().mode).toBe("follow-latest");
|
||||
|
||||
camera.jumpTo.mockClear();
|
||||
setGeometry({
|
||||
scrollTop: 1_800,
|
||||
scrollHeight: 2_400,
|
||||
});
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
|
||||
expect(camera.jumpTo).toHaveBeenCalledWith(1_900);
|
||||
});
|
||||
|
||||
it("pins a waiting prompt to the exact lower boundary across all layout changes", () => {
|
||||
const {
|
||||
camera,
|
||||
coordinator,
|
||||
advanceFrame,
|
||||
setGeometry,
|
||||
} = motionHarness({
|
||||
scrollHeight: 930,
|
||||
clientHeight: 500,
|
||||
maxScrollTop: 430,
|
||||
});
|
||||
coordinator.updateTurn({
|
||||
id: "turn-1",
|
||||
promptId: "prompt-1",
|
||||
hasOutput: false,
|
||||
});
|
||||
advanceFrame();
|
||||
expect(camera.jumpTo).toHaveBeenLastCalledWith(430);
|
||||
|
||||
setGeometry({
|
||||
composerHeight: 148,
|
||||
scrollHeight: 958,
|
||||
promptTop: 404,
|
||||
});
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
|
||||
expect(camera.jumpTo.mock.calls).toEqual([[430], [458]]);
|
||||
expect(camera.followTo).not.toHaveBeenCalled();
|
||||
expect(coordinator.snapshot().mode).toBe("anchor-prompt");
|
||||
|
||||
setGeometry({
|
||||
scrollTop: 458,
|
||||
scrollHeight: 990,
|
||||
});
|
||||
coordinator.invalidateGeometry();
|
||||
advanceFrame();
|
||||
|
||||
expect(camera.jumpTo.mock.calls).toEqual([[430], [458], [490]]);
|
||||
});
|
||||
|
||||
it("retargets a prompt navigation from authoritative geometry without restarting the camera", () => {
|
||||
const { camera, coordinator, measure, setGeometry } = motionHarness();
|
||||
coordinator.navigateHistoryToPrompt("prompt-46");
|
||||
@@ -763,6 +357,7 @@ describe("ThreadMotionCoordinator", () => {
|
||||
setGeometry({ promptTop: 520 });
|
||||
coordinator.reconcileObservedGeometry();
|
||||
|
||||
expect(measure).toHaveBeenLastCalledWith("prompt-46", false);
|
||||
expect(camera.navigateTo).toHaveBeenLastCalledWith(520);
|
||||
expect(camera.cancel).not.toHaveBeenCalled();
|
||||
expect(coordinator.snapshot().mode).toBe("navigating-history");
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user