Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(chat): prefetch adjacent sessions and smooth archive-advance transitions (MUL-9881) (#11215)
Jiayuan Zhang5941cd0502b4
diff --git a/packages/core/chat/queries.test.ts b/packages/core/chat/queries.test.tsindex 0b94be88ca..27e11071cf 100644--- a/packages/core/chat/queries.test.ts+++ b/packages/core/chat/queries.test.ts@@ -1,12 +1,17 @@// @vitest-environment node-import { describe, expect, it } from "vitest";+import { QueryClient } from "@tanstack/react-query";+import { afterEach, describe, expect, it, vi } from "vitest";+import { setApiInstance } from "../api";+import type { ApiClient } from "../api/client";import type { TaskMessagePayload } from "../types/events";-import type { ChatSession } from "../types/chat";+import type { ChatMessage, ChatSession } from "../types/chat";import {+ chatKeys,countUnreadChatSessions,isTaskMessageTaskId,mergeTaskMessagesBySeq,+ prefetchChatSession,sortChatSessions,taskMessagesOptions,unionTaskMessagesBySeq,@@ -200,3 +205,72 @@ describe("countUnreadChatSessions", () => {expect(countUnreadChatSessions(sessions)).toBe(0);});});++describe("prefetchChatSession", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ const makeMessage = (over: Partial<ChatMessage> & Pick<ChatMessage, "id">): ChatMessage => ({+ chat_session_id: "s-1",+ role: "assistant",+ content: "reply",+ task_id: null,+ created_at: "2026-01-01T00:00:00Z",+ ...over,+ });++ it("warms messages, pending task, wakeups, and up to two tail assistant timelines", async () => {+ const t1 = "11111111-1111-4111-8111-111111111111";+ const t2 = "22222222-2222-4222-8222-222222222222";+ const t3 = "33333333-3333-4333-8333-333333333333";++ const listMessages = vi.fn(async () => ({+ messages: [+ makeMessage({ id: "m1", role: "assistant", task_id: t1 }),+ makeMessage({ id: "m2", role: "user", task_id: t1 }),+ makeMessage({ id: "m3", role: "assistant", task_id: t2 }),+ makeMessage({ id: "m4", role: "assistant", task_id: "optimistic-1" }),+ makeMessage({ id: "m5", role: "assistant", task_id: t3 }),+ ],+ limit: 50,+ has_more: false,+ next_cursor: null,+ }));+ const getPending = vi.fn(async (_sessionId: string) => ({}));+ const listWakeups = vi.fn(async (_sessionId: string) => []);+ const listTaskMessages = vi.fn(async (_taskId: string) => []);+ setApiInstance({+ listChatMessagesPage: listMessages,+ getPendingChatTask: getPending,+ listChatSessionWakeups: listWakeups,+ listTaskMessages,+ } as unknown as ApiClient);++ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ await prefetchChatSession(qc, "s-1");++ expect(listMessages).toHaveBeenCalledTimes(1);+ expect(getPending).toHaveBeenCalledWith("s-1");+ expect(listWakeups).toHaveBeenCalledWith("s-1");+ // Only the newest two valid UUID assistant task timelines are warmed.+ expect(listTaskMessages.mock.calls.map(([id]) => id)).toEqual([t3, t2]);+ expect(qc.getQueryData(chatKeys.pendingTask("s-1"))).toEqual({});+ expect(qc.getQueryData(chatKeys.wakeups("s-1"))).toEqual([]);++ // Second call hits the Infinity-staleTime cache without refetching.+ await prefetchChatSession(qc, "s-1");+ expect(listMessages).toHaveBeenCalledTimes(1);+ expect(getPending).toHaveBeenCalledTimes(1);+ expect(listWakeups).toHaveBeenCalledTimes(1);+ expect(listTaskMessages).toHaveBeenCalledTimes(2);+ });++ it("is a no-op for an empty session id", async () => {+ const listMessages = vi.fn();+ setApiInstance({ listChatMessagesPage: listMessages } as unknown as ApiClient);+ const qc = new QueryClient();+ await prefetchChatSession(qc, "");+ expect(listMessages).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.tsindex 8dc0489cbd..4c8db7008b 100644--- a/packages/core/chat/queries.ts+++ b/packages/core/chat/queries.ts@@ -1,8 +1,15 @@-import { infiniteQueryOptions, queryOptions, useQuery, type QueryClient } from "@tanstack/react-query";+import {+ infiniteQueryOptions,+ queryOptions,+ useQuery,+ type InfiniteData,+ type QueryClient,+} from "@tanstack/react-query";import { useEffect, useRef } from "react";import { api } from "../api";import type { TaskMessagePayload } from "../types/events";import type {+ ChatMessagesPage,ChatQuickActionsFailureState,ChatQuickActionsPendingState,ChatSession,@@ -208,6 +215,50 @@ export function chatWakeupsOptions(sessionId: string) {});}+/**+ * How many trailing assistant turns' task timelines to warm after prefetching+ * a session's newest message page. Keeps the visible tail from expanding+ * asynchronously when `AssistantMessage` upgrades from plain text to its+ * collapsible `TimelineView`, while capping cache entries for MUL-6396.+ */+const PREFETCH_TAIL_TASK_LIMIT = 2;++/**+ * Warms a chat session's conversation queries in parallel so archiving and+ * advancing to the next thread — or clicking an adjacent row — renders from+ * cache without flashing the skeleton or asynchronously popping in bottom+ * strips (wakeups). All warmed queries use `staleTime: Infinity`, so an+ * already-warm session costs nothing.+ */+export async function prefetchChatSession(+ qc: QueryClient,+ sessionId: string,+): Promise<void> {+ if (!sessionId) return;+ await Promise.all([+ qc.prefetchInfiniteQuery(chatMessagesPageOptions(sessionId)),+ qc.prefetchQuery(pendingChatTaskOptions(sessionId)),+ qc.prefetchQuery(chatWakeupsOptions(sessionId)),+ ]);++ const newestMessages =+ qc.getQueryData<InfiniteData<ChatMessagesPage>>(chatKeys.messagesPage(sessionId))+ ?.pages?.[0]?.messages ?? [];+ const tailTaskIds: string[] = [];+ const seen = new Set<string>();+ for (let i = newestMessages.length - 1; i >= 0 && tailTaskIds.length < PREFETCH_TAIL_TASK_LIMIT; i--) {+ const m = newestMessages[i];+ if (!m || m.role !== "assistant" || !isTaskMessageTaskId(m.task_id) || seen.has(m.task_id)) {+ continue;+ }+ seen.add(m.task_id);+ tailTaskIds.push(m.task_id);+ }+ if (tailTaskIds.length > 0) {+ await Promise.all(tailTaskIds.map((taskId) => qc.prefetchQuery(taskMessagesOptions(taskId))));+ }+}+export function myChatWakeupsOptions(wsId: string) {return queryOptions({queryKey: chatKeys.myWakeups(wsId),diff --git a/packages/ui/styles/base.css b/packages/ui/styles/base.cssindex 6d1c088d61..ca1197d723 100644--- a/packages/ui/styles/base.css+++ b/packages/ui/styles/base.css@@ -208,6 +208,62 @@}}+/* Chat session switch / archive-advance message transition (MUL-9881).+ * Plays once the virtualized list has landed on its live end (`hasReachedLiveEnd`),+ * so the reader never sees Virtuoso's unmeasured scroll jump. `backwards`+ * releases `transform` on finish so sticky/fixed descendants keep their normal+ * containing block. */+@keyframes chat-enter-next {+ from {+ opacity: 0;+ transform: translateY(10px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+}++@keyframes chat-enter-prev {+ from {+ opacity: 0;+ transform: translateY(-10px);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+}++@keyframes chat-enter-fade {+ from {+ opacity: 0;+ }+ to {+ opacity: 1;+ }+}++.animate-chat-enter-next {+ animation: chat-enter-next 160ms cubic-bezier(0.23, 1, 0.32, 1) backwards;+}++.animate-chat-enter-prev {+ animation: chat-enter-prev 160ms cubic-bezier(0.23, 1, 0.32, 1) backwards;+}++.animate-chat-enter-fade {+ animation: chat-enter-fade 130ms ease-out backwards;+}++@media (prefers-reduced-motion: reduce) {+ .animate-chat-enter-next,+ .animate-chat-enter-prev {+ animation-name: chat-enter-fade;+ animation-duration: 120ms;+ }+}+/* Chat FAB: gentle color + border tint while a chat task is running.* Keeps the ring at the same thickness — only hue shifts towards brand* at half-cycle, no outer glow. */diff --git a/packages/views/chat/chat-page.test.tsx b/packages/views/chat/chat-page.test.tsxindex 8e845d4f6a..203938d56c 100644--- a/packages/views/chat/chat-page.test.tsx+++ b/packages/views/chat/chat-page.test.tsx@@ -15,13 +15,50 @@ import {const TEST_RESOURCES = { en: { common: enCommon, chat: enChat } };+const lastMessageListProps = vi.hoisted(() => ({+ current: null as null | { revealKey?: string | null; enterTransition?: string | null },+}));+const mockArchiveOutcome = vi.hoisted(() => ({+ current: { moved: false } as+ | { moved: false }+ | { moved: true; targetSessionId: string; direction: "next" | "prev" }+ | { moved: true; targetSessionId: null; direction: null },+}));+const mockHasMessages = vi.hoisted(() => ({ current: false }));+const mockAdvanceSelectionAfterArchive = vi.hoisted(() =>+ vi.fn(() => {+ const outcome = mockArchiveOutcome.current;+ if (outcome.moved) mockSetActiveSession(outcome.targetSessionId);+ return outcome;+ }),+);+const mockArchiveSession = vi.hoisted(() => vi.fn());+const mockSelectSession = vi.hoisted(() => vi.fn());+// These tests target the page-level URL wiring (`?agent=` / `?session=`), so// the conversation internals are stubbed and the controller is replaced with// a ref-driven fake the tests can steer. The thread-list stub stays// interactive: selecting a thread is the user action that must supersede a// pending `?agent=` intent.vi.mock("./components/chat-message-list", () => ({- ChatMessageList: () => <div>chat-message-list</div>,+ ChatMessageList: ({+ revealKey,+ enterTransition,+ }: {+ revealKey?: string | null;+ enterTransition?: string | null;+ }) => {+ lastMessageListProps.current = { revealKey, enterTransition };+ return (+ <div+ data-testid="chat-message-list"+ data-reveal-key={revealKey ?? ""}+ data-enter-transition={enterTransition ?? ""}+ >+ chat-message-list+ </div>+ );+ },ChatMessageSkeleton: () => <div>chat-message-skeleton</div>,}));vi.mock("./components/chat-input", () => ({@@ -29,20 +66,53 @@ vi.mock("./components/chat-input", () => ({}));vi.mock("./components/chat-thread-list", () => ({ChatThreadList: ({+ activeSessionId,onSelectSession,+ onArchive,}: {+ activeSessionId: string | null;onSelectSession: (s: { id: string; agent_id: string }) => void;+ onArchive: (s: { id: string; agent_id: string }) => void;}) => (- <button- type="button"- onClick={() => onSelectSession({ id: "session-9", agent_id: "agent-9" })}- >- select-thread- </button>+ <div>+ <button+ type="button"+ onClick={() => onSelectSession({ id: "session-9", agent_id: "agent-9" })}+ >+ select-thread+ </button>+ <button+ type="button"+ onClick={() =>+ onArchive({ id: activeSessionId ?? "session-1", agent_id: "agent-1" })+ }+ >+ archive-active-thread+ </button>+ </div>),}));+const mockCurrentSession = vi.hoisted(() => ({+ current: null as { id: string; agent_id: string } | null,+}));+vi.mock("./components/chat-session-header", () => ({- ChatSessionHeader: () => <div>chat-session-header</div>,+ ChatSessionHeader: ({+ session,+ onArchive,+ }: {+ session: { id: string; agent_id: string };+ onArchive?: (s: { id: string; agent_id: string }) => void;+ }) => (+ <div>+ <span>chat-session-header</span>+ {onArchive && (+ <button type="button" onClick={() => onArchive(session)}>+ archive-from-header+ </button>+ )}+ </div>+ ),}));vi.mock("./components/chat-wakeups", () => ({ChatWakeupStrip: () => null,@@ -144,7 +214,7 @@ vi.mock("./components/use-chat-controller", async () => {() => storeRef.current,).activeSessionId,selectedAgentId: null,- currentSession: null,+ currentSession: mockCurrentSession.current,isSessionArchived: false,isAgentArchived: false,isAgentRuntimeBound: true,@@ -155,7 +225,7 @@ vi.mock("./components/use-chat-controller", async () => {pendingTask: null,pendingTaskId: null,showSkeleton: false,- hasMessages: false,+ hasMessages: mockHasMessages.current,firstItemIndex: 0,hasOlderMessages: false,isFetchingOlderMessages: false,@@ -168,9 +238,9 @@ vi.mock("./components/use-chat-controller", async () => {handleUploadFile: vi.fn(),handleNewChat: vi.fn(),handleStartNewChat: mockStartNewChat,- handleSelectSession: vi.fn(),- advanceSelectionAfterArchive: vi.fn(),- archiveSession: vi.fn(),+ handleSelectSession: mockSelectSession,+ advanceSelectionAfterArchive: mockAdvanceSelectionAfterArchive,+ archiveSession: mockArchiveSession,setActiveSession: mockSetActiveSession,setSelectedAgentId: vi.fn(),}),@@ -259,6 +329,10 @@ beforeEach(() => {agentsSettledRef.current = true;platformWorkspace.slug = "acme";layout.width = DESKTOP;+ lastMessageListProps.current = null;+ mockArchiveOutcome.current = { moved: false };+ mockHasMessages.current = false;+ mockCurrentSession.current = null;});describe("ChatPage URL synchronization", () => {@@ -495,3 +569,97 @@ describe("ChatPage responsive layout", () => {expect(screen.getByText("chat-input")).toBeInTheDocument();});});++describe("ChatPage archive and session transitions", () => {+ it("opens an initial deep-linked session with revealKey and no directional transition", () => {+ mockHasMessages.current = true;+ storeRef.current = { activeSessionId: "session-1" };+ renderPage("session=session-1");++ const list = screen.getByTestId("chat-message-list");+ expect(list).toHaveAttribute("data-reveal-key", "session-1");+ expect(list).toHaveAttribute("data-enter-transition", "");+ });++ it("applies the 'next' transition when archiving advances to the following thread", () => {+ mockHasMessages.current = true;+ storeRef.current = { activeSessionId: "session-1" };+ mockArchiveOutcome.current = {+ moved: true,+ targetSessionId: "session-2",+ direction: "next",+ };+ renderPage("session=session-1");++ fireEvent.click(screen.getByRole("button", { name: "archive-active-thread" }));++ expect(mockAdvanceSelectionAfterArchive).toHaveBeenCalledTimes(1);+ expect(mockArchiveSession).toHaveBeenCalledWith("session-1");+ const list = screen.getByTestId("chat-message-list");+ expect(list).toHaveAttribute("data-reveal-key", "session-2");+ expect(list).toHaveAttribute("data-enter-transition", "next");+ });++ it("applies the 'prev' transition when archiving the last thread falls back upward", () => {+ mockHasMessages.current = true;+ storeRef.current = { activeSessionId: "session-3" };+ mockArchiveOutcome.current = {+ moved: true,+ targetSessionId: "session-2",+ direction: "prev",+ };+ renderPage("session=session-3");++ fireEvent.click(screen.getByRole("button", { name: "archive-active-thread" }));++ const list = screen.getByTestId("chat-message-list");+ expect(list).toHaveAttribute("data-reveal-key", "session-2");+ expect(list).toHaveAttribute("data-enter-transition", "prev");+ });++ it("fades in the neutral select prompt when archiving the only thread on desktop", () => {+ mockHasMessages.current = true;+ storeRef.current = { activeSessionId: "session-only" };+ mockArchiveOutcome.current = {+ moved: true,+ targetSessionId: null,+ direction: null,+ };+ renderPage("session=session-only");++ fireEvent.click(screen.getByRole("button", { name: "archive-active-thread" }));++ const prompt = screen.getByText("Pick a conversation, or start a new one with +");+ expect(prompt.parentElement?.className).toContain("animate-chat-enter-fade");+ });++ it("applies a gentle fade when selecting another thread directly", () => {+ mockHasMessages.current = true;+ storeRef.current = { activeSessionId: "session-1" };+ mockSelectSession.mockImplementationOnce((s: { id: string }) => {+ mockSetActiveSession(s.id);+ });+ renderPage("session=session-1");++ fireEvent.click(screen.getByRole("button", { name: "select-thread" }));++ const list = screen.getByTestId("chat-message-list");+ expect(list).toHaveAttribute("data-reveal-key", "session-9");+ expect(list).toHaveAttribute("data-enter-transition", "fade");+ });++ it("returns to the thread list without advancing when archiving in compact layout", () => {+ layout.width = FOLD_INNER_PORTRAIT;+ mockHasMessages.current = true;+ mockCurrentSession.current = { id: "session-1", agent_id: "agent-1" };+ storeRef.current = { activeSessionId: "session-1" };+ renderPage("session=session-1");++ fireEvent.click(screen.getByRole("button", { name: "archive-from-header" }));++ expect(mockSetActiveSession).toHaveBeenCalledWith(null);+ expect(mockArchiveSession).toHaveBeenCalledWith("session-1");+ expect(mockAdvanceSelectionAfterArchive).not.toHaveBeenCalled();+ expect(screen.getByRole("button", { name: "select-thread" })).toBeInTheDocument();+ });+});diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsxindex 9cf423c9c8..3fa52ca6f4 100644--- a/packages/views/chat/chat-page.tsx+++ b/packages/views/chat/chat-page.tsx@@ -1,11 +1,15 @@"use client";-import { useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { AnimatePresence, motion } from "motion/react";import { ArrowLeft, Bot, MessageSquare, Plus } from "@multica/ui/icons";import { toast } from "sonner";import { Button } from "@multica/ui/components/ui/button";import { IconButton } from "@multica/ui/components/common/icon-button";import { useIsCompact } from "@multica/ui/hooks/use-mobile";+import { UI_EASE_OUT, UI_MOTION_DURATION } from "@multica/ui/lib/motion";+import { cn } from "@multica/ui/lib/utils";+import { useReducedMotion } from "@multica/core/appearance";import { useRequiredWorkspaceSlug, useWorkspacePaths } from "@multica/core/paths";import { getCurrentSlug } from "@multica/core/platform";import { useChatStore } from "@multica/core/chat";@@ -22,7 +26,11 @@ import { useListColumnCollapsed } from "../layout/app-shell-context";import { ListColumn } from "../layout/list-column";import { useNavigation } from "../navigation";import { useT } from "../i18n";-import { ChatMessageList, ChatMessageSkeleton } from "./components/chat-message-list";+import {+ ChatMessageList,+ ChatMessageSkeleton,+ type ChatMessageEnterTransition,+} from "./components/chat-message-list";import { ChatInput } from "./components/chat-input";import { ChatQueue } from "./components/chat-queue";import { ChatWakeupStrip, useChatWakeups } from "./components/chat-wakeups";@@ -32,6 +40,7 @@ import { EmptyState } from "./components/chat-empty-state";import { NewChatButton } from "./components/new-chat-button";import { useChatController } from "./components/use-chat-controller";import { useChatAnnotations } from "./components/use-chat-annotations";+import { useChatSessionPrefetch } from "./components/use-chat-session-prefetch";import { OfflineBanner } from "./components/offline-banner";import { NoAgentBanner } from "./components/no-agent-banner";import { ArchivedAgentBanner } from "./components/archived-agent-banner";@@ -40,6 +49,47 @@ import { RuntimeRequiredBanner } from "./components/runtime-required-banner";import { ChatAppRequests } from "../common/app-requests";import { useRegisterCommandBarContext } from "../search/register-context";+/**+ * Smoothly expands/collapses an optional status strip above the composer so+ * async or session-dependent banners do not snap the message viewport.+ * Keying on `slotKey` keeps height steady when two consecutive sessions both+ * show a banner in the same slot.+ */+function CollapsibleSlot({+ slotKey,+ visible,+ children,+}: {+ slotKey: string;+ visible: boolean;+ children: ReactNode;+}) {+ const reduceMotion = useReducedMotion();+ const duration = reduceMotion ? 0 : UI_MOTION_DURATION.fast;++ return (+ <AnimatePresence initial={false}>+ {visible && (+ <motion.div+ key={slotKey}+ data-slot={slotKey}+ initial={{ opacity: 0, height: 0, overflow: "hidden" }}+ animate={{+ opacity: 1,+ height: "auto",+ transitionEnd: { overflow: "visible" },+ }}+ exit={{ opacity: 0, height: 0, overflow: "hidden" }}+ transition={{ duration, ease: UI_EASE_OUT }}+ className="shrink-0"+ >+ {children}+ </motion.div>+ )}+ </AnimatePresence>+ );+}+/*** Chat tab — the first-class two-pane surface (thread list on the left,* conversation on the right), mirroring the Inbox page layout. Shares all@@ -71,9 +121,17 @@ export function ChatPage() {const isCurrentChatRoute = pathname === wsPaths.chat();const isCompact = useIsCompact();+ const isSurfaceActive = isCurrentChatRoute && getCurrentSlug() === workspaceSlug;const c = useChatController({- isActive: isCurrentChatRoute && getCurrentSlug() === workspaceSlug,+ isActive: isSurfaceActive,+ });+ const prefetchSession = useChatSessionPrefetch({+ wsId: c.wsId,+ sessions: c.sessions,+ activeSessionId: c.activeSessionId,+ isActive: isSurfaceActive,});+ const reduceMotion = useReducedMotion();const { data: quickActionsPending = null } = useQuery(chatQuickActionsPendingOptions(c.activeSessionId ?? ""),);@@ -151,8 +209,37 @@ export function ChatPage() {if (urlAgent) consumedAgentIntent.current = urlAgent;};+ // Directional hint for in-page session transitions: archiving the current+ // thread plays a subtle directional glide aligned with list order ("next" or+ // "prev"); direct clicks or URL switches use a gentle opacity fade. Initial+ // page load has no transition so first paint lands immediately.+ const [sessionTransition, setSessionTransition] = useState<{+ sessionId: string | null;+ direction: ChatMessageEnterTransition;+ } | null>(null);+ const [prevActiveSessionId, setPrevActiveSessionId] = useState<string | null>(+ c.activeSessionId,+ );+ if (c.activeSessionId !== prevActiveSessionId) {+ setPrevActiveSessionId(c.activeSessionId);+ if (+ prevActiveSessionId !== null &&+ c.activeSessionId !== null &&+ sessionTransition?.sessionId !== c.activeSessionId+ ) {+ setSessionTransition({ sessionId: c.activeSessionId, direction: "fade" });+ }+ }+ const activeTransition: ChatMessageEnterTransition | null =+ sessionTransition?.sessionId === c.activeSessionId+ ? sessionTransition.direction+ : null;+const handleSelect = (session: ChatSession) => {supersedeAgentIntent();+ if (session.id !== c.activeSessionId) {+ setSessionTransition({ sessionId: session.id, direction: "fade" });+ }c.handleSelectSession(session);setComposingNew(false);};@@ -166,10 +253,17 @@ export function ChatPage() {supersedeAgentIntent();if (session.id === c.activeSessionId) {if (isCompact) {+ setSessionTransition(null);c.setActiveSession(null);setComposingNew(false);} else {- c.advanceSelectionAfterArchive(session);+ const result = c.advanceSelectionAfterArchive(session);+ if (result?.moved) {+ setSessionTransition({+ sessionId: result.targetSessionId,+ direction: result.direction ?? "fade",+ });+ }}}c.archiveSession(session.id);@@ -179,6 +273,7 @@ export function ChatPage() {// A manual ⊕ pick outranks a pending deep link; when called FROM the// intent effect the ref is already set to this param, so this is a no-op.supersedeAgentIntent();+ setSessionTransition(null);if (agent) c.handleStartNewChat(agent);else c.handleNewChat();setComposingNew(true);@@ -272,6 +367,7 @@ export function ChatPage() {activeSessionId={c.activeSessionId}onSelectSession={handleSelect}onArchive={handleArchive}+ onPrefetchSession={prefetchSession}/></div>);@@ -294,6 +390,7 @@ export function ChatPage() {/>);const backToList = () => {+ setSessionTransition(null);c.setActiveSession(null);setComposingNew(false);};@@ -305,9 +402,34 @@ export function ChatPage() {// `@container`: the conversation column's gutter (CHAT_GUTTER) widens with// THIS pane, which the user resizes independently of the browser window.const queuedTasks = c.pendingTask?.queued_tasks ?? [];+ const statusBanner = c.isAgentAccessRevoked ? (+ <AgentAccessRevokedBanner agentName={c.activeAgent?.name} />+ ) : c.noAgent ? (+ <NoAgentBanner />+ ) : c.isAgentArchived ? (+ <ArchivedAgentBanner agentName={c.activeAgent?.name} />+ ) : !c.isAgentRuntimeBound && c.activeAgent ? (+ <RuntimeRequiredBanner+ agentId={c.activeAgent.id}+ agentName={c.activeAgent.name}+ />+ ) : c.availability === "offline" || c.availability === "unstable" ? (+ <OfflineBanner agentName={c.activeAgent?.name} availability={c.availability} />+ ) : null;+ const hasActiveWakeup =+ !!c.activeSessionId && wakeups.some((w) => w.status === "active");+ const emptyEnterClass = activeTransition+ ? reduceMotion+ ? "animate-chat-enter-fade"+ : activeTransition === "next"+ ? "animate-chat-enter-next"+ : activeTransition === "prev"+ ? "animate-chat-enter-prev"+ : "animate-chat-enter-fade"+ : undefined;const conversation = (<div className="flex flex-1 flex-col min-h-0 @container">- {c.currentSession && (+ {c.currentSession ? (<ChatSessionHeaderleading={compactConversation ? (@@ -327,12 +449,22 @@ export function ChatPage() {agent={c.activeAgent}onArchive={handleArchive}/>- )}+ ) : !isCompact && !listCollapsed && c.activeSessionId ? (+ // Keep the 48px header band reserved while the active session row+ // resolves from the sessions query so the message area never drops+ // down when metadata lands. When `listCollapsed` is true, the desktop+ // wrapper below already renders a 48px `<PageHeader>` above `conversation`.+ <PageHeader leading={false} className="bg-background">+ {null}+ </PageHeader>+ ) : null}{c.showSkeleton ? (<ChatMessageSkeleton />) : c.hasMessages ? (<ChatMessageListkey={c.activeSessionId}+ revealKey={c.activeSessionId}+ enterTransition={activeTransition}messages={c.messages}pendingTask={c.pendingTask}availability={c.availability}@@ -362,33 +494,29 @@ export function ChatPage() {wakeups={wakeups}/>) : (- <EmptyState- agent={c.activeAgent}- hasSessions={c.sessions.length > 0}- onPickPrompt={c.sendConversationStarter}- />+ <div+ key={c.activeSessionId ?? "new"}+ className={cn("flex min-h-0 flex-1 flex-col overflow-hidden", emptyEnterClass)}+ >+ <EmptyState+ agent={c.activeAgent}+ hasSessions={c.sessions.length > 0}+ onPickPrompt={c.sendConversationStarter}+ />+ </div>)}- {c.isAgentAccessRevoked ? (- <AgentAccessRevokedBanner agentName={c.activeAgent?.name} />- ) : c.noAgent ? (- <NoAgentBanner />- ) : c.isAgentArchived ? (- <ArchivedAgentBanner agentName={c.activeAgent?.name} />- ) : !c.isAgentRuntimeBound && c.activeAgent ? (- <RuntimeRequiredBanner- agentId={c.activeAgent.id}- agentName={c.activeAgent.name}- />- ) : (- <OfflineBanner agentName={c.activeAgent?.name} availability={c.availability} />- )}+ <CollapsibleSlot slotKey="chat-status-banner" visible={statusBanner !== null}>+ {statusBanner}+ </CollapsibleSlot><div className="px-4"><ChatAppRequests sessionId={c.activeSessionId} /></div>- <ChatWakeupStrip sessionId={c.activeSessionId} wakeups={wakeups} />+ <CollapsibleSlot slotKey="chat-wakeup-slot" visible={hasActiveWakeup}>+ <ChatWakeupStrip sessionId={c.activeSessionId} wakeups={wakeups} />+ </CollapsibleSlot><ChatQueuetasks={queuedTasks}@@ -488,7 +616,12 @@ export function ChatPage() {) : noAgentPage ? (noAgentState) : (- <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-muted-foreground">+ <div+ className={cn(+ "flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-muted-foreground",+ activeTransition && "animate-chat-enter-fade",+ )}+ ><MessageSquare className="h-10 w-10 text-faint-foreground" /><p className="text-body">{t(($) => $.page.select_prompt)}</p></div>diff --git a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx b/packages/views/chat/components/chat-message-list.autoscroll.test.tsxindex 37dca2c87f..cf01c1d63e 100644--- a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx+++ b/packages/views/chat/components/chat-message-list.autoscroll.test.tsx@@ -2,11 +2,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { act, render } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { I18nProvider } from "@multica/core/i18n/react";+import { useAppearanceStore } from "@multica/core/appearance";import { chatKeys } from "@multica/core/chat/queries";import type { TaskMessagePayload } from "@multica/core/types";import type { ReactElement } from "react";import enChat from "../../locales/en/chat.json";-import { ChatMessageList } from "./chat-message-list";+import { ChatMessageList, type ChatMessageEnterTransition } from "./chat-message-list";import { resetRevealedLists } from "./stick-to-bottom";// Auto-scroll wiring: the list must keep the live end visible through streaming@@ -359,8 +360,14 @@ function taskMsg(seq: number, content: string): TaskMessagePayload {function renderStreamingChat({contentHeight = 2000,revealKey,+ enterTransition,onRevealed,-}: { contentHeight?: number; revealKey?: string; onRevealed?: () => void } = {}) {+}: {+ contentHeight?: number;+ revealKey?: string;+ enterTransition?: ChatMessageEnterTransition | null;+ onRevealed?: () => void;+} = {}) {const qc = new QueryClient();qc.setQueryData(chatKeys.taskMessages(TASK_ID), [taskMsg(0, "Looking into it. ")]);@@ -370,6 +377,7 @@ function renderStreamingChat({<ChatMessageListactive={active}revealKey={revealKey}+ enterTransition={enterTransition}onRevealed={onRevealed}messages={[]}pendingTask={{ task_id: TASK_ID, status: "running" }}@@ -893,4 +901,43 @@ describe("ChatMessageList auto-scroll", () => {expect(observedTargets()).toHaveLength(0);});++ it("defers the directional enter transition until the list reaches its live end, and degrades under reduced motion", () => {+ const box = (el: Element, top: number, bottom: number) => {+ el.getBoundingClientRect = () => ({ top, bottom }) as DOMRect;+ };+ const settleFrames = (count: number) => {+ for (let i = 0; i < count; i++) act(() => renderFrame());+ };++ useAppearanceStore.setState({ reduceMotion: false });+ const first = renderStreamingChat({ revealKey: "enter-next", enterTransition: "next" });+ box(first.scroll.el, 0, VIEWPORT);+ const liveRow = first.view.container.querySelector("[data-chat-live-end]")!;+ box(liveRow, VIEWPORT - 120, VIEWPORT - 16);++ // Before landing, the list stays hidden and does not start its reveal animation prematurely.+ expect(first.scroll.el.className).toContain("invisible");+ expect(first.scroll.el.className).not.toContain("animate-chat-enter-next");++ settleFrames(12);+ expect(first.scroll.el.className).not.toContain("invisible");+ expect(first.scroll.el.className).toContain("animate-chat-enter-next");+ expect(first.scroll.el).toHaveAttribute("data-chat-enter-transition", "next");+ first.view.unmount();++ // Under reduced motion, directional transitions degrade to pure opacity fade.+ useAppearanceStore.setState({ reduceMotion: true });+ try {+ const reduced = renderStreamingChat({ revealKey: "enter-reduced", enterTransition: "prev" });+ box(reduced.scroll.el, 0, VIEWPORT);+ box(reduced.view.container.querySelector("[data-chat-live-end]")!, VIEWPORT - 120, VIEWPORT - 16);+ settleFrames(12);+ expect(reduced.scroll.el.className).toContain("animate-chat-enter-fade");+ expect(reduced.scroll.el.className).not.toContain("animate-chat-enter-prev");+ expect(reduced.scroll.el).toHaveAttribute("data-chat-enter-transition", "fade");+ } finally {+ useAppearanceStore.setState({ reduceMotion: false });+ }+ });});diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsxindex da4a5d03ed..980b24b7dd 100644--- a/packages/views/chat/components/chat-message-list.tsx+++ b/packages/views/chat/components/chat-message-list.tsx@@ -28,6 +28,7 @@ import {RotateCw,} from "@multica/ui/icons";import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";+import { useReducedMotion } from "@multica/core/appearance";import { isTaskMessageTaskId, taskMessagesOptions } from "@multica/core/chat/queries";import { RichContent } from "../../rich-content";import { RichContentScrollRootProvider } from "../../rich-content/scroll-root";@@ -65,6 +66,8 @@ import { ChatWakeupCards, ChatWakeupDivider, useWakeupsBySourceTask } from "./ch// ─── Public component ────────────────────────────────────────────────────+export type ChatMessageEnterTransition = "next" | "prev" | "fade";+interface ChatMessageListProps {/** Pause bottom-stick effects while a closing floating window fades out. */active?: boolean;@@ -74,6 +77,13 @@ interface ChatMessageListProps {* (stick-to-bottom.ts). Omit to pay the settle on every mount.*/revealKey?: string | null;+ /**+ * Subtle reveal transition played once the list has landed at the live end+ * (`hasReachedLiveEnd`): directional glide for archive-advance (`"next"` /+ * `"prev"`), or gentle opacity fade for direct session switches (`"fade"`).+ * Respects `prefers-reduced-motion` by degrading directional glides to fade.+ */+ enterTransition?: ChatMessageEnterTransition | null;/** The list became visible to the reader — on reveal, and on each reactivation after it. */onRevealed?: () => void;messages: ChatMessage[];@@ -196,6 +206,7 @@ const LIST_COMPONENTS: Components<ChatRenderItem, ChatListContext> = {export function ChatMessageList({active = true,revealKey = null,+ enterTransition = null,onRevealed,messages,pendingTask,@@ -237,6 +248,17 @@ export function ChatMessageList({// Soft edge fade hinting more content above/below. Kept small so it barely// grazes full-bleed previews (image / HTML) at the edges.const fadeStyle = useScrollFade(scrollRef, 16);+ const reduceMotion = useReducedMotion();+ const enterClass =+ hasReachedLiveEnd && enterTransition+ ? reduceMotion+ ? "animate-chat-enter-fade"+ : enterTransition === "next"+ ? "animate-chat-enter-next"+ : enterTransition === "prev"+ ? "animate-chat-enter-prev"+ : "animate-chat-enter-fade"+ : undefined;const pendingTaskId = pendingTask?.task_id ?? null;const wakeupsBySourceTask = useWakeupsBySourceTask(wakeups);@@ -366,9 +388,11 @@ export function ChatMessageList({* pinned above the composer instead of scrolling with the rows. */}<div ref={annotations?.cardRef} {...annotations?.captureProps} className="relative flex min-h-0 flex-1 flex-col">{annotations?.popup}+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden"><divref={setScrollContainerRef}data-tab-scroll-root+ data-chat-enter-transition={hasReachedLiveEnd && enterTransition ? (reduceMotion ? "fade" : enterTransition) : undefined}style={fadeStyle}// The gutter lives on the scroll container, so it applies once to the// whole list — rows, header, footer — and the scrollbar still rides the@@ -377,7 +401,7 @@ export function ChatMessageList({// container paints nothing for that whole window anyway — the rows are// not measured yet — so this costs no visible time and spares the// reader a frame of the wrong messages (see stick-to-bottom.ts).- className={cn("flex-1 overflow-y-auto", CHAT_GUTTER, !hasReachedLiveEnd && "invisible")}+ className={cn("flex-1 overflow-y-auto", CHAT_GUTTER, !hasReachedLiveEnd && "invisible", enterClass)}>{/* Already inside the gutter + column, so this pre-mount frame renders the* skeleton BODY rather than <ChatMessageSkeleton>, which brings its own@@ -458,6 +482,7 @@ export function ChatMessageList({</RichContentScrollRootProvider>)}</div>+ </div>{jumpToLiveEnd.visible && (<JumpToLiveEndButtonhasNewReply={jumpToLiveEnd.hasNewReply}diff --git a/packages/views/chat/components/chat-session-header.test.tsx b/packages/views/chat/components/chat-session-header.test.tsxindex 0bd98b3cb4..99ef024588 100644--- a/packages/views/chat/components/chat-session-header.test.tsx+++ b/packages/views/chat/components/chat-session-header.test.tsx@@ -248,4 +248,28 @@ describe("ChatSessionHeader rename keyboard behavior", () => {expect(screen.queryByRole("textbox", { name: RENAME_LABEL })).not.toBeInTheDocument();expect(screen.getByText("Original title")).toBeInTheDocument();});++ it("resets inline rename state when switching to another session", () => {+ const nextSession: ChatSession = {+ ...session,+ id: "session-2",+ title: "Next session",+ };+ const { rerender } = render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <ChatSessionHeader session={session} agent={null} />+ </I18nProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Original title" }));+ expect(screen.getByRole("textbox", { name: RENAME_LABEL })).toBeInTheDocument();++ rerender(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <ChatSessionHeader session={nextSession} agent={null} />+ </I18nProvider>,+ );++ expect(screen.queryByRole("textbox", { name: RENAME_LABEL })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Next session" })).toBeInTheDocument();+ });});diff --git a/packages/views/chat/components/chat-session-header.tsx b/packages/views/chat/components/chat-session-header.tsxindex 55fe6fa2bf..99cf712bde 100644--- a/packages/views/chat/components/chat-session-header.tsx+++ b/packages/views/chat/components/chat-session-header.tsx@@ -83,6 +83,16 @@ export function ChatSessionHeader({const title = session.title?.trim() || t(($) => $.window.untitled);+ useEffect(() => {+ clearPendingBlurCommit();+ isComposingRef.current = false;+ commitAfterCompositionRef.current = false;+ setEditing(false);+ setConfirmDelete(false);+ setDraft(session.title ?? "");+ // eslint-disable-next-line react-hooks/exhaustive-deps -- reset transient header UI only when switching sessions+ }, [session.id]);+useEffect(() => {if (editing) {inputRef.current?.focus();diff --git a/packages/views/chat/components/chat-thread-list.test.tsx b/packages/views/chat/components/chat-thread-list.test.tsxindex ad481280c7..5a1d7a26f3 100644--- a/packages/views/chat/components/chat-thread-list.test.tsx+++ b/packages/views/chat/components/chat-thread-list.test.tsx@@ -61,6 +61,7 @@ vi.mock("@tanstack/react-query", async (importOriginal) => {});import { ChatThreadList } from "./chat-thread-list";+import { SESSION_LIST_VIRTUALIZE_AFTER } from "./session-history-list";const TEST_RESOURCES = { en: { chat: enChat, issues: enIssues } };@@ -96,24 +97,33 @@ function renderList({onArchive = vi.fn(),onSelectSession = vi.fn(),+ onPrefetchSession = vi.fn(),renderedSessions = sessions,renderedAgents = [agent],} = {},) {- render(+ const makeUi = (list: ChatSession[], activeId: string | null) => (<VirtuosoMockContext.Provider value={{ viewportHeight: 560, itemHeight: 56 }}><I18nProvider locale="en" resources={TEST_RESOURCES}><ChatThreadList- sessions={renderedSessions}+ sessions={list}agents={renderedAgents}- activeSessionId={activeSessionId}+ activeSessionId={activeId}onSelectSession={onSelectSession}onArchive={onArchive}+ onPrefetchSession={onPrefetchSession}/></I18nProvider>- </VirtuosoMockContext.Provider>,+ </VirtuosoMockContext.Provider>);- return { onArchive, onSelectSession };+ const view = render(makeUi(renderedSessions, activeSessionId));+ return {+ onArchive,+ onSelectSession,+ onPrefetchSession,+ rerenderList: (list: ChatSession[], activeId: string | null = activeSessionId) =>+ view.rerender(makeUi(list, activeId)),+ };}const ARCHIVE_LABEL = enChat.list.archive;@@ -385,3 +395,77 @@ describe("ChatThreadList right-click menu", () => {expect(onSelectSession).not.toHaveBeenCalled();});});++describe("ChatThreadList prefetch and smooth exit", () => {+ it("triggers onPrefetchSession when hovering or focusing a row", () => {+ const { onPrefetchSession } = renderList("s1");+ const row = screen.getByText("Chat s2").closest("[data-chat-thread-row]")!;++ fireEvent.pointerEnter(row);+ fireEvent.focus(row);++ expect(onPrefetchSession).toHaveBeenCalledTimes(2);+ expect(onPrefetchSession).toHaveBeenNthCalledWith(1, "s2");+ expect(onPrefetchSession).toHaveBeenNthCalledWith(2, "s2");+ });++ it("marks a removed history row as exiting while animating out in a short list", () => {+ const { rerenderList } = renderList("s1");+ expect(screen.getByText("Chat s1")).toBeInTheDocument();++ // Optimistic archive flips s1 to status="archived", dropping it from history.+ const nextSessions = sessions.map((s) =>+ s.id === "s1" ? { ...s, status: "archived" as const } : s,+ );+ rerenderList(nextSessions, "s2");++ const exiting = document.querySelector("[data-chat-row-exiting]");+ expect(exiting).toBeInTheDocument();+ expect(exiting).toHaveAttribute("aria-hidden", "true");+ expect(exiting?.className).toContain("pointer-events-none");+ expect(screen.getByText("Chat s2").closest("[aria-current]")).toHaveAttribute(+ "aria-current",+ "true",+ );+ });++ it("marks a removed archived row as exiting when unarchived in the archived view", () => {+ const archived = [+ makeSession({ id: "a1", status: "archived", updated_at: "2026-07-08T03:00:00Z" }),+ makeSession({ id: "a2", status: "archived", updated_at: "2026-07-08T02:00:00Z" }),+ ];+ const { rerenderList } = renderList(null, {+ renderedSessions: [...sessions, ...archived],+ });+ fireEvent.click(screen.getByRole("button", { name: /Archived.*2/ }));+ expect(screen.getByText("Chat a1")).toBeInTheDocument();++ rerenderList(+ [...sessions, { ...archived[0]!, status: "active" }, archived[1]!],+ null,+ );++ const exiting = document.querySelector("[data-chat-row-exiting]");+ expect(exiting).toBeInTheDocument();+ expect(exiting).toHaveAttribute("aria-hidden", "true");+ });++ it("keeps the same scroll container element when crossing the virtualization threshold", () => {+ const overThreshold = Array.from(+ { length: SESSION_LIST_VIRTUALIZE_AFTER + 1 },+ (_, i) => makeSession({ id: `s-${i}` }),+ );+ const { rerenderList } = renderList("s-0", {+ renderedSessions: overThreshold,+ });++ const scrollerBefore = document.querySelector("[data-chat-session-scroller]");+ expect(scrollerBefore).toBeInTheDocument();++ // Archiving one row drops the active count from 61 to 60 (virtualized -> animated list).+ rerenderList(overThreshold.slice(1), "s-1");++ const scrollerAfter = document.querySelector("[data-chat-session-scroller]");+ expect(scrollerAfter).toBe(scrollerBefore);+ });+});diff --git a/packages/views/chat/components/chat-thread-list.tsx b/packages/views/chat/components/chat-thread-list.tsxindex 42b50d6fb1..90a21477ad 100644--- a/packages/views/chat/components/chat-thread-list.tsx+++ b/packages/views/chat/components/chat-thread-list.tsx@@ -100,6 +100,7 @@ export function ChatThreadList({activeSessionId,onSelectSession,onArchive,+ onPrefetchSession,}: {sessions: ChatSession[];agents: Agent[];@@ -109,6 +110,8 @@ export function ChatThreadList({// aware (desktop advances to the next chat; mobile drops back to the list)// and routes through the shared controller — see ChatPage.handleArchive.onArchive: (session: ChatSession) => void;+ /** Warm a session's messages and context on pointer hover or keyboard focus. */+ onPrefetchSession?: (sessionId: string) => void;}) {const { t } = useT("chat");const { t: tLayout } = useT("layout");@@ -396,8 +399,15 @@ export function ChatThreadList({return (<divkey={session.id}+ data-chat-thread-row={session.id}aria-current={isCurrent ? "true" : undefined}tabIndex={0}+ onPointerEnter={() => {+ if (!isConfirmingAction) onPrefetchSession?.(session.id);+ }}+ onFocus={() => {+ if (!isConfirmingAction) onPrefetchSession?.(session.id);+ }}onClick={(e) => {if (isConfirmingAction || isRenaming || e.defaultPrevented) return;// Plain click keeps the master-detail selection. On web, a modifier@@ -608,7 +618,12 @@ export function ChatThreadList({</span></button><div className="min-h-0 flex-1">- <SessionHistoryList sessions={archivedSessions} renderRow={renderRow} />+ <SessionHistoryList+ key="archived"+ sessions={archivedSessions}+ renderRow={renderRow}+ animateExit+ /></div>{rowContextMenu}</div>@@ -645,9 +660,11 @@ export function ChatThreadList({return (<><SessionHistoryList+ key="history"sessions={historySessions}renderRow={renderRow}footer={archivedEntry}+ animateExit/>{rowContextMenu}</>diff --git a/packages/views/chat/components/session-history-list.tsx b/packages/views/chat/components/session-history-list.tsxindex ddeefd180f..213d1e95bc 100644--- a/packages/views/chat/components/session-history-list.tsx+++ b/packages/views/chat/components/session-history-list.tsx@@ -1,37 +1,119 @@"use client";-import type { ReactNode } from "react";+import { useState, type ReactNode } from "react";+import { AnimatePresence, motion, useIsPresent } from "motion/react";import { Virtuoso, type Components } from "react-virtuoso";+import { useReducedMotion } from "@multica/core/appearance";+import { UI_EASE_OUT, UI_MOTION_DURATION } from "@multica/ui/lib/motion";+import { cn } from "@multica/ui/lib/utils";import type { ChatSession } from "@multica/core/types";type ListContext = { footer?: ReactNode };+/**+ * Up to this many rows, `animateExit` renders rows directly inside+ * `AnimatePresence` so archiving/deleting a row collapses its height smoothly+ * instead of snapping the rows below upward. Longer lists switch to+ * `<Virtuoso>` over the same outer scroll container (via `customScrollParent`,+ * like `InboxSection` does past its 50-row boundary) so crossing the threshold+ * never swaps the scroller element or resets scroll position.+ */+export const SESSION_LIST_VIRTUALIZE_AFTER = 60;+// Keep component identities stable, including when there is no archive entry.// Passing an explicit undefined components prop breaks Virtuoso 4.18 builds.const COMPONENTS: Components<ChatSession, ListContext> = {Footer: ({ context }) => <>{context?.footer}</>,};+function SessionExitRow({ children }: { children: ReactNode }) {+ const isPresent = useIsPresent();+ const reduceMotion = useReducedMotion();++ return (+ <motion.div+ data-chat-row-exiting={!isPresent ? "" : undefined}+ aria-hidden={!isPresent || undefined}+ initial={false}+ exit={{+ opacity: 0,+ height: 0,+ overflow: "hidden",+ transition: {+ duration: reduceMotion ? 0 : UI_MOTION_DURATION.fast,+ ease: UI_EASE_OUT,+ },+ }}+ className={cn(!isPresent && "pointer-events-none")}+ >+ {children}+ </motion.div>+ );+}+export function SessionHistoryList({sessions,renderRow,footer,maxHeight,estimatedRowHeight = 56,+ animateExit = false,}: {sessions: ChatSession[];renderRow: (session: ChatSession) => ReactNode;footer?: ReactNode;maxHeight?: number;estimatedRowHeight?: number;+ /** Smoothly collapse rows as they leave the list (for small/medium lists). */+ animateExit?: boolean;}) {+ const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);+ const height =+ maxHeight == null+ ? "100%"+ : Math.min(maxHeight, sessions.length * estimatedRowHeight);++ if (animateExit) {+ const virtualize = sessions.length > SESSION_LIST_VIRTUALIZE_AFTER;+ return (+ <div+ ref={setScrollEl}+ data-chat-session-scroller=""+ className="overflow-y-auto"+ style={{ height }}+ >+ {virtualize ? (+ scrollEl ? (+ <Virtuoso+ customScrollParent={scrollEl}+ data={sessions}+ defaultItemHeight={estimatedRowHeight}+ increaseViewportBy={200}+ computeItemKey={(_, session) => session.id}+ itemContent={(_, session) => renderRow(session)}+ components={COMPONENTS}+ context={{ footer }}+ />+ ) : null+ ) : (+ <>+ <AnimatePresence initial={false}>+ {sessions.map((session) => (+ <SessionExitRow key={session.id}>+ {renderRow(session)}+ </SessionExitRow>+ ))}+ </AnimatePresence>+ {footer}+ </>+ )}+ </div>+ );+ }+return (<Virtuoso- style={{- height: maxHeight == null- ? "100%"- : Math.min(maxHeight, sessions.length * estimatedRowHeight),- }}+ style={{ height }}data={sessions}defaultItemHeight={estimatedRowHeight}increaseViewportBy={200}diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsxindex a5531fc3d2..3d417472ea 100644--- a/packages/views/chat/components/use-chat-controller.test.tsx+++ b/packages/views/chat/components/use-chat-controller.test.tsx@@ -583,8 +583,12 @@ describe("useChatController.advanceSelectionAfterArchive", () => {it("advances to the next chat and syncs the selected agent across agents", () => {const result = setup("sA", [sA, sB, sC], [agentA, agentB]);- act(() => result.current.advanceSelectionAfterArchive(sA));+ let outcome;+ act(() => {+ outcome = result.current.advanceSelectionAfterArchive(sA);+ });+ expect(outcome).toEqual({ moved: true, targetSessionId: "sB", direction: "next" });expect(h.store.setActiveSession).toHaveBeenCalledWith("sB");// The next chat belongs to a different agent — selectedAgentId must follow// so a subsequent "new chat" defaults to the right agent (the review bug).@@ -597,32 +601,48 @@ describe("useChatController.advanceSelectionAfterArchive", () => {const a1 = makeSession({ id: "a1", agent_id: "agent-a", updated_at: "2026-07-08T03:00:00Z" });const a2 = makeSession({ id: "a2", agent_id: "agent-a", updated_at: "2026-07-08T02:00:00Z" });const result = setup("a1", [a1, a2], [agentA, agentB]);- act(() => result.current.advanceSelectionAfterArchive(a1));+ let outcome;+ act(() => {+ outcome = result.current.advanceSelectionAfterArchive(a1);+ });+ expect(outcome).toEqual({ moved: true, targetSessionId: "a2", direction: "next" });expect(h.store.setActiveSession).toHaveBeenCalledWith("a2");expect(h.store.setSelectedAgentId).not.toHaveBeenCalled();});it("falls back to the previous chat when archiving the last open one", () => {const result = setup("sC", [sA, sB, sC], [agentA, agentB]);- act(() => result.current.advanceSelectionAfterArchive(sC));+ let outcome;+ act(() => {+ outcome = result.current.advanceSelectionAfterArchive(sC);+ });+ expect(outcome).toEqual({ moved: true, targetSessionId: "sB", direction: "prev" });expect(h.store.setActiveSession).toHaveBeenCalledWith("sB");});it("clears the selection when archiving the only chat", () => {const only = makeSession({ id: "only", agent_id: "agent-a" });const result = setup("only", [only], [agentA]);- act(() => result.current.advanceSelectionAfterArchive(only));+ let outcome;+ act(() => {+ outcome = result.current.advanceSelectionAfterArchive(only);+ });+ expect(outcome).toEqual({ moved: true, targetSessionId: null, direction: null });expect(h.store.setActiveSession).toHaveBeenCalledWith(null);expect(h.store.setSelectedAgentId).not.toHaveBeenCalled();});it("is a no-op when the archived chat is not the open one", () => {const result = setup("sB", [sA, sB, sC], [agentA, agentB]);- act(() => result.current.advanceSelectionAfterArchive(sA));+ let outcome;+ act(() => {+ outcome = result.current.advanceSelectionAfterArchive(sA);+ });+ expect(outcome).toEqual({ moved: false });expect(h.store.setActiveSession).not.toHaveBeenCalled();expect(h.store.setSelectedAgentId).not.toHaveBeenCalled();});diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.tsindex cb80eb241e..2e442b470b 100644--- a/packages/views/chat/components/use-chat-controller.ts+++ b/packages/views/chat/components/use-chat-controller.ts@@ -98,6 +98,13 @@ export type ProjectContextChange =| { kind: "startFreshChat"; agentId: string; projectId: string }| { kind: "setDraftProject"; projectId: string | null };+export type ChatArchiveAdvanceDirection = "next" | "prev";++export type ChatArchiveAdvanceResult =+ | { moved: false }+ | { moved: true; targetSessionId: string; direction: ChatArchiveAdvanceDirection }+ | { moved: true; targetSessionId: null; direction: null };+export function planProjectContextChange(input: {targetProjectId: string | null;activeSessionId: string | null;@@ -829,15 +836,24 @@ export function useChatController(opts?: { isActive?: boolean }) {// right agent even when the next chat belongs to a different agent. A no-op// when the archived session isn't the open one — that selection stays put.const advanceSelectionAfterArchive = useCallback(- (session: { id: string; agent_id: string }) => {- if (activeSessionId !== session.id) return;+ (session: { id: string; agent_id: string }): ChatArchiveAdvanceResult => {+ if (activeSessionId !== session.id) return { moved: false };const history = sortChatSessions(sessions.filter((s) => s.status !== "archived"),);const idx = history.findIndex((s) => s.id === session.id);- const next = history[idx + 1] ?? history[idx - 1] ?? null;- if (next) handleSelectSession(next);- else setActiveSession(null);+ const next = history[idx + 1] ?? null;+ if (next) {+ handleSelectSession(next);+ return { moved: true, targetSessionId: next.id, direction: "next" };+ }+ const prev = history[idx - 1] ?? null;+ if (prev) {+ handleSelectSession(prev);+ return { moved: true, targetSessionId: prev.id, direction: "prev" };+ }+ setActiveSession(null);+ return { moved: true, targetSessionId: null, direction: null };},[activeSessionId, sessions, handleSelectSession, setActiveSession],);diff --git a/packages/views/chat/components/use-chat-session-prefetch.test.tsx b/packages/views/chat/components/use-chat-session-prefetch.test.tsxnew file mode 100644index 0000000000..39d8d639fc--- /dev/null+++ b/packages/views/chat/components/use-chat-session-prefetch.test.tsx@@ -0,0 +1,238 @@+import { act, renderHook } from "@testing-library/react";+import type { ReactNode } from "react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { api } from "@multica/core/api";+import { chatKeys } from "@multica/core/chat/queries";+import type { ChatSession } from "@multica/core/types";+import {+ pickAdjacentChatSessions,+ useChatSessionPrefetch,+} from "./use-chat-session-prefetch";++const featureState = vi.hoisted(() => ({ appRequests: false }));+vi.mock("@multica/core/config", () => ({+ useFeatureEnabled: () => featureState.appRequests,+}));++vi.mock("@multica/core/api", () => ({+ api: {+ listChatMessagesPage: vi.fn(async (sessionId: string) => ({+ messages: [+ {+ id: `msg-${sessionId}`,+ chat_session_id: sessionId,+ role: "assistant",+ content: `reply for ${sessionId}`,+ task_id: null,+ created_at: "2026-07-08T00:00:00Z",+ },+ ],+ limit: 50,+ has_more: false,+ next_cursor: null,+ })),+ getPendingChatTask: vi.fn(async () => ({})),+ listChatSessionWakeups: vi.fn(async () => []),+ listTaskMessages: vi.fn(async () => []),+ listAppRequests: vi.fn(async () => ({ requests: [] })),+ },+}));++function makeSession(+ overrides: Partial<ChatSession> & Pick<ChatSession, "id">,+): ChatSession {+ return {+ workspace_id: "ws-1",+ agent_id: "agent-1",+ creator_id: "user-1",+ title: `Chat ${overrides.id}`,+ status: "active",+ has_unread: false,+ unread_count: 0,+ last_message: null,+ pinned: false,+ created_at: "2026-07-08T00:00:00Z",+ updated_at: "2026-07-08T00:00:00Z",+ ...overrides,+ };+}++const sessions: ChatSession[] = [+ makeSession({ id: "s1", updated_at: "2026-07-08T05:00:00Z" }),+ makeSession({ id: "s2", updated_at: "2026-07-08T04:00:00Z" }),+ makeSession({ id: "s3", updated_at: "2026-07-08T03:00:00Z" }),+ makeSession({ id: "s4", updated_at: "2026-07-08T02:00:00Z" }),+ makeSession({ id: "s5", updated_at: "2026-07-08T01:00:00Z" }),+];++describe("pickAdjacentChatSessions", () => {+ it("prioritizes next, then prev, then next+1 around the active session", () => {+ const picked = pickAdjacentChatSessions(sessions, "s2");+ expect(picked.map((s) => s.id)).toEqual(["s3", "s1", "s4"]);+ });++ it("picks prev when viewing the last session in history", () => {+ const picked = pickAdjacentChatSessions(sessions, "s5");+ expect(picked.map((s) => s.id)).toEqual(["s4"]);+ });++ it("respects pinned-first ordering when picking neighbours", () => {+ const mixed = [+ makeSession({ id: "recent", updated_at: "2026-07-08T05:00:00Z" }),+ makeSession({ id: "pinned", pinned: true, updated_at: "2026-07-08T01:00:00Z" }),+ makeSession({ id: "older", updated_at: "2026-07-08T02:00:00Z" }),+ ];+ // Sorted order: pinned, recent, older. Active = pinned -> next1=recent, next2=older.+ expect(pickAdjacentChatSessions(mixed, "pinned").map((s) => s.id)).toEqual([+ "recent",+ "older",+ ]);+ });++ it("picks adjacent archived sessions when viewing an archived chat", () => {+ const archived = [+ makeSession({ id: "a1", status: "archived", updated_at: "2026-07-08T03:00:00Z" }),+ makeSession({ id: "a2", status: "archived", updated_at: "2026-07-08T02:00:00Z" }),+ makeSession({ id: "a3", status: "archived", updated_at: "2026-07-08T01:00:00Z" }),+ ];+ expect(pickAdjacentChatSessions([...sessions, ...archived], "a2").map((s) => s.id)).toEqual([+ "a3",+ "a1",+ ]);+ });++ it("warms the top active sessions when nothing is selected", () => {+ const withArchived = [+ makeSession({ id: "arch", status: "archived", updated_at: "2026-07-08T09:00:00Z" }),+ ...sessions,+ ];+ expect(pickAdjacentChatSessions(withArchived, null).map((s) => s.id)).toEqual([+ "s1",+ "s2",+ ]);+ });+});++function setup(+ list: ChatSession[],+ activeSessionId: string | null,+ isActive = true,+) {+ const qc = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>+ );+ const hook = renderHook(+ ({ items, activeId, active }) =>+ useChatSessionPrefetch({+ wsId: "ws-1",+ sessions: items,+ activeSessionId: activeId,+ isActive: active,+ }),+ {+ wrapper,+ initialProps: { items: list, activeId: activeSessionId, active: isActive },+ },+ );+ return { qc, hook };+}++describe("useChatSessionPrefetch", () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+ featureState.appRequests = false;+ });++ it("warms next, prev, and next+1 sessions sequentially on idle", async () => {+ const { qc } = setup(sessions, "s2");+ expect(api.listChatMessagesPage).not.toHaveBeenCalled();++ await act(async () => {+ await vi.advanceTimersByTimeAsync(500);+ });++ expect(vi.mocked(api.listChatMessagesPage).mock.calls.map(([id]) => id)).toEqual([+ "s3",+ "s1",+ "s4",+ ]);+ expect(vi.mocked(api.getPendingChatTask).mock.calls.map(([id]) => id)).toEqual([+ "s3",+ "s1",+ "s4",+ ]);+ expect(vi.mocked(api.listChatSessionWakeups).mock.calls.map(([id]) => id)).toEqual([+ "s3",+ "s1",+ "s4",+ ]);+ expect(api.listAppRequests).not.toHaveBeenCalled();+ expect(qc.getQueryData(chatKeys.messagesPage("s3"))).toBeDefined();+ });++ it("warms chat app requests when the Composio feature flag is enabled", async () => {+ featureState.appRequests = true;+ setup(sessions.slice(0, 2), "s1");++ await act(async () => {+ await vi.advanceTimersByTimeAsync(500);+ });++ expect(api.listAppRequests).toHaveBeenCalledWith({ chatSessionId: "s2" });+ });++ it("does not prefetch while the surface is inactive", async () => {+ setup(sessions, "s2", false);++ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ });++ expect(api.listChatMessagesPage).not.toHaveBeenCalled();+ });++ it("does not restart when realtime replaces identical session lists", async () => {+ const { hook } = setup(sessions.slice(0, 2), "s1");+ hook.rerender({+ items: sessions.slice(0, 2).map((s) => ({ ...s })),+ activeId: "s1",+ active: true,+ });++ await act(async () => {+ await vi.advanceTimersByTimeAsync(500);+ });++ expect(api.listChatMessagesPage).toHaveBeenCalledTimes(1);+ expect(api.listChatMessagesPage).toHaveBeenCalledWith("s2", {+ before: null,+ limit: 50,+ });+ });++ it("warms a pointed-at session on demand and skips already-warm caches", async () => {+ const { hook } = setup(sessions, "s1");+ await act(async () => {+ await vi.advanceTimersByTimeAsync(500);+ });+ // s2 and s3 were warmed on idle. Hovering s5 fetches it; hovering s2 is a cache hit.+ await act(async () => {+ await hook.result.current("s5");+ });+ await act(async () => {+ await hook.result.current("s2");+ });++ expect(vi.mocked(api.listChatMessagesPage).mock.calls.map(([id]) => id)).toEqual([+ "s2",+ "s3",+ "s5",+ ]);+ });+});diff --git a/packages/views/chat/components/use-chat-session-prefetch.ts b/packages/views/chat/components/use-chat-session-prefetch.tsnew file mode 100644index 0000000000..a2ac1258dd--- /dev/null+++ b/packages/views/chat/components/use-chat-session-prefetch.ts@@ -0,0 +1,137 @@+"use client";++import { useCallback, useEffect, useMemo } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { prefetchChatSession, sortChatSessions } from "@multica/core/chat/queries";+import { chatAppRequestsOptions } from "@multica/core/connected-apps";+import { useFeatureEnabled } from "@multica/core/config";+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";+import type { ChatSession } from "@multica/core/types";++/** Sessions warmed when idle and nothing is selected yet. */+export const CHAT_IDLE_PREFETCH_LIMIT = 2;++/**+ * Pick the adjacent sessions to warm around `activeSessionId` in priority order:+ *+ * - When an active session is open: `next` first (the primary target of+ * `advanceSelectionAfterArchive`), then `prev` (the fallback when archiving+ * the last session, and an immediately adjacent click target), then `next+1`+ * for consecutive archiving.+ * - Works across both the active history list and the archived view (whichever+ * list contains `activeSessionId`).+ * - When no session is open: the top rows in history order.+ */+export function pickAdjacentChatSessions(+ sessions: readonly ChatSession[],+ activeSessionId: string | null,+): ChatSession[] {+ const history = sortChatSessions(sessions.filter((s) => s.status !== "archived"));+ const picked: ChatSession[] = [];+ const seen = new Set<string>();+ const add = (session: ChatSession | null | undefined) => {+ if (!session?.id || session.id === activeSessionId || seen.has(session.id)) return;+ seen.add(session.id);+ picked.push(session);+ };++ if (activeSessionId) {+ const historyIdx = history.findIndex((s) => s.id === activeSessionId);+ if (historyIdx >= 0) {+ add(history[historyIdx + 1]);+ add(history[historyIdx - 1]);+ add(history[historyIdx + 2]);+ return picked;+ }++ const archived = sortChatSessions(sessions.filter((s) => s.status === "archived"));+ const archivedIdx = archived.findIndex((s) => s.id === activeSessionId);+ if (archivedIdx >= 0) {+ add(archived[archivedIdx + 1]);+ add(archived[archivedIdx - 1]);+ add(archived[archivedIdx + 2]);+ return picked;+ }+ }++ for (const session of history) {+ if (picked.length >= CHAT_IDLE_PREFETCH_LIMIT) break;+ add(session);+ }+ return picked;+}++/**+ * Warms neighbouring chat sessions in the background while the Chat page is+ * active so archiving and auto-advancing (or clicking an adjacent thread) hits+ * a warm cache without flashing the skeleton or asynchronously popping in+ * bottom strips. Returns an on-demand `prefetchSession` callback for row hover+ * and focus.+ */+export function useChatSessionPrefetch({+ wsId,+ sessions,+ activeSessionId,+ isActive = true,+}: {+ wsId: string;+ sessions: readonly ChatSession[];+ activeSessionId: string | null;+ isActive?: boolean;+}) {+ const qc = useQueryClient();+ const appRequestsEnabled = useFeatureEnabled(COMPOSIO_MCP_APPS_FLAG, false);++ const prefetchSession = useCallback(+ (sessionId: string) => {+ if (!wsId || !sessionId) return Promise.resolve();+ return Promise.all([+ prefetchChatSession(qc, sessionId),+ appRequestsEnabled+ ? qc.prefetchQuery(chatAppRequestsOptions(wsId, sessionId))+ : undefined,+ ])+ .then(() => undefined)+ .catch(() => {+ // A failed warm-up falls back cleanly to the session's own query on open.+ });+ },+ [qc, wsId, appRequestsEnabled],+ );++ const idleTargets = useMemo(+ () => (isActive ? pickAdjacentChatSessions(sessions, activeSessionId) : []),+ [isActive, sessions, activeSessionId],+ );+ // Effect identity follows the target session IDs, not the session object+ // references that realtime patches replace on every chat event.+ const idleKey = idleTargets.map((s) => s.id).join(",");++ useEffect(() => {+ if (!isActive || !wsId || !idleKey) return;+ let cancelled = false;+ const run = async () => {+ // Sequential: each session fans out across messages, pending task, and wakeups.+ for (const session of idleTargets) {+ if (cancelled) return;+ await prefetchSession(session.id);+ }+ };+ const timeout = activeSessionId ? 150 : 400;+ if (typeof window.requestIdleCallback === "function") {+ const id = window.requestIdleCallback(() => void run(), { timeout });+ return () => {+ cancelled = true;+ window.cancelIdleCallback(id);+ };+ }+ const timer = window.setTimeout(() => void run(), activeSessionId ? 100 : 300);+ return () => {+ cancelled = true;+ window.clearTimeout(timer);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed by target session IDs+ }, [idleKey, wsId, isActive, appRequestsEnabled]);++ return prefetchSession;+}