Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8030: fix(chat): stop hidden floating chat scroll loops (#9351)
LinYushenf357a4e97710
diff --git a/e2e/perf/README.md b/e2e/perf/README.mdindex 56e077c0e1..266b082046 100644--- a/e2e/perf/README.md+++ b/e2e/perf/README.md@@ -1,7 +1,7 @@-# UI performance scenario+# UI performance scenarios-One browser scenario: typing a comment on a long issue thread while three agent-runs stream progress. It exists because of MUL-7227, where a summary animation+The comment-typing scenario models a long issue thread while three agent runs+stream progress. It exists because of MUL-7227, where a summary animationreplaced a DOM node per streamed message and typing a comment slowed to a crawl.Component tests could not see it — they run in jsdom, which has no stylerecalculation, no layout and no main-thread contention.@@ -40,6 +40,17 @@ success, on failure and on cancellation.The ordinary e2e suite ignores this directory; it needs a production build anda machine that is not busy doing anything else.+The floating-chat lifetime regression runs against the same production build:++```bash+pnpm exec playwright test --config=playwright.perf.config.ts floating-chat-lifetime.spec.ts+```++It checks that closing removes the message list, keeps the real composer and+an in-flight upload alive, shows messages received while closed on reopen, and+survives an interrupted exit. It also checks that the message list's ancestor+is never scaled. HTTP and WebSocket traffic is synthetic; no backend is needed.+## When to run itNothing runs this automatically. The routine guard is the component test fromdiff --git a/e2e/perf/floating-chat-lifetime.spec.ts b/e2e/perf/floating-chat-lifetime.spec.tsnew file mode 100644index 0000000000..d63c54654a--- /dev/null+++ b/e2e/perf/floating-chat-lifetime.spec.ts@@ -0,0 +1,197 @@+import { expect, test } from "@playwright/test";++// Production shared UI with synthetic HTTP/WS boundaries; no backend or account.+const wsId = "11111111-1111-4111-8111-111111111111";+const userId = "22222222-2222-4222-8222-222222222222";+const agentId = "33333333-3333-4333-8333-333333333333";+const sessionId = "44444444-4444-4444-8444-444444444444";+const taskId = "77777777-7777-4777-8777-777777777777";+const timestamp = "2026-10-20T00:00:00Z";+const session = {+ id: sessionId, workspace_id: wsId, agent_id: agentId, creator_id: userId,+ title: "Chat lifetime", status: "active", has_unread: false, unread_count: 0,+ last_message: null, pinned: false, created_at: timestamp, updated_at: timestamp,+};+const agent = {+ id: agentId, workspace_id: wsId, runtime_id: "55555555-5555-4555-8555-555555555555",+ name: "Fixture Agent", description: "", instructions: "", avatar_url: null,+ runtime_mode: "local", runtime_config: {}, custom_args: [], visibility: "workspace",+ permission_mode: "public_to", invocation_targets: [{ target_type: "workspace", target_id: null }],+ status: "idle", max_concurrent_tasks: 1, model: "", owner_id: userId, skills: [],+ runtime_availability: "online", created_at: timestamp, updated_at: timestamp,+ archived_at: null, archived_by: null,+};++test.use({ viewport: { width: 1280, height: 800 }, locale: "en-US", serviceWorkers: "block" });++test("closing floating chat releases its list and preserves the live composer", async ({ page, context, baseURL }) => {+ const origin = new URL(baseURL ?? "http://localhost:3000").origin;+ const unexpected: string[] = [];+ const errors: string[] = [];+ page.on("pageerror", error => errors.push(error.message));+ await page.emulateMedia({ reducedMotion: "no-preference" });+ await context.addCookies([+ { name: "multica_logged_in", value: "1", url: origin },+ { name: "last_workspace_slug", value: "perf", url: origin },+ ]);+ await context.addInitScript(({ sessionId, agentId }) => {+ localStorage.setItem("multica:chat:isOpen", "true");+ localStorage.setItem("multica:chat:floatingChatEnabled", "true");+ localStorage.setItem("multica:chat:activeSessionId:perf", sessionId);+ localStorage.setItem("multica:chat:selectedAgentId:perf", agentId);+ }, { sessionId, agentId });+ let latestContent = "Latest fixture message";+ const taskMessages = [{ task_id: taskId, seq: 0, type: "text", content: "Streaming fixture. " }];+ let uploadStarted = false;+ let finishUpload!: () => void;+ const uploadGate = new Promise<void>(resolve => { finishUpload = resolve; });+ const responseFor = (path: string): unknown => {+ switch (path) {+ case "/api/config": return { feature_flags: {}, allow_signup: true };+ case "/api/me": return {+ id: userId, name: "Fixture User", email: "[email protected]", avatar_url: null,+ language: "en", onboarded_at: timestamp, onboarding_questionnaire: { source: "other" },+ created_at: timestamp, updated_at: timestamp,+ };+ case "/api/workspaces": return [{+ id: wsId, name: "Perf", slug: "perf", description: null, context: null,+ settings: { github_enabled: false }, repos: [], issue_prefix: "PERF", avatar_url: null,+ created_at: timestamp, updated_at: timestamp,+ }];+ case "/api/agents": return [agent];+ case "/api/chat/sessions": return [session];+ case `/api/chat/sessions/${sessionId}`: return session;+ case `/api/chat/sessions/${sessionId}/messages/page`: return {+ messages: Array.from({ length: 50 }, (_, i) => ({+ id: `message-${i}`, chat_session_id: sessionId, role: "user", task_id: null,+ content: i === 49 ? latestContent : `Fixture message ${i}. `.repeat(1 + i % 5),+ created_at: timestamp,+ })), limit: 50, has_more: false,+ };+ case `/api/chat/sessions/${sessionId}/pending-task`: return {+ task_id: taskId, status: "running", created_at: timestamp, supports_queue: true, queued_tasks: [],+ };+ case `/api/tasks/${taskId}/messages`: return taskMessages;+ case `/api/chat/sessions/${sessionId}/read`: return {};+ case `/api/chat/sessions/${sessionId}/draft-restores`: return [];+ case "/api/chat/pending-tasks/has-any": return { has_pending: true };+ case "/api/projects": return { projects: [], total: 0 };+ case "/api/issues": return { issues: [], total: 0 };+ case "/api/issue-statuses": return { statuses: [] };+ case "/api/properties": return { properties: [], total: 0 };+ case "/api/quick-actions": return { quick_actions: [] };+ case "/api/client-usage": return {};+ case "/api/issue-view-preferences": return { scope_type: "workspace", scope_id: null,+ ordered_view_ids: [], hidden_view_ids: [], default_view_id: null };+ case "/api/issue-workflows": return { workflows: [] };+ case "/api/search-index/manifest": return {+ cursor: "0", issue_count: 0, comment_count: 0, project_count: 0, text_bytes: 0,+ };+ case "/api/search-index/snapshot": return {+ issues: [], comments: [], projects: [], next_after_number: 0, done: true,+ };+ case "/api/search-index/changes": return {+ issues: [], comments: [], projects: [], deleted: { issues: [], comments: [], projects: [] },+ cursor: "0", has_more: false,+ };+ case `/api/workspaces/${wsId}/members`: return [{+ id: "member-1", user_id: userId, workspace_id: wsId, role: "owner",+ name: "Fixture User", email: "[email protected]", avatar_url: null,+ }];+ case "/api/runtimes": case "/api/squads": case "/api/agent-task-snapshot":+ case "/api/invitations": case "/api/inbox": case "/api/inbox/unread-summary":+ case "/api/pins": case "/api/chat/pending-tasks": case "/api/assignee-frequency":+ case "/api/issue-views": case "/api/issue-wakeup-summaries":+ case "/api/agent-run-counts": case "/api/agent-activity-30d":+ return [];+ default: return undefined;+ }+ };+ await context.route("**/*", async route => {+ const url = new URL(route.request().url());+ if (url.origin !== origin) return route.abort();+ if (!url.pathname.startsWith("/api/")) return route.continue();+ if (url.pathname === "/api/upload-file") {+ uploadStarted = true;+ await uploadGate;+ return route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({+ id: "66666666-6666-4666-8666-666666666666", workspace_id: wsId,+ issue_id: null, comment_id: null, chat_session_id: sessionId, uploader_id: userId,+ filename: "pending.txt", url: `${origin}/fixture-upload.txt`,+ download_url: `${origin}/fixture-upload.txt`, markdown_url: `${origin}/fixture-upload.txt`,+ content_type: "text/plain", size_bytes: 4, created_at: timestamp,+ }) });+ }+ const body = responseFor(url.pathname);+ if (body === undefined) unexpected.push(url.pathname);+ await route.fulfill({ status: body === undefined ? 404 : 200,+ contentType: "application/json", body: JSON.stringify(body ?? {}) });+ });+ let invalidateMessages = () => {};+ let streamChunk = (_content: string) => {};+ await context.routeWebSocket(url => url.pathname === "/ws", socket => {+ socket.onMessage(() => {});+ invalidateMessages = () => socket.send(JSON.stringify({+ type: "chat:message", actor_id: userId, actor_type: "user",+ payload: { chat_session_id: sessionId, message_id: "arrived-hidden", role: "user" },+ }));+ streamChunk = content => {+ const payload = { task_id: taskId, seq: taskMessages.length, type: "text", content };+ taskMessages.push(payload);+ socket.send(JSON.stringify({ type: "task:message", payload, actor_type: "system", actor_id: "" }));+ };+ });++ await page.goto(`${origin}/perf/agents`, { waitUntil: "domcontentloaded" });+ const list = page.locator('[data-tab-scroll-root]').filter({ hasText: "Latest fixture message" });+ await expect(list).toBeVisible();+ const shell = list.locator('xpath=ancestor::div[@aria-hidden][1]');+ const editor = shell.locator('.tiptap[contenteditable="true"]');+ await expect(editor).toBeVisible();+ await expect(shell.getByText("Streaming fixture.", { exact: true })).toBeVisible();+ await expect(shell).toHaveCSS("transform", "none");+ const composer = await editor.elementHandle();++ await editor.fill("Last edit before closing");+ await editor.evaluate(element => {+ const files = new DataTransfer();+ files.items.add(new File(["test"], "pending.txt", { type: "text/plain" }));+ element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: files }));+ });+ await expect.poll(() => uploadStarted).toBe(true);+ await shell.locator('button:has(svg.lucide-minus)').evaluate(button => (button as HTMLButtonElement).click());+ await expect(page.locator('[data-tab-scroll-root]').filter({ hasText: "Latest fixture message" })).toHaveCount(0);+ expect(await composer?.evaluate(element => element.isConnected)).toBe(true);+ expect(await composer?.textContent()).toContain("Last edit before closing");+ expect(await composer?.evaluate(element =>+ getComputedStyle(element.closest('[aria-hidden]')!).transform)).toBe("none");+ finishUpload();+ await expect.poll(() => page.evaluate(() =>+ localStorage.getItem("multica:chat:draft-attachments:perf"))).toContain("66666666-6666-4666-8666-666666666666");++ latestContent = "Arrived while closed";+ for (let chunk = 0; chunk < 10; chunk++) {+ streamChunk(`Hidden chunk ${chunk}. `);+ await page.waitForTimeout(100);+ }+ await expect(page.locator('[data-tab-scroll-root]').filter({ hasText: "Latest fixture message" })).toHaveCount(0);+ invalidateMessages();+ await page.getByRole("button", { name: "Multica is working...", exact: true }).click();+ await expect(page.getByText("Arrived while closed", { exact: true })).toBeVisible();+ await expect(page.getByText(/Streaming fixture\. Hidden chunk 0\./)).toContainText("Hidden chunk 9.");+ expect(await composer?.evaluate(element => element.isConnected)).toBe(true);+ expect(await composer?.textContent()).toContain("Last edit before closing");+ expect(await composer?.textContent()).toContain("pending.txt");+ const reopened = page.locator('div[aria-hidden="false"]').filter({ has: page.locator('.tiptap') });+ await expect(reopened).toHaveCSS("transform", "none");++ // Reopening inside the exit animation must cancel removal of the same list.+ await reopened.locator('button:has(svg.lucide-minus)').evaluate(button => (button as HTMLButtonElement).click());+ await page.getByRole("button", { name: "Multica is working...", exact: true }).evaluate(button => (button as HTMLButtonElement).click());+ // Let the interrupted 150ms exit finish before checking that it cannot remove the reopened list.+ await page.waitForTimeout(250);+ await expect(page.getByText("Arrived while closed", { exact: true })).toBeVisible();+ expect(await composer?.evaluate(element => element.isConnected)).toBe(true);+ expect(errors).toEqual([]);+ expect(unexpected).toEqual([]);+});diff --git a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx b/packages/views/chat/components/chat-message-list.autoscroll.test.tsxindex ca0f0a7c19..8916e05c2b 100644--- a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx+++ b/packages/views/chat/components/chat-message-list.autoscroll.test.tsx@@ -359,17 +359,19 @@ function renderStreamingChat({ contentHeight = 2000 } = {}) {const qc = new QueryClient();qc.setQueryData(chatKeys.taskMessages(TASK_ID), [taskMsg(0, "Looking into it. ")]);- const view = render(+ const content = (active: boolean) => (<I18nProvider locale="en" resources={TEST_RESOURCES}><QueryClientProvider client={qc}><ChatMessageList+ active={active}messages={[]}pendingTask={{ task_id: TASK_ID, status: "running" }}availability={undefined}/></QueryClientProvider>- </I18nProvider>,+ </I18nProvider>);+ const view = render(content(true));const el = view.container.querySelector<HTMLElement>("[data-tab-scroll-root]");if (!el) throw new Error("chat list did not render a scroll container");@@ -377,6 +379,7 @@ function renderStreamingChat({ contentHeight = 2000 } = {}) {return {qc,view,+ setActive: (active: boolean) => view.rerender(content(active)),scroll: scroller(el, contentHeight),rowCount: () => view.container.querySelectorAll("[data-row-key]").length,followsAtBottom: () =>@@ -395,6 +398,54 @@ function renderStreamingChat({ contentHeight = 2000 } = {}) {}describe("ChatMessageList auto-scroll", () => {+ it("stops following and reveal polling before a closing list unmounts", () => {+ const { view, scroll, setActive, followsAtBottom } = renderStreamingChat();+ const observedBefore = observedTargets().length;+ const measure = vi.spyOn(scroll.el, "getBoundingClientRect");+ const staleHeightCallback = reportContentHeightChanged;++ setActive(false);++ expect(view.container.contains(scroll.el)).toBe(true);+ expect(followsAtBottom()).toBe("false");+ expect(observedTargets()).toHaveLength(observedBefore - 1);+ scroll.grow(120);+ scroll.shrinkViewport(72);+ scroll.browserScrollsListUp(100);+ act(() => staleHeightCallback?.());+ for (let frame = 0; frame < 20; frame++) act(() => renderFrame());++ expect(scroll.pinCalls()).toHaveLength(0);+ expect(measure).not.toHaveBeenCalled();+ });++ it("resumes following if a closing list is reopened before unmount", () => {+ const { scroll, setActive, followsAtBottom } = renderStreamingChat();++ setActive(false);+ scroll.grow(120);+ setActive(true);+ scroll.grow(120);++ expect(followsAtBottom()).toBe("auto");+ expect(scroll.pinCalls()).toHaveLength(1);+ expect(scroll.distanceFromBottom()).toBe(0);+ });++ it("preserves the reader's released follow across an interrupted close", () => {+ const { scroll, setActive, followsAtBottom } = renderStreamingChat();++ scroll.readerScrollsUp(240);+ setActive(false);+ scroll.grow(120);+ setActive(true);+ scroll.grow(120);++ expect(followsAtBottom()).toBe("false");+ expect(scroll.pinCalls()).toHaveLength(0);+ expect(scroll.distanceFromBottom()).toBe(480);+ });+it("follows a streaming reply whose row count never changes", () => {const { scroll, streamChunk, rowCount } = renderStreamingChat();diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsxindex 3071765b67..f4904ee502 100644--- a/packages/views/chat/components/chat-message-list.tsx+++ b/packages/views/chat/components/chat-message-list.tsx@@ -62,6 +62,8 @@ import { useT } from "../../i18n";// ─── Public component ────────────────────────────────────────────────────interface ChatMessageListProps {+ /** Pause bottom-stick effects while a closing floating window fades out. */+ active?: boolean;messages: ChatMessage[];/*** Server-authoritative pending-task snapshot. `null` / undefined means@@ -176,6 +178,7 @@ const LIST_COMPONENTS: Components<ChatRenderItem, ChatListContext> = {};export function ChatMessageList({+ active = true,messages,pendingTask,availability,@@ -205,6 +208,7 @@ export function ChatMessageList({const { isFollowing, onContentHeightChanged, hasReachedLiveEnd } = useStickToBottom(scrollContainerEl,pinToLiveEnd,+ active,);// Soft edge fade hinting more content above/below. Kept small so it barely// grazes full-bleed previews (image / HTML) at the edges.diff --git a/packages/views/chat/components/chat-window-messages.test.tsx b/packages/views/chat/components/chat-window-messages.test.tsxnew file mode 100644index 0000000000..4015d01060--- /dev/null+++ b/packages/views/chat/components/chat-window-messages.test.tsx@@ -0,0 +1,116 @@+import { act, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { AnimatePresence } from "motion/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { chatKeys } from "@multica/core/chat/queries";+import type { ChatMessage } from "@multica/core/types";+import { ChatWindowMessages } from "./chat-window-messages";++const fetchMessages = vi.hoisted(() => vi.fn());+vi.mock("@multica/core/api", () => ({ api: { listChatMessagesPage: fetchMessages } }));+vi.mock("@multica/core/chat/mutations", () => ({+ useRegenerateChatQuickActions: () => ({ mutateAsync: vi.fn() }),+}));+vi.mock("./chat-message-list", () => ({+ ChatMessageList: ({ active, messages }: { active: boolean; messages: ChatMessage[] }) => (+ <div data-testid="messages" data-active={active}>+ {messages.map((message) => <p key={message.id}>{message.content}</p>)}+ </div>+ ),+ ChatMessageSkeleton: () => <div data-testid="skeleton" />,+}));++function message(id: string): ChatMessage {+ return {+ id, chat_session_id: "session-1", role: "user", content: id,+ task_id: null, created_at: "2026-10-20T00:00:00Z",+ };+}++function pages(messages: ChatMessage[]) {+ return { pages: [{ messages, limit: 50, has_more: false }], pageParams: [null] };+}++function renderWindow(open: boolean) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const key = chatKeys.messagesPage("session-1");+ qc.setQueryData(key, pages([message("initial message")]));+ const content = (isOpen: boolean) => (+ <QueryClientProvider client={qc}>+ <AnimatePresence initial={false}>+ {isOpen && (+ <ChatWindowMessages+ sessionId="session-1"+ pendingTask={undefined}+ pendingTaskLoading={false}+ availability={undefined}+ onQuickAction={vi.fn()}+ quickActionsDisabled={false}+ quickActionsPendingMessageId={null}+ >+ <div>empty</div>+ </ChatWindowMessages>+ )}+ </AnimatePresence>+ </QueryClientProvider>+ );+ const view = render(content(open));+ return {+ qc,+ key,+ setOpen: (isOpen: boolean) => view.rerender(content(isOpen)),+ observers: () => qc.getQueryCache().find({ queryKey: key })?.getObserversCount() ?? 0,+ };+}++beforeEach(() => { fetchMessages.mockReset(); });++describe("floating chat message lifetime", () => {+ it("keeps message observers absent when the window starts closed", () => {+ const { observers } = renderWindow(false);+ expect(screen.queryByTestId("messages")).not.toBeInTheDocument();+ expect(observers()).toBe(0);+ expect(fetchMessages).not.toHaveBeenCalled();+ });++ it("follows immediately on open, stops during exit, then reads new data on reopen", async () => {+ const { qc, key, setOpen, observers } = renderWindow(true);+ expect(screen.getByTestId("messages")).toHaveAttribute("data-active", "true");+ expect(observers()).toBe(1);++ setOpen(false);+ expect(screen.getByTestId("messages")).toHaveAttribute("data-active", "false");+ await waitFor(() => expect(screen.queryByTestId("messages")).not.toBeInTheDocument());+ expect(observers()).toBe(0);++ act(() => qc.setQueryData(key, pages([message("arrived while closed")])));+ setOpen(true);+ expect(screen.getByText("arrived while closed")).toBeInTheDocument();+ expect(screen.getByTestId("messages")).toHaveAttribute("data-active", "true");+ expect(observers()).toBe(1);+ });++ it("cancels an interrupted exit without losing the live list", async () => {+ const { setOpen, observers } = renderWindow(true);+ const list = screen.getByTestId("messages");+ setOpen(false);+ setOpen(true);+ expect(screen.getByTestId("messages")).toBe(list);+ expect(list).toHaveAttribute("data-active", "true");+ await waitFor(() => expect(list.parentElement?.style.opacity).toBe("1"));+ expect(observers()).toBe(1);+ });++ it("fetches the full message window when its inactive cache was collected", async () => {+ const { qc, key, setOpen } = renderWindow(true);+ setOpen(false);+ await waitFor(() => expect(screen.queryByTestId("messages")).not.toBeInTheDocument());+ qc.removeQueries({ queryKey: key });+ fetchMessages.mockResolvedValue({ messages: [message("refetched after collection")], limit: 50, has_more: false });++ setOpen(true);++ expect(await screen.findByText("refetched after collection")).toBeInTheDocument();+ expect(fetchMessages).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/views/chat/components/chat-window-messages.tsx b/packages/views/chat/components/chat-window-messages.tsxnew file mode 100644index 0000000000..104b2b3b97--- /dev/null+++ b/packages/views/chat/components/chat-window-messages.tsx@@ -0,0 +1,88 @@+"use client";++import type { ReactNode } from "react";+import { useInfiniteQuery } from "@tanstack/react-query";+import { motion, useIsPresent } from "motion/react";+import type { AgentAvailability } from "@multica/core/agents";+import type { ChatPendingTask, ChatQuickAction } from "@multica/core/types";+import { chatMessagesPageOptions } from "@multica/core/chat/queries";+import { hideQueuedChatMessages } from "@multica/core/chat/pending";+import { useRegenerateChatQuickActions } from "@multica/core/chat/mutations";+import { ChatMessageList, ChatMessageSkeleton } from "./chat-message-list";++const CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX = 1_000_000;++/** Message-only observers leave with the fading list; the composer stays alive. */+export function ChatWindowMessages({+ sessionId,+ pendingTask,+ pendingTaskLoading,+ availability,+ onQuickAction,+ quickActionsDisabled,+ quickActionsPendingMessageId,+ children,+}: {+ sessionId: string | null;+ pendingTask: ChatPendingTask | null | undefined;+ pendingTaskLoading: boolean;+ availability: AgentAvailability | undefined;+ onQuickAction: (action: ChatQuickAction) => void | Promise<unknown>;+ quickActionsDisabled: boolean;+ quickActionsPendingMessageId: string | null;+ children: ReactNode;+}) {+ const isPresent = useIsPresent();+ const regenerateQuickActions = useRegenerateChatQuickActions();+ const {+ data,+ isLoading,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ } = useInfiniteQuery(chatMessagesPageOptions(sessionId ?? ""));+ const pages = sessionId ? data?.pages ?? [] : [];+ const messages = hideQueuedChatMessages(+ [...pages].reverse().flatMap((page) => page.messages),+ pendingTask ?? undefined,+ );+ // Older pages prepend rows without changing the newest window's indices.+ const olderMessageCount = pages.slice(1).reduce(+ (count, page) => count + page.messages.length,+ 0,+ );++ return (+ <motion.div+ className="flex flex-1 min-h-0 flex-col"+ initial={false}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ transition={{ duration: 0.15 }}+ >+ {sessionId && (isLoading || pendingTaskLoading) ? (+ <ChatMessageSkeleton />+ ) : messages.length > 0 || pendingTask?.task_id ? (+ <ChatMessageList+ key={sessionId}+ active={isPresent}+ messages={messages}+ pendingTask={pendingTask}+ availability={availability}+ firstItemIndex={messages.length > 0+ ? CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX - olderMessageCount+ : 0}+ hasOlderMessages={!!hasNextPage}+ isFetchingOlderMessages={isFetchingNextPage}+ onLoadOlderMessages={() => void fetchNextPage()}+ onQuickAction={onQuickAction}+ quickActionsDisabled={quickActionsDisabled}+ onRegenerateQuickActions={(message) => sessionId+ ? regenerateQuickActions.mutateAsync({ sessionId, messageId: message.id })+ : undefined}+ quickActionsPendingMessageId={quickActionsPendingMessageId}+ />+ ) : children}+ </motion.div>+ );+}diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsxindex adf89d3502..b3fe2ef50e 100644--- a/packages/views/chat/components/chat-window.tsx+++ b/packages/views/chat/components/chat-window.tsx@@ -1,8 +1,8 @@"use client";import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";-import { motion } from "motion/react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { AnimatePresence, motion } from "motion/react";import { Minus, Maximize2, Minimize2, ChevronDown, Plus, Check, Archive, Pencil, Loader2, Square } from "lucide-react";import { Button } from "@multica/ui/components/ui/button";import { cn } from "@multica/ui/lib/utils";@@ -46,7 +46,6 @@ import { AgentAccessRevokedBanner } from "./agent-access-revoked-banner";import { RuntimeRequiredBanner } from "./runtime-required-banner";import {chatSessionsOptions,- chatMessagesPageOptions,pendingChatTaskOptions,pendingChatTasksOptions,chatKeys,@@ -55,7 +54,6 @@ import {import {useCreateChatSession,useMarkChatSessionRead,- useRegenerateChatQuickActions,useSetChatSessionArchived,useSetChatSessionProject,useUpdateChatSession,@@ -65,12 +63,11 @@ import { upsertChatMessageToCaches } from "@multica/core/chat/message-cache";import { chatQuickActionsPendingOptions } from "@multica/core/chat/queries";import { useQuickActionsPendingTimeout } from "@multica/core/chat/use-quick-actions-pending-timeout";import { useQuickActionsFailureToast } from "./use-quick-actions-failure-toast";-import { hideQueuedChatMessages } from "@multica/core/chat/pending";import { removeChatMessageFromCaches } from "@multica/core/realtime";import { useChatDraftRestore } from "./use-chat-draft-restore";import { useChatTaskActions } from "./use-chat-task-actions";import { useChatInputFocus } from "./use-chat-input-focus";-import { ChatMessageList, ChatMessageSkeleton } from "./chat-message-list";+import { ChatWindowMessages } from "./chat-window-messages";import { ChatInput } from "./chat-input";import { ChatQueue } from "./chat-queue";import { EmptyState } from "./chat-empty-state";@@ -93,7 +90,6 @@ import { useLocale, useT } from "../../i18n";const uiLogger = createLogger("chat.ui");const apiLogger = createLogger("chat.api");-const CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX = 1_000_000;export function ChatWindow() {@@ -109,7 +105,6 @@ export function ChatWindow() {useQuickActionsPendingTimeout(activeSessionId ?? null, quickActionsPending);// Toast when an accepted refresh later fails in the daemon (async half).useQuickActionsFailureToast(activeSessionId ?? null);- const regenerateQuickActions = useRegenerateChatQuickActions();const selectedAgentId = useChatStore((s) => s.selectedAgentId);const selectedProjectId = useChatStore((s) => s.selectedProjectId);const setOpen = useChatStore((s) => s.setOpen);@@ -127,24 +122,6 @@ export function ChatWindow() {const { data: projects = [], isSuccess: projectsLoaded } = useQuery(projectListOptions(wsId),);- const {- data: rawMessagePages,- isLoading: messagesLoading,- fetchNextPage: fetchOlderMessages,- hasNextPage: hasOlderMessages,- isFetchingNextPage: isFetchingOlderMessages,- } = useInfiniteQuery(chatMessagesPageOptions(activeSessionId ?? ""));- // When no active session, always show empty — don't use stale cache.- // Page 0 contains the latest chronological window; later cursor pages are- // older chronological windows. Reverse pages so older fetched pages render- // above the initial latest page. The Virtuoso firstItemIndex is client-owned:- // it starts from a large stable base and only subtracts the count of loaded- // prepended rows, so concurrent server inserts cannot drift the scroll anchor.- const messagePages = activeSessionId ? rawMessagePages?.pages ?? [] : [];- const allMessages = [...messagePages].reverse().flatMap((page) => page.messages);- // Skeleton only shows for an un-cached session fetch. Cached switches- // return data synchronously — no flash. `enabled: false` (new chat)- // keeps isLoading false so the conversation starters aren't hidden.// Server-authoritative pending task. Survives refresh / reopen / session// switch because it's keyed on sessionId in the Query cache; WS events// (chat:message / chat:done / task:*) keep it invalidated in real time.@@ -153,16 +130,6 @@ export function ChatWindow() {const { data: pendingTask, isLoading: pendingTaskLoading } = useQuery(pendingChatTaskOptions(activeSessionId ?? ""),);- const showSkeleton =- !!activeSessionId && (messagesLoading || pendingTaskLoading);- const messages = hideQueuedChatMessages(allMessages, pendingTask);- const olderMessageCount = messagePages.slice(1).reduce(- (sum, page) => sum + page.messages.length,- 0,- );- const firstItemIndex = messages.length > 0- ? CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX - olderMessageCount- : 0;const pendingTaskId = pendingTask?.task_id ?? null;const stopRequestedBeforeTaskRef = useRef(false);// Durable deferred-cancellation draft restores (#5219). Same hook as the chat@@ -763,10 +730,6 @@ export function ChatWindow() {const { renderWidth, renderHeight, isAtMax, boundsReady, isDragging, toggleExpand, startDrag } = useChatResize(windowRef);- // Show the list (vs empty state) as soon as there's anything to display —- // a real message, or a pending task whose timeline will stream in.- const hasMessages = messages.length > 0 || !!pendingTaskId;-const isVisible = isOpen && (isExpanded || boundsReady);// Small screens drop the floating-card form entirely — a 90%-of-375px@@ -839,17 +802,15 @@ export function ChatWindow() {aria-hidden={!isOpen}className={containerClass}style={containerStyle}- initial={{ opacity: 0, scale: 0.95, ...motionSize }}+ initial={{ opacity: 0, ...motionSize }}animate={{opacity: isVisible ? 1 : 0,- scale: isVisible ? 1 : 0.95,...motionSize,}}transition={{width: isDragging ? { duration: 0 } : { type: "spring", duration: 0.3, bounce: 0 },height: isDragging ? { duration: 0 } : { type: "spring", duration: 0.3, bounce: 0 },opacity: { duration: 0.15 },- scale: { type: "spring", duration: 0.2, bounce: 0 },}}>{!isMobile && <ChatResizeHandles onDragStart={startDrag} />}@@ -919,45 +880,33 @@ export function ChatWindow() {</div>{/* Messages / skeleton / empty state */}- {showSkeleton ? (- <ChatMessageSkeleton />- ) : hasMessages ? (- <ChatMessageList- key={activeSessionId}- messages={messages}- pendingTask={pendingTask}- availability={availability}- firstItemIndex={firstItemIndex}- hasOlderMessages={!!hasOlderMessages}- isFetchingOlderMessages={isFetchingOlderMessages}- onLoadOlderMessages={() => void fetchOlderMessages()}- onQuickAction={(action) => handleSend(action.prompt)}- quickActionsDisabled={- !!pendingTaskId ||- isSessionArchived ||- isAgentArchived ||- isAgentAccessRevoked ||- !activeAgentRuntimeBound ||- noAgent- }- onRegenerateQuickActions={(message) =>- activeSessionId- ? regenerateQuickActions.mutateAsync({- sessionId: activeSessionId,- messageId: message.id,- })- : undefined- }- quickActionsPendingMessageId={quickActionsPending?.message_id ?? null}- />- ) : (- <EmptyState- agent={activeAgent}- hasSessions={sessions.length > 0}- onPickPrompt={sendConversationStarter}- customizeHref={customizeConversationStartersHref}- />- )}+ <AnimatePresence initial={false}>+ {isOpen && (+ <ChatWindowMessages+ sessionId={activeSessionId}+ pendingTask={pendingTask}+ pendingTaskLoading={pendingTaskLoading}+ availability={availability}+ onQuickAction={(action) => handleSend(action.prompt)}+ quickActionsDisabled={+ !!pendingTaskId ||+ isSessionArchived ||+ isAgentArchived ||+ isAgentAccessRevoked ||+ !activeAgentRuntimeBound ||+ noAgent+ }+ quickActionsPendingMessageId={quickActionsPending?.message_id ?? null}+ >+ <EmptyState+ agent={activeAgent}+ hasSessions={sessions.length > 0}+ onPickPrompt={sendConversationStarter}+ customizeHref={customizeConversationStartersHref}+ />+ </ChatWindowMessages>+ )}+ </AnimatePresence>{/* Status banner above the input — single mutually-exclusive slot.* Priority: no-agent > offline / unstable. Agent presence is thediff --git a/packages/views/chat/components/stick-to-bottom.ts b/packages/views/chat/components/stick-to-bottom.tsindex 1a4012f296..63b3572634 100644--- a/packages/views/chat/components/stick-to-bottom.ts+++ b/packages/views/chat/components/stick-to-bottom.ts@@ -126,21 +126,23 @@ export interface StickToBottom {export function useStickToBottom(scrollEl: HTMLElement | null,pinToLiveEnd: () => void,+ active = true,): StickToBottom {const followRef = useRef<LiveEndFollow | null>(null);if (followRef.current === null) {followRef.current = createLiveEndFollow();- // Unlike the transcript, the chat list is always live. Activated at- // creation, not in an effect: `followOutput` reads the latch on the- // very first render.- followRef.current.setActive(true);}const follow = followRef.current;+ // followOutput reads this latch in the same render, so an effect would update+ // it too late. Retained exit callbacks must also stop before the list unmounts.+ follow.setActive(active);+ const activeRef = useRef(active);+ activeRef.current = active;const pinRef = useRef(pinToLiveEnd);pinRef.current = pinToLiveEnd;const pin = useCallback(() => {- pinRef.current();+ if (activeRef.current) pinRef.current();}, []);// Polled rather than driven off Virtuoso's callbacks: `atBottomStateChange`@@ -150,13 +152,14 @@ export function useStickToBottom(// as the list holds still costs a handful of rect reads at open.const [hasReachedLiveEnd, setHasReachedLiveEnd] = useState(false);useEffect(() => {- if (!scrollEl || hasReachedLiveEnd) return;+ if (!active || !scrollEl || hasReachedLiveEnd) return;let frame = 0;// The scroll extent is the cheapest proxy for "some row changed size":// every late arrival that would shift the view also moves it.let lastHeight = -1;let steadySince: number | null = null;const poll = (now: number) => {+ if (!activeRef.current) return;const height = scrollEl.scrollHeight;const steady = height === lastHeight && isShowingLiveEndRow(scrollEl);lastHeight = height;@@ -174,22 +177,23 @@ export function useStickToBottom(cancelAnimationFrame(frame);clearTimeout(deadline);};- }, [scrollEl, hasReachedLiveEnd]);+ }, [active, scrollEl, hasReachedLiveEnd]);// Content grew or the viewport resized — displacement with no scroll event,// so it can never promote staged reader input.const onResize = useCallback(() => {- if (!scrollEl) return;+ if (!activeRef.current || !scrollEl) return;if (follow.onResize(distanceFromBottom(scrollEl))) pin();}, [scrollEl, follow, pin]);useEffect(() => {- if (!scrollEl) return;+ if (!active || !scrollEl) return;// Mirror of the transcript dialog's wiring with the live end at the// BOTTOM: away from it is up, so every input sign flips.let inputFrame: number | null = null;const stageInput = (delta: number) => {+ if (!activeRef.current) return;follow.input(delta);if (inputFrame !== null) cancelAnimationFrame(inputFrame);inputFrame = requestAnimationFrame(() => {@@ -252,6 +256,7 @@ export function useStickToBottom(};let atEdge = isAtLiveEnd(scrollEl);const onScroll = () => {+ if (!activeRef.current) return;const nowAtEdge = isAtLiveEnd(scrollEl);if (nowAtEdge !== atEdge) {atEdge = nowAtEdge;@@ -294,7 +299,7 @@ export function useStickToBottom(follow.pointerUp();follow.touchEnd();};- }, [scrollEl, follow, pin, onResize]);+ }, [active, scrollEl, follow, pin, onResize]);return useMemo(() => ({