feat(chat): follow the newest message in the conversation
一些检测仍在等待运行
ci / Portable quality checks (push) Waiting to run
ci / Windows Tauri build (push) Waiting to run

The message list had no scroll code at all. Opening a conversation
landed at the top of the history, and every message sent or received
appeared below the fold, so reading a reply meant scrolling down by
hand each time.

Scroll to the tail when the rendered messages change and when the slot
or session changes. Following stops as soon as the reader scrolls more
than 80px away from the bottom and resumes when they return, so reading
back through history is not interrupted by an arriving delta.

scrollTo carries the smooth behaviour but is not universally available —
jsdom has none — so it falls back to assigning scrollTop.

Refs: F-44 (audit P2-28).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
这个提交存在于:
YokiiroBW 2026-07-27 02:21:30 +08:00
父节点 3a221a22d6
当前提交 529357523c
共有 2 个文件被更改,包括 84 次插入 和 0 次删除

查看文件

@ -136,6 +136,44 @@ it("releases every listener on unmount", async () => {
});
});
it("follows the newest message, and stops once the reader scrolls up", async () => {
// jsdom has no scrollTo, which is also why the component falls back to
// scrollTop. Install a spy so the intent is observable either way.
const scrollTo = vi.fn();
Object.defineProperty(Element.prototype, "scrollTo", {
configurable: true,
writable: true,
value: scrollTo,
});
render(<ChatPanel fixedSlot="companion" />);
await flushListen();
scrollTo.mockClear();
emitTauriEvent("connection-runtime-event", deltaEvent("第一段"));
await waitFor(() => expect(scrollTo).toHaveBeenCalled());
// Scrolling away from the bottom must stop the view from being yanked back.
const list = document.querySelector(".chat-message-list") as HTMLElement;
Object.defineProperty(list, "scrollHeight", {
value: 1000,
configurable: true,
});
Object.defineProperty(list, "clientHeight", {
value: 200,
configurable: true,
});
list.scrollTop = 0;
fireEvent.scroll(list);
scrollTo.mockClear();
emitTauriEvent("connection-runtime-event", deltaEvent("第二段"));
await waitFor(() => expect(screen.getByText(/第二段/)).toBeInTheDocument());
expect(scrollTo).not.toHaveBeenCalled();
delete (Element.prototype as unknown as Record<string, unknown>).scrollTo;
});
it("keeps drafts on the slot they were typed in", async () => {
await renderWithTabs();

查看文件

@ -102,6 +102,13 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
companion: false,
operations: false,
});
const messageListRef = useRef<HTMLDivElement | null>(null);
/// Whether the view should follow new content.
///
/// Starts true so opening a conversation lands on the newest message, and
/// stays true until the reader scrolls up — following unconditionally would
/// yank someone out of the history they were reading.
const followTail = useRef(true);
const speechRecognition = useRef<{
start: () => void;
stop: () => void;
@ -164,6 +171,38 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
setSlotError((current) => ({ ...current, [slot]: message }));
};
/// Distance from the bottom that still counts as "reading the newest".
const TAIL_THRESHOLD_PX = 80;
const scrollToTail = useCallback((behavior: ScrollBehavior) => {
const list = messageListRef.current;
if (!list) return;
// `scrollTo` carries the smooth behaviour, but it is not universally
// available — jsdom has no implementation at all — so fall back to the
// property, which every engine supports.
if (typeof list.scrollTo === "function") {
list.scrollTo({ top: list.scrollHeight, behavior });
} else {
list.scrollTop = list.scrollHeight;
}
}, []);
// Follow the tail whenever the rendered messages change: a sent message, a
// streamed delta, or a freshly loaded history. The list had no scroll code at
// all, so every send left the new message below the fold.
useEffect(() => {
if (!followTail.current) return;
scrollToTail("smooth");
}, [visibleMessages, scrollToTail]);
// Opening a conversation, or switching slot or session, starts at the newest
// message rather than at the top.
useEffect(() => {
followTail.current = true;
const frame = window.requestAnimationFrame(() => scrollToTail("auto"));
return () => window.cancelAnimationFrame(frame);
}, [selectedSlot, historySessionId, scrollToTail]);
useEffect(() => {
// `listen()` resolves after the effect may already have been cleaned up.
// Assigning the unregister function unconditionally dropped it in that
@ -761,6 +800,13 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
<div
id={`chat-panel-${selectedSlot}`}
className="chat-message-list"
ref={messageListRef}
onScroll={(event) => {
const list = event.currentTarget;
const distanceFromTail =
list.scrollHeight - list.scrollTop - list.clientHeight;
followTail.current = distanceFromTail <= TAIL_THRESHOLD_PX;
}}
role="tabpanel"
aria-label={`${selectedSlot} messages`}
aria-busy={sending[selectedSlot]}