fix(web): 回答从开头开始读,两个会话面同一套钉顶跟随
Independent Staging Quality Gate / validate (push) Failing after 6m26s
Independent Staging Quality Gate / publish (push) Skipped

This commit is contained in:
jesse-ux
2026-09-17 21:47:54 +08:00
parent e4e73f56c0
commit 11c0028d59
15 changed files with 460 additions and 27 deletions
+1 -1
View File
@@ -783,7 +783,7 @@ export default function Home() {
});
const jumpToLatestVisible = !rectificationSurfaceOpen
&& !starterHomeVisible
&& !conversationAnchor.anchored
&& conversationAnchor.latestBelowFold
&& Boolean(activeSession?.messages.length);
function setDraft(value: string) {
+5
View File
@@ -1127,6 +1127,11 @@ button:disabled { cursor: default; opacity: .45; }
.message-content { min-width: 0; max-width: min(80%, 680px); }
.message-bubble { overflow: hidden; border: 0; padding: var(--space-3) var(--space-4); border-radius: var(--radius-lg); background: var(--color-canvas-muted); }
.message-assistant .message-bubble { border-radius: 0; background: transparent; padding: var(--space-3) 0; }
/* Last turn fills the remaining viewport so a short reply can still pin its
head at the top. Variables are written by useConversationScrollAnchor. */
.conversation .message-list > :last-child .message-assistant {
min-height: calc(var(--conversation-viewport, 0px) - var(--latest-turn-head-height, 0px));
}
.message-thinking {
margin: 0 0 var(--space-3);
}
@@ -464,8 +464,7 @@ export function RectificationAgenticChat(props: RectificationAgenticChatProps) {
const boardId = useId();
const boardTitleId = useId();
const composerRemainingId = useId();
// The same anchor-and-follow the consultation surface uses: streamed tokens and
// new cards land the viewport on the bottom only while the reader is there.
// Same pin-the-turn-head hook as the consultation surface (BUG-930).
const conversationAnchor = useConversationScrollAnchor(conversation, true, caseId);
useLayoutEffect(() => {
@@ -717,6 +716,7 @@ export function RectificationAgenticChat(props: RectificationAgenticChatProps) {
: []),
liveRow,
]));
if (!continuation) conversationAnchor.pinLatestTurn();
let raw = "";
let runOutcome: "succeeded" | "stopped" | "failed" = "failed";
let activityTrace: readonly AgentActivityTraceItem[] = emptyActivityTrace();
@@ -1079,6 +1079,7 @@ export function RectificationAgenticChat(props: RectificationAgenticChatProps) {
},
},
]);
conversationAnchor.pinLatestTurn();
setPending(true);
const abortController = new AbortController();
runAbort.current = abortController;
@@ -1231,6 +1232,7 @@ export function RectificationAgenticChat(props: RectificationAgenticChatProps) {
activity: { phase: "evidence-validation", label: adoptingLabel, startedAt: Date.now() },
},
]);
conversationAnchor.pinLatestTurn();
const abortController = new AbortController();
runAbort.current = abortController;
try {
@@ -1812,7 +1814,7 @@ export function RectificationAgenticChat(props: RectificationAgenticChatProps) {
</section>
<div className="composer-wrap">
{!conversationAnchor.anchored && (
{conversationAnchor.latestBelowFold && (
<JumpToLatestButton onClick={conversationAnchor.anchorToLatest} />
)}
<ChatComposer
+3 -1
View File
@@ -86,7 +86,9 @@ import type { PublicLanguageModelCatalog } from "@/lib/public-models";
type ConversationAnchor = {
readonly anchored: boolean;
readonly latestBelowFold: boolean;
readonly anchorToLatest: () => void;
readonly pinLatestTurn: (target?: HTMLElement) => void;
};
export type ConsultationRunParams = {
@@ -657,7 +659,7 @@ export function useConsultationRun(params: ConsultationRunParams) {
}
setOnboardingJustCompleted(false);
updateSession(sessionId, () => userSession);
conversationAnchor.anchorToLatest();
conversationAnchor.pinLatestTurn();
setDraft("");
setDraftTheme(null);
setDraftEntrypoint(null);
@@ -4,6 +4,8 @@ import { useEffect, useRef, useState } from "react";
import type { RefObject } from "react";
export const conversationAnchorThreshold = 96;
export const conversationPinSpaceToken = "--space-4";
const pinSpaceFallbackPx = 16;
type AnchorState = {
readonly key: string;
@@ -12,7 +14,9 @@ type AnchorState = {
type ConversationScrollAnchor = {
readonly anchored: boolean;
readonly latestBelowFold: boolean;
readonly anchorToLatest: () => void;
readonly pinLatestTurn: (target?: HTMLElement) => void;
};
export function conversationDistanceFromBottom(container: HTMLElement) {
@@ -24,28 +28,114 @@ export function nextAnchorState(anchored: boolean, distanceFromBottom: number, s
return scrolledUp ? false : anchored;
}
export function readPinSpacePx(element: HTMLElement): number {
if (typeof getComputedStyle !== "function") return pinSpaceFallbackPx;
const raw = getComputedStyle(element).getPropertyValue(conversationPinSpaceToken).trim();
const parsed = Number.parseFloat(raw);
return Number.isFinite(parsed) ? parsed : pinSpaceFallbackPx;
}
const DOCUMENT_POSITION_FOLLOWING = 4;
export function isNodeAfter(earlier: Node, later: Node): boolean {
if (typeof earlier.compareDocumentPosition !== "function") return false;
return (earlier.compareDocumentPosition(later) & DOCUMENT_POSITION_FOLLOWING) !== 0;
}
/**
* Turn head is the latest user row, unless an assistant sits after it with
* another assistant in between (choice / opening / auto-continue: this turn
* has no user row) or there is no user row at all.
*/
export function resolveTurnHead(container: ParentNode, target?: HTMLElement | null): HTMLElement | null {
if (target) return target;
const users = Array.from(container.querySelectorAll(".message-user")) as HTMLElement[];
const assistants = Array.from(container.querySelectorAll(".message-assistant")) as HTMLElement[];
const lastUser = users.at(-1) ?? null;
const lastAssistant = assistants.at(-1) ?? null;
if (!lastUser) return lastAssistant;
if (!lastAssistant) return lastUser;
if (!isNodeAfter(lastUser, lastAssistant)) return lastUser;
const between = assistants.some((row) => isNodeAfter(lastUser, row) && isNodeAfter(row, lastAssistant));
return between ? lastAssistant : lastUser;
}
export function offsetWithinScroller(scroller: HTMLElement, node: HTMLElement): number {
return node.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop;
}
export function pinTurnScrollTop(scroller: HTMLElement, row: HTMLElement, spacePx: number): number {
return Math.max(0, offsetWithinScroller(scroller, row) - spacePx);
}
export function applyFollowBottom(
element: { scrollTop: number; scrollHeight: number },
anchored: boolean,
): void {
if (!anchored) return;
element.scrollTop = element.scrollHeight;
}
export function applyTurnSpacer(container: HTMLElement, head: HTMLElement | null): void {
container.style.setProperty("--conversation-viewport", `${container.clientHeight}px`);
container.style.setProperty("--latest-turn-head-height", `${head?.offsetHeight ?? 0}px`);
}
export function clearTurnSpacer(container: HTMLElement): void {
container.style.removeProperty("--conversation-viewport");
container.style.removeProperty("--latest-turn-head-height");
}
export function lastTurnTail(container: HTMLElement): HTMLElement | null {
return (container.querySelector(".message-list > :last-child .message-assistant")
?? container.querySelector(".message-assistant:last-of-type")
?? container.querySelector(".message-user:last-of-type")) as HTMLElement | null;
}
export function turnTailOverflow(container: HTMLElement): number {
const last = lastTurnTail(container);
if (!last) return conversationDistanceFromBottom(container);
return last.offsetTop + last.offsetHeight - (container.scrollTop + container.clientHeight);
}
export function latestContentBelowFold(overflow: number): boolean {
return overflow > conversationAnchorThreshold;
}
/**
* Owns both halves of "follow the conversation": whether the reader is
* anchored to the bottom (a scroll listener), and landing the viewport on the
* newest content while they are (a resize observer over the scroller's
* children, one frame per change). Both chat surfaces use this one hook, so
* streamed tokens never call scrollTo directly and settlement never adds a
* second, smooth scroll on top of the follow.
* children, one frame per change). Both chat surfaces use this one hook.
*
* A new turn pins its head (the user row, or the new assistant when this turn
* has no user row) at the top and does not follow streamed growth. Switching
* conversations still lands on the newest content once.
*/
export function useConversationScrollAnchor(
container: RefObject<HTMLElement | null>,
active: boolean,
resetKey: string,
): ConversationScrollAnchor {
const [anchor, setAnchor] = useState<AnchorState>({ key: resetKey, anchored: true });
const [anchor, setAnchor] = useState<AnchorState>({ key: resetKey, anchored: false });
const [latestBelowFold, setLatestBelowFold] = useState(false);
const lastScrollTop = useRef(0);
const anchoredRef = useRef(true);
const anchoredRef = useRef(false);
const shouldLand = useRef(true);
const holdUnpin = useRef(false);
const pinnedHeadRef = useRef<HTMLElement | null>(null);
const anchored = anchor.key === resetKey ? anchor.anchored : true;
useEffect(() => {
anchoredRef.current = anchored;
}, [anchored]);
useEffect(() => {
shouldLand.current = true;
holdUnpin.current = false;
pinnedHeadRef.current = null;
}, [resetKey]);
useEffect(() => {
const element = container.current;
if (!active || !element) return;
@@ -53,9 +143,20 @@ export function useConversationScrollAnchor(
let frame = 0;
const measure = () => {
frame = 0;
const overflow = turnTailOverflow(element);
const distance = conversationDistanceFromBottom(element);
const scrolledUp = element.scrollTop < lastScrollTop.current;
lastScrollTop.current = element.scrollTop;
setLatestBelowFold(latestContentBelowFold(overflow));
if (holdUnpin.current) {
if (scrolledUp) {
holdUnpin.current = false;
} else if (distance <= conversationAnchorThreshold) {
holdUnpin.current = false;
} else {
return;
}
}
setAnchor((current) => {
const currentAnchored = current.key === resetKey ? current.anchored : true;
const next = nextAnchorState(currentAnchored, distance, scrolledUp);
@@ -76,15 +177,31 @@ export function useConversationScrollAnchor(
// Follow: while anchored, any change in the scroller's content height lands the
// viewport on the bottom, at most once per frame. Switching conversations
// (resetKey) lands there immediately.
// (resetKey) lands there immediately. Unanchored turns only refresh the spacer.
useEffect(() => {
const element = container.current;
if (!active || !element) return;
let frame = 0;
const follow = () => {
frame = 0;
if (!anchoredRef.current) return;
element.scrollTop = element.scrollHeight;
if (shouldLand.current) {
element.scrollTop = element.scrollHeight;
shouldLand.current = false;
holdUnpin.current = false;
pinnedHeadRef.current = null;
clearTurnSpacer(element);
const atBottom = conversationDistanceFromBottom(element) <= conversationAnchorThreshold;
anchoredRef.current = atBottom;
setAnchor({ key: resetKey, anchored: atBottom });
setLatestBelowFold(false);
return;
}
if (anchoredRef.current) {
element.scrollTop = element.scrollHeight;
} else {
applyTurnSpacer(element, pinnedHeadRef.current ?? resolveTurnHead(element));
}
setLatestBelowFold(latestContentBelowFold(turnTailOverflow(element)));
};
const requestFollow = () => {
if (frame) return;
@@ -118,13 +235,45 @@ export function useConversationScrollAnchor(
return {
anchored,
latestBelowFold,
anchorToLatest: () => {
const element = container.current;
holdUnpin.current = false;
shouldLand.current = false;
if (element) {
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
element.scrollTo({ top: element.scrollHeight, behavior: reduceMotion ? "auto" : "smooth" });
setLatestBelowFold(false);
}
setAnchor({ key: resetKey, anchored: true });
},
pinLatestTurn: (target?: HTMLElement) => {
const element = container.current;
const run = () => {
shouldLand.current = false;
holdUnpin.current = true;
anchoredRef.current = false;
if (!element) {
setAnchor({ key: resetKey, anchored: false });
setLatestBelowFold(false);
return;
}
const head = resolveTurnHead(element, target);
pinnedHeadRef.current = head;
applyTurnSpacer(element, head);
const space = readPinSpacePx(element);
const top = head ? pinTurnScrollTop(element, head, space) : 0;
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
element.scrollTo({ top, behavior: reduceMotion ? "auto" : "smooth" });
lastScrollTop.current = element.scrollTop;
setAnchor({ key: resetKey, anchored: false });
setLatestBelowFold(latestContentBelowFold(turnTailOverflow(element)));
};
if (typeof window === "undefined") {
run();
return;
}
window.requestAnimationFrame(run);
},
};
}