Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8417 fix(chat): open the floating chat with its messages already showing (#9737)
Jiayuan Zhang249fdf2d84be
diff --git a/e2e/perf/README.md b/e2e/perf/README.mdindex 266b082046..444567a1a6 100644--- a/e2e/perf/README.md+++ b/e2e/perf/README.md@@ -49,7 +49,8 @@ pnpm exec playwright test --config=playwright.perf.config.ts floating-chat-lifetIt checks that closing removes the message list, keeps the real composer andan in-flight upload alive, shows messages received while closed on reopen, andsurvives 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.+is never scaled, and that a reopened window never paints before its message+list does. HTTP and WebSocket traffic is synthetic; no backend is needed.## When to run itdiff --git a/e2e/perf/floating-chat-lifetime.spec.ts b/e2e/perf/floating-chat-lifetime.spec.tsindex 80880f057f..23088e0aee 100644--- a/e2e/perf/floating-chat-lifetime.spec.ts+++ b/e2e/perf/floating-chat-lifetime.spec.ts@@ -98,6 +98,7 @@ test("closing floating chat releases its list and preserves the live composer",id: "member-1", user_id: userId, workspace_id: wsId, role: "owner",name: "Fixture User", email: "[email protected]", avatar_url: null,}];+ case "/api/skills": case "/api/autopilots":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":@@ -176,8 +177,30 @@ test("closing floating chat releases its list and preserves the live composer",}await expect(page.locator('[data-tab-scroll-root]').filter({ hasText: "Latest fixture message" })).toHaveCount(0);invalidateMessages();+ // MUL-8417: the reopened window must not paint before its message list does.+ await page.evaluate(() => {+ const frames: Array<{ opacity: number; listVisible: boolean }> = [];+ Object.assign(window, { __reopenFrames: frames });+ const sample = () => {+ const panel = [...document.querySelectorAll<HTMLElement>("div[aria-hidden]")]+ .find(element => element.querySelector(".tiptap"));+ const list = panel?.querySelector<HTMLElement>("[data-tab-scroll-root]");+ frames.push({+ opacity: panel ? Number(getComputedStyle(panel).opacity) : 0,+ listVisible: !!list && getComputedStyle(list).visibility === "visible",+ });+ if (frames.length < 60) requestAnimationFrame(sample);+ };+ requestAnimationFrame(sample);+ });await page.getByRole("button", { name: "Multica is working...", exact: true }).click();await expect(page.getByText("Arrived while closed", { exact: true })).toBeVisible();+ const reopenFrames = () => page.evaluate(() =>+ (window as unknown as { __reopenFrames: Array<{ opacity: number; listVisible: boolean }> }).__reopenFrames);+ await expect.poll(async () => (await reopenFrames()).length).toBe(60);+ const frames = await reopenFrames();+ expect(frames.some(frame => frame.opacity === 1)).toBe(true);+ expect(frames.filter(frame => frame.opacity > 0 && !frame.listVisible)).toEqual([]);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");diff --git a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx b/packages/views/chat/components/chat-message-list.autoscroll.test.tsxindex 8916e05c2b..37dca2c87f 100644--- a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx+++ b/packages/views/chat/components/chat-message-list.autoscroll.test.tsx@@ -7,6 +7,7 @@ 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 { resetRevealedLists } from "./stick-to-bottom";// Auto-scroll wiring: the list must keep the live end visible through streaming// growth and composer resizes, releasing only on real reader input. The latch@@ -355,7 +356,11 @@ function taskMsg(seq: number, content: string): TaskMessagePayload {return { task_id: TASK_ID, seq, type: "text", content } as TaskMessagePayload;}-function renderStreamingChat({ contentHeight = 2000 } = {}) {+function renderStreamingChat({+ contentHeight = 2000,+ revealKey,+ onRevealed,+}: { contentHeight?: number; revealKey?: string; onRevealed?: () => void } = {}) {const qc = new QueryClient();qc.setQueryData(chatKeys.taskMessages(TASK_ID), [taskMsg(0, "Looking into it. ")]);@@ -364,6 +369,8 @@ function renderStreamingChat({ contentHeight = 2000 } = {}) {<QueryClientProvider client={qc}><ChatMessageListactive={active}+ revealKey={revealKey}+ onRevealed={onRevealed}messages={[]}pendingTask={{ task_id: TASK_ID, status: "running" }}availability={undefined}@@ -543,6 +550,90 @@ describe("ChatMessageList auto-scroll", () => {expect(scroll.el.className).not.toContain("invisible");});+ // MUL-8417: the floating window remounts its list on every open. A+ // conversation already revealed in this page session has no cold content left+ // to settle, so it shows as soon as it lands — but it still has to land.+ describe("revealing a conversation again", () => {+ const frames = (count: number) => {+ for (let i = 0; i < count; i++) act(() => renderFrame());+ };+ const mountAtLiveEnd = (options: Parameters<typeof renderStreamingChat>[0]) => {+ const chat = renderStreamingChat(options);+ const box = (el: Element, top: number, bottom: number) => {+ el.getBoundingClientRect = () => ({ top, bottom }) as DOMRect;+ };+ box(chat.scroll.el, 0, VIEWPORT);+ const liveEndRow = chat.view.container.querySelector("[data-chat-live-end]");+ if (!liveEndRow) throw new Error("the newest row is not marked as the live end");+ return {+ ...chat,+ land: () => box(liveEndRow, VIEWPORT - 200, VIEWPORT - 16),+ predictBelowFold: () => box(liveEndRow, 4600, 5200),+ };+ };++ beforeEach(() => resetRevealedLists());++ it("skips the settle window once the conversation has been revealed", () => {+ const first = mountAtLiveEnd({ revealKey: "session-1" });+ first.land();+ frames(2);+ expect(first.scroll.el.className).toContain("invisible");+ frames(20);+ expect(first.scroll.el.className).not.toContain("invisible");+ first.view.unmount();++ const again = mountAtLiveEnd({ revealKey: "session-1" });+ expect(again.scroll.el.className).toContain("invisible");+ again.predictBelowFold();+ frames(20);+ expect(again.scroll.el.className).toContain("invisible");++ again.land();+ frames(2);+ expect(again.scroll.el.className).not.toContain("invisible");+ });++ it("still settles a conversation it has not revealed", () => {+ const first = mountAtLiveEnd({ revealKey: "session-1" });+ first.land();+ frames(20);+ first.view.unmount();++ const other = mountAtLiveEnd({ revealKey: "session-2" });+ other.land();+ frames(2);+ expect(other.scroll.el.className).toContain("invisible");+ });++ it("still settles every mount of an unnamed list", () => {+ const first = mountAtLiveEnd({});+ first.land();+ frames(20);+ first.view.unmount();++ const again = mountAtLiveEnd({});+ again.land();+ frames(2);+ expect(again.scroll.el.className).toContain("invisible");+ });++ it("reports the reveal, and again when a closing list is reopened", () => {+ const onRevealed = vi.fn();+ const chat = mountAtLiveEnd({ revealKey: "session-1", onRevealed });+ chat.land();+ frames(2);+ expect(onRevealed).not.toHaveBeenCalled();+ frames(20);+ expect(onRevealed).toHaveBeenCalledTimes(1);++ chat.setActive(false);+ expect(onRevealed).toHaveBeenCalledTimes(1);+ chat.setActive(true);+ expect(onRevealed).toHaveBeenCalledTimes(2);+ });+ });+it("keeps the newest content clear of a composer that grew", () => {const { scroll } = renderStreamingChat();diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsxindex ecfa259344..cf4531c0c9 100644--- a/packages/views/chat/components/chat-message-list.tsx+++ b/packages/views/chat/components/chat-message-list.tsx@@ -64,6 +64,14 @@ import { useT } from "../../i18n";interface ChatMessageListProps {/** Pause bottom-stick effects while a closing floating window fades out. */active?: boolean;+ /**+ * Names the conversation, so a later mount of it in this page session+ * reveals as soon as it lands instead of waiting out the settle window+ * (stick-to-bottom.ts). Omit to pay the settle on every mount.+ */+ revealKey?: string | null;+ /** The list became visible to the reader — on reveal, and on each reactivation after it. */+ onRevealed?: () => void;messages: ChatMessage[];/*** Server-authoritative pending-task snapshot. `null` / undefined means@@ -179,6 +187,8 @@ const LIST_COMPONENTS: Components<ChatRenderItem, ChatListContext> = {export function ChatMessageList({active = true,+ revealKey = null,+ onRevealed,messages,pendingTask,availability,@@ -209,7 +219,11 @@ export function ChatMessageList({scrollContainerEl,pinToLiveEnd,active,+ revealKey,);+ useEffect(() => {+ if (active && hasReachedLiveEnd) onRevealed?.();+ }, [active, hasReachedLiveEnd, onRevealed]);// 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);diff --git a/packages/views/chat/components/chat-window-messages.test.tsx b/packages/views/chat/components/chat-window-messages.test.tsxindex 4015d01060..743f9d16a2 100644--- a/packages/views/chat/components/chat-window-messages.test.tsx+++ b/packages/views/chat/components/chat-window-messages.test.tsx@@ -11,12 +11,28 @@ vi.mock("@multica/core/api", () => ({ api: { listChatMessagesPage: fetchMessagesvi.mock("@multica/core/chat/mutations", () => ({useRegenerateChatQuickActions: () => ({ mutateAsync: vi.fn() }),}));+const listProps = vi.hoisted(() => ({+ current: null as null | { revealKey?: string | null; onRevealed?: () => void },+}));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>- ),+ ChatMessageList: ({+ active,+ messages,+ revealKey,+ onRevealed,+ }: {+ active: boolean;+ messages: ChatMessage[];+ revealKey?: string | null;+ onRevealed?: () => void;+ }) => {+ listProps.current = { revealKey, onRevealed };+ return (+ <div data-testid="messages" data-active={active}>+ {messages.map((message) => <p key={message.id}>{message.content}</p>)}+ </div>+ );+ },ChatMessageSkeleton: () => <div data-testid="skeleton" />,}));@@ -31,22 +47,30 @@ function pages(messages: ChatMessage[]) {return { pages: [{ messages, limit: 50, has_more: false }], pageParams: [null] };}-function renderWindow(open: boolean) {+function renderWindow(+ open: boolean,+ {+ sessionId = "session-1",+ cached = true,+ onReady,+ }: { sessionId?: string | null; cached?: boolean; onReady?: () => void } = {},+) {const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });const key = chatKeys.messagesPage("session-1");- qc.setQueryData(key, pages([message("initial message")]));+ if (cached) qc.setQueryData(key, pages([message("initial message")]));const content = (isOpen: boolean) => (<QueryClientProvider client={qc}><AnimatePresence initial={false}>{isOpen && (<ChatWindowMessages- sessionId="session-1"+ sessionId={sessionId}pendingTask={undefined}pendingTaskLoading={false}availability={undefined}onQuickAction={vi.fn()}quickActionsDisabled={false}quickActionsPendingMessageId={null}+ onReady={onReady}><div>empty</div></ChatWindowMessages>@@ -63,7 +87,46 @@ function renderWindow(open: boolean) {};}-beforeEach(() => { fetchMessages.mockReset(); });+beforeEach(() => {+ fetchMessages.mockReset();+ listProps.current = null;+});++// MUL-8417: the window fades in around this area, so it must say when the area+// has something to show rather than an empty, hidden list.+describe("floating chat message readiness", () => {+ it("is ready at once for the empty state of a new chat", () => {+ const onReady = vi.fn();+ renderWindow(true, { sessionId: null, onReady });+ expect(screen.getByText("empty")).toBeInTheDocument();+ expect(onReady).toHaveBeenCalled();+ });++ it("is ready at once for the skeleton of an uncached session", () => {+ fetchMessages.mockReturnValue(new Promise(() => {}));+ const onReady = vi.fn();+ renderWindow(true, { cached: false, onReady });+ expect(screen.getByTestId("skeleton")).toBeInTheDocument();+ expect(onReady).toHaveBeenCalled();+ });++ it("leaves a list's readiness to the list, named by its session", () => {+ const onReady = vi.fn();+ renderWindow(true, { onReady });+ expect(screen.getByTestId("messages")).toBeInTheDocument();+ expect(onReady).not.toHaveBeenCalled();+ expect(listProps.current?.revealKey).toBe("session-1");+ expect(listProps.current?.onRevealed).toBe(onReady);+ });++ it("does not report ready while the area is leaving", () => {+ const onReady = vi.fn();+ const { setOpen } = renderWindow(true, { sessionId: null, onReady });+ onReady.mockClear();+ setOpen(false);+ expect(onReady).not.toHaveBeenCalled();+ });+});describe("floating chat message lifetime", () => {it("keeps message observers absent when the window starts closed", () => {diff --git a/packages/views/chat/components/chat-window-messages.tsx b/packages/views/chat/components/chat-window-messages.tsxindex 104b2b3b97..1454bd1bd5 100644--- a/packages/views/chat/components/chat-window-messages.tsx+++ b/packages/views/chat/components/chat-window-messages.tsx@@ -1,6 +1,6 @@"use client";-import type { ReactNode } from "react";+import { useEffect, type ReactNode } from "react";import { useInfiniteQuery } from "@tanstack/react-query";import { motion, useIsPresent } from "motion/react";import type { AgentAvailability } from "@multica/core/agents";@@ -21,6 +21,7 @@ export function ChatWindowMessages({onQuickAction,quickActionsDisabled,quickActionsPendingMessageId,+ onReady,children,}: {sessionId: string | null;@@ -30,6 +31,8 @@ export function ChatWindowMessages({onQuickAction: (action: ChatQuickAction) => void | Promise<unknown>;quickActionsDisabled: boolean;quickActionsPendingMessageId: string | null;+ /** This area has something to show — the window can fade in around it. */+ onReady?: () => void;children: ReactNode;}) {const isPresent = useIsPresent();@@ -51,6 +54,14 @@ export function ChatWindowMessages({(count, page) => count + page.messages.length,0,);+ const showSkeleton = !!sessionId && (isLoading || pendingTaskLoading);+ const showList = !showSkeleton && (messages.length > 0 || !!pendingTask?.task_id);++ // The skeleton and the empty state are right on their first frame; the list+ // is hidden until it lands, so it reports through `onRevealed` instead.+ useEffect(() => {+ if (isPresent && !showList) onReady?.();+ }, [isPresent, showList, onReady]);return (<motion.div@@ -60,12 +71,14 @@ export function ChatWindowMessages({exit={{ opacity: 0 }}transition={{ duration: 0.15 }}>- {sessionId && (isLoading || pendingTaskLoading) ? (+ {showSkeleton ? (<ChatMessageSkeleton />- ) : messages.length > 0 || pendingTask?.task_id ? (+ ) : showList ? (<ChatMessageListkey={sessionId}active={isPresent}+ revealKey={sessionId}+ onRevealed={onReady}messages={messages}pendingTask={pendingTask}availability={availability}diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsxindex aa560ee21a..31c8798376 100644--- a/packages/views/chat/components/chat-window.tsx+++ b/packages/views/chat/components/chat-window.tsx@@ -69,6 +69,7 @@ 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 { useChatOpenReveal } from "./use-chat-open-reveal";import { ChatWindowMessages } from "./chat-window-messages";import { ChatInput } from "./chat-input";import { ChatQueue } from "./chat-queue";@@ -731,8 +732,9 @@ export function ChatWindow() {const isExpanded = useChatStore((s) => s.isExpanded);const { renderWidth, renderHeight, isAtMax, boundsReady, isDragging, toggleExpand, startDrag } = useChatResize(windowRef);+ const { contentReady, markContentReady } = useChatOpenReveal(isOpen);- const isVisible = isOpen && (isExpanded || boundsReady);+ const isVisible = isOpen && (isExpanded || boundsReady) && contentReady;// Small screens drop the floating-card form entirely — a 90%-of-375px// "window" is all chrome and no content, so the panel goes full-screen@@ -902,6 +904,7 @@ export function ChatWindow() {noAgent}quickActionsPendingMessageId={quickActionsPending?.message_id ?? null}+ onReady={markContentReady}><EmptyStateagent={activeAgent}diff --git a/packages/views/chat/components/stick-to-bottom.ts b/packages/views/chat/components/stick-to-bottom.tsindex 63b3572634..4dad8bc280 100644--- a/packages/views/chat/components/stick-to-bottom.ts+++ b/packages/views/chat/components/stick-to-bottom.ts@@ -82,6 +82,9 @@ export function isShowingLiveEndRow(scrollEl: HTMLElement): boolean {* is the window the list waits for that to stop — raise it to absorb slower* content at the cost of showing the conversation later, lower it to paint* sooner and let late arrivals shift the view.+ *+ * A list that names its conversation pays it only on that conversation's first+ * reveal in a page session (see `revealedLists`).*/const LIVE_END_SETTLE_MS = 120;@@ -89,6 +92,39 @@ const LIVE_END_SETTLE_MS = 120;// reveal whatever Virtuoso has: a shift beats a blank chat.const REVEAL_DEADLINE_MS = 1000;+/**+ * Conversations whose list has already been revealed in this page session.+ *+ * What the settle window waits out is cold content: fonts, image decodes,+ * diagram heights. A conversation the reader has already seen here has none+ * left — fonts are loaded, images are in the memory cache, code highlighting is+ * synchronous and rich blocks reserve their session-cached height — so waiting+ * again buys nothing. It does cost: the floating chat unmounts its list on+ * close (MUL-8030), so without this every Cmd+J paid the full window again as+ * an empty panel (MUL-8417). A warm list still waits to land; it only skips the+ * settle.+ *+ * Module-level for the same reason as `rich-content/mounted-block-registry.ts`:+ * the list that would remember is the one that just unmounted. Bounded,+ * oldest-first; an evicted conversation only pays the settle once more.+ */+const MAX_TRACKED_REVEALS = 200;+const revealedLists = new Set<string>();++function markListRevealed(key: string): void {+ if (revealedLists.has(key)) return;+ if (revealedLists.size >= MAX_TRACKED_REVEALS) {+ const oldest = revealedLists.values().next();+ if (!oldest.done) revealedLists.delete(oldest.value);+ }+ revealedLists.add(key);+}++/** Test-only: the registry outlives individual lists by design. */+export function resetRevealedLists(): void {+ revealedLists.clear();+}+export interface StickToBottom {/** For `followOutput`: the reader is still following the live end. */isFollowing(): boolean;@@ -122,11 +158,15 @@ export interface StickToBottom {* releases and the list cannot be scrolled at all (MUL-6879). An index-based* scroll to the last row is what Virtuoso's own `followOutput` does, and it* converges because Virtuoso measures that row before deciding where to stop.+ *+ * `revealKey` names the conversation for `revealedLists`; without one, every+ * mount pays the settle window.*/export function useStickToBottom(scrollEl: HTMLElement | null,pinToLiveEnd: () => void,active = true,+ revealKey: string | null = null,): StickToBottom {const followRef = useRef<LiveEndFollow | null>(null);if (followRef.current === null) {@@ -151,6 +191,13 @@ export function useStickToBottom(// on the frame the correcting scroll lands. A frame loop that stops as soon// as the list holds still costs a handful of rect reads at open.const [hasReachedLiveEnd, setHasReachedLiveEnd] = useState(false);+ // Read once at mount: the registry is bookkeeping, not render state.+ const [settleMs] = useState(() =>+ revealKey !== null && revealedLists.has(revealKey) ? 0 : LIVE_END_SETTLE_MS,+ );+ useEffect(() => {+ if (hasReachedLiveEnd && revealKey !== null) markListRevealed(revealKey);+ }, [hasReachedLiveEnd, revealKey]);useEffect(() => {if (!active || !scrollEl || hasReachedLiveEnd) return;let frame = 0;@@ -164,10 +211,12 @@ export function useStickToBottom(const steady = height === lastHeight && isShowingLiveEndRow(scrollEl);lastHeight = height;if (!steady) steadySince = null;- else if (steadySince === null) steadySince = now;- else if (now - steadySince >= LIVE_END_SETTLE_MS) {- setHasReachedLiveEnd(true);- return;+ else {+ steadySince ??= now;+ if (now - steadySince >= settleMs) {+ setHasReachedLiveEnd(true);+ return;+ }}frame = requestAnimationFrame(poll);};@@ -177,7 +226,7 @@ export function useStickToBottom(cancelAnimationFrame(frame);clearTimeout(deadline);};- }, [active, scrollEl, hasReachedLiveEnd]);+ }, [active, scrollEl, hasReachedLiveEnd, settleMs]);// Content grew or the viewport resized — displacement with no scroll event,// so it can never promote staged reader input.diff --git a/packages/views/chat/components/use-chat-open-reveal.test.ts b/packages/views/chat/components/use-chat-open-reveal.test.tsnew file mode 100644index 0000000000..8872ffdc6e--- /dev/null+++ b/packages/views/chat/components/use-chat-open-reveal.test.ts@@ -0,0 +1,58 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, renderHook } from "@testing-library/react";+import { OPEN_REVEAL_DEADLINE_MS, useChatOpenReveal } from "./use-chat-open-reveal";++describe("useChatOpenReveal", () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ function renderReveal(initialOpen: boolean) {+ return renderHook(+ ({ isOpen }: { isOpen: boolean }) => useChatOpenReveal(isOpen),+ { initialProps: { isOpen: initialOpen } },+ );+ }++ it("holds an open window until its message area reports ready", () => {+ const { result, rerender } = renderReveal(false);+ rerender({ isOpen: true });+ expect(result.current.contentReady).toBe(false);++ act(() => result.current.markContentReady());+ expect(result.current.contentReady).toBe(true);+ });++ // MUL-8417: readiness belongs to one open. Carrying it over would let the+ // next open fade in around a list that has not landed yet.+ it("waits again on every open", () => {+ const { result, rerender } = renderReveal(true);+ act(() => result.current.markContentReady());++ rerender({ isOpen: false });+ expect(result.current.contentReady).toBe(false);++ rerender({ isOpen: true });+ expect(result.current.contentReady).toBe(false);+ act(() => result.current.markContentReady());+ expect(result.current.contentReady).toBe(true);+ });++ it("opens anyway once the deadline passes", () => {+ const { result } = renderReveal(true);++ act(() => vi.advanceTimersByTime(OPEN_REVEAL_DEADLINE_MS - 1));+ expect(result.current.contentReady).toBe(false);+ act(() => vi.advanceTimersByTime(1));+ expect(result.current.contentReady).toBe(true);+ });++ it("does not let a closed window's deadline reveal the next open", () => {+ const { result, rerender } = renderReveal(true);+ act(() => vi.advanceTimersByTime(OPEN_REVEAL_DEADLINE_MS - 50));+ rerender({ isOpen: false });+ rerender({ isOpen: true });++ act(() => vi.advanceTimersByTime(50));+ expect(result.current.contentReady).toBe(false);+ });+});diff --git a/packages/views/chat/components/use-chat-open-reveal.ts b/packages/views/chat/components/use-chat-open-reveal.tsnew file mode 100644index 0000000000..d658dcacdf--- /dev/null+++ b/packages/views/chat/components/use-chat-open-reveal.ts@@ -0,0 +1,41 @@+"use client";++import { useCallback, useEffect, useState } from "react";++/**+ * Longest the floating window waits for its message area before fading in+ * anyway. Covers a cold first open — a list that has to land and then settle —+ * so that one still appears composed; past it, a list that keeps moving opens+ * behind its own reveal rather than leaving the toggle looking dead.+ */+export const OPEN_REVEAL_DEADLINE_MS = 300;++/**+ * Holds the floating window's fade-in until its message area can paint.+ *+ * Closing unmounts the message list (MUL-8030), so each open mounts a fresh one,+ * and a fresh list stays invisible until it has landed on the newest message+ * (MUL-6879). Fading the window in on the keypress put that wait on screen as a+ * panel with a header and a composer and nothing between them, on every open+ * (MUL-8417). The window now starts its fade when the area reports ready.+ *+ * Readiness is per open: closing clears it, so the next open waits again.+ */+export function useChatOpenReveal(isOpen: boolean): {+ contentReady: boolean;+ markContentReady: () => void;+} {+ const [contentReady, setContentReady] = useState(false);+ const markContentReady = useCallback(() => setContentReady(true), []);++ useEffect(() => {+ if (!isOpen) return;+ const deadline = setTimeout(markContentReady, OPEN_REVEAL_DEADLINE_MS);+ return () => {+ clearTimeout(deadline);+ setContentReady(false);+ };+ }, [isOpen, markContentReady]);++ return { contentReady, markContentReady };+}