Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7563 perf(chat): virtualize session history lists (#8637)
DuellingSwordf02a6aa60e57
diff --git a/e2e/perf/README.md b/e2e/perf/README.mdindex 444567a1a6..439e4caad3 100644--- a/e2e/perf/README.md+++ b/e2e/perf/README.md@@ -6,6 +6,27 @@ replaced 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.+## Chat session lists++`chat-session-lists.spec.ts` exercises the real Chat history, archive and floating+history dropdown against synthetic HTTP/WebSocket boundaries. It checks that+2,000 sessions mount fewer than 40 rows, can scroll to and select the last row,+and also covers compact layout and empty/single-session dropdowns. Each measured+surface emits a JSON record and a test attachment with mounted rows and time to+readiness; timings are illustrative samples, not performance thresholds.++Run against a local production Web build (no API server or account needed):++```bash+PLAYWRIGHT_BASE_URL=http://localhost:3000 pnpm exec playwright test --config=playwright.perf.config.ts chat-session-lists.spec.ts+# Measure the original full-list implementation with the same fixture:+CHAT_LIST_BASELINE=1 PLAYWRIGHT_BASE_URL=http://localhost:3001 pnpm exec playwright test --config=playwright.perf.config.ts chat-session-lists.spec.ts+```++`scripts/perf-compare.mjs` remains scoped to the comment-typing scenario below;+its report format and comparisons are unchanged. Session data is still fetched+in full: these checks measure rendering, not API pagination or network savings.+## What it runs againstThe real Next.js production build, the real page, the real shell and CSS, thediff --git a/e2e/perf/chat-session-lists.spec.ts b/e2e/perf/chat-session-lists.spec.tsnew file mode 100644index 0000000000..a853c5f645--- /dev/null+++ b/e2e/perf/chat-session-lists.spec.ts@@ -0,0 +1,216 @@+import { expect, test, type Locator, type Page } from "@playwright/test";++// Real production UI, synthetic API/WS only. Run with CHAT_LIST_BASELINE=1+// against the unmodified build to measure the same workload without the+// window-size assertions. Never send these fixtures to a real backend.+const baseline = process.env.CHAT_LIST_BASELINE === "1";+const count = 2000;+const wsId = "11111111-1111-4111-8111-111111111111";+const userId = "22222222-2222-4222-8222-222222222222";+const agentId = "33333333-3333-4333-8333-333333333333";+const at = "2026-01-01T00:00:00Z";+const workspace = {+ id: wsId, name: "Perf", slug: "perf", description: null, context: null,+ settings: { github_enabled: false }, repos: [], issue_prefix: "PERF",+ avatar_url: null, created_at: at, updated_at: at,+};++function sessions(archived: boolean, size = count) {+ return Array.from({ length: size }, (_, i) => ({+ id: `${archived ? "bbbb" : "aaaa"}${String(i).padStart(4, "0")}-4444-4444-8444-444444444444`,+ workspace_id: wsId, agent_id: agentId, creator_id: userId,+ title: `${archived ? "Archived" : "Session"} ${String(i).padStart(4, "0")}`,+ status: archived ? "archived" : "active", pinned: false,+ has_unread: false, unread_count: 0, last_message: null,+ created_at: at, updated_at: new Date(Date.parse(at) - i * 1000).toISOString(),+ }));+}++test.use({ viewport: { width: 1280, height: 800 }, locale: "en-US", serviceWorkers: "block" });++function responseFor(path: string, rows: ReturnType<typeof sessions>): unknown {+ switch (path) {+ case "/api/config": return { feature_flags: {}, allow_signup: true };+ case "/api/me": return {+ id: userId, name: "Perf User", email: "[email protected]", avatar_url: null,+ language: "en", onboarded_at: at, onboarding_questionnaire: { source: "other" },+ created_at: at, updated_at: at,+ };+ case "/api/workspaces": return [workspace];+ case "/api/client-usage": return {};+ case "/api/chat/sessions": return rows;+ case "/api/chat/pending-tasks": return { tasks: [] };+ case "/api/chat/pending-tasks/has-any": return { has_pending: false };+ 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/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`:+ case "/api/agents": 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/assignee-frequency":+ case "/api/skills": case "/api/autopilots":+ case "/api/agent-run-counts": case "/api/agent-activity-30d":+ return [];+ }+ const match = /^\/api\/chat\/sessions\/([^/]+)(.*)$/.exec(path);+ if (!match) return undefined;+ const session = rows.find((row) => row.id === match[1]);+ if (!session) return undefined;+ switch (match[2]) {+ case "/messages/page": return { messages: [], limit: 50, has_more: false, next_cursor: null };+ case "/messages": return [];+ case "/pending-task": case "/read": return {};+ case "/draft-restores": return { restores: [] };+ case "": return session;+ default: return undefined;+ }+}++async function setup(page: Page, baseURL: string, withArchive: boolean, size = count) {+ const origin = new URL(baseURL).origin;+ const rows = [...sessions(false, size), ...(withArchive ? sessions(true, size) : [])];+ const errors: string[] = [];+ const unexpected: string[] = [];+ page.on("pageerror", (error) => errors.push(error.message));+ await page.context().addCookies([+ { name: "multica_logged_in", value: "1", url: origin },+ { name: "last_workspace_slug", value: "perf", url: origin },+ ]);+ await page.addInitScript(() => {+ localStorage.setItem("multica:chat:floatingChatEnabled", "true");+ });+ await page.routeWebSocket(() => true, (ws) => { ws.onMessage(() => {}); });+ await page.route("**/*", async (route) => {+ const url = new URL(route.request().url());+ if (url.origin !== origin) {+ unexpected.push(url.origin + url.pathname);+ return route.abort();+ }+ if (!url.pathname.startsWith("/api/")) return route.continue();+ const body = responseFor(url.pathname, rows);+ if (body === undefined) {+ unexpected.push(`${route.request().method()} ${url.pathname}${url.search}`);+ return route.fulfill({ status: 404, contentType: "application/json", body: "{}" });+ }+ return route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(body) });+ });+ return { errors, unexpected };+}++// Find the actual scroll owner, so both the original full list and the+// virtualized list receive the same user-visible scroll operation.+async function scrollToEnd(row: Locator) {+ await row.evaluate((el) => {+ for (let parent = el.parentElement; parent; parent = parent.parentElement) {+ if (parent.scrollHeight > parent.clientHeight && /auto|scroll/.test(getComputedStyle(parent).overflowY)) {+ parent.scrollTop = parent.scrollHeight;+ return;+ }+ }+ throw new Error("No scrollable list ancestor");+ });+}++async function record(page: Page, surface: string, started: number, rows: Locator) {+ await page.evaluate(() => new Promise<void>((done) => requestAnimationFrame(() => requestAnimationFrame(() => done()))));+ const mounted = await rows.count();+ const report = { surface, baseline, sessions: count, mounted_rows: mounted, ready_ms: Date.now() - started };+ await test.info().attach(surface, { body: JSON.stringify(report, null, 2), contentType: "application/json" });+ // Like the other performance scenario, emit measurements for the comparison log.+ console.log(JSON.stringify(report));+ if (!baseline) expect(mounted).toBeLessThan(40);+ else expect(mounted).toBe(count);+}++for (const withArchive of [false, true]) {+ test(`chat history with${withArchive ? "" : "out"} an archive footer`, async ({ page, baseURL }) => {+ const state = await setup(page, baseURL!, withArchive);+ const started = Date.now();+ await page.goto("/perf/chat");+ const first = page.getByText("Session 0000", { exact: true });+ await expect(first).toBeVisible();+ await record(page, `history-${withArchive}`, started, page.getByText(/^Session \d{4}$/));+ await page.screenshot({ path: test.info().outputPath("history.png") });+ await scrollToEnd(first);+ const last = page.getByText("Session 1999", { exact: true });+ await expect(last).toBeVisible();+ await last.locator("xpath=ancestor::*[@tabindex='0'][1]").press("Enter");+ await expect(page).toHaveURL(/session=aaaa1999/);+ if (withArchive) {+ const archiveStarted = Date.now();+ await page.getByRole("button", { name: /Archived.*2000/ }).click();+ const archived = page.getByText("Archived 0000", { exact: true });+ await expect(archived).toBeVisible();+ await record(page, "archived", archiveStarted, page.getByText(/^Archived \d{4}$/));+ await scrollToEnd(archived);+ await expect(page.getByText("Archived 1999", { exact: true })).toBeVisible();+ }+ expect(state.errors).toEqual([]);+ expect(state.unexpected).toEqual([]);+ });+}++test("floating chat history scrolls to an offscreen session", async ({ page, baseURL }) => {+ const state = await setup(page, baseURL!, false);+ await page.addInitScript(() => localStorage.setItem("multica:chat:isOpen", "true"));+ await page.goto("/perf/inbox");+ const started = Date.now();+ await page.getByRole("button", { name: "New chat", exact: true }).click();+ const history = page.getByRole("group", { name: "Chat history" });+ await expect(history).toBeVisible();+ await record(page, "dropdown", started, history.getByText(/^Session \d{4}$/));+ await page.screenshot({ path: test.info().outputPath("dropdown.png") });+ await scrollToEnd(history.getByText("Session 0000", { exact: true }));+ const last = history.getByText("Session 1999", { exact: true });+ await expect(last).toBeVisible();+ await last.click();+ await expect(history).not.toBeVisible();+ await expect(page.getByRole("button", { name: "Session 1999", exact: true })).toBeVisible();+ expect(state.errors).toEqual([]);+ expect(state.unexpected).toEqual([]);+});++test("compact chat list can select its last session", async ({ page, baseURL }) => {+ const state = await setup(page, baseURL!, false);+ await page.setViewportSize({ width: 390, height: 844 });+ await page.goto("/perf/chat");+ const first = page.getByText("Session 0000", { exact: true });+ await expect(first).toBeVisible();+ await scrollToEnd(first);+ await page.getByText("Session 1999", { exact: true }).click();+ await expect(page).toHaveURL(/session=aaaa1999/);+ expect(state.errors).toEqual([]);+ expect(state.unexpected).toEqual([]);+});++for (const size of [0, 1]) {+ test(`floating history with ${size} sessions`, async ({ page, baseURL }) => {+ const state = await setup(page, baseURL!, false, size);+ await page.addInitScript(() => localStorage.setItem("multica:chat:isOpen", "true"));+ await page.goto("/perf/inbox");+ await page.getByRole("button", { name: "New chat", exact: true }).click();+ if (size === 0) {+ await expect(page.getByText("No previous chats", { exact: true })).toBeVisible();+ } else {+ const history = page.getByRole("group", { name: "Chat history" });+ await expect(history.getByText("Session 0000", { exact: true })).toBeVisible();+ const bounds = await history.boundingBox();+ expect(bounds!.height).toBeGreaterThan(44);+ expect(bounds!.height).toBeLessThan(160);+ }+ expect(state.errors).toEqual([]);+ expect(state.unexpected).toEqual([]);+ });+}diff --git a/packages/core/chat/queries.test.ts b/packages/core/chat/queries.test.tsindex a7108f937f..0b94be88ca 100644--- a/packages/core/chat/queries.test.ts+++ b/packages/core/chat/queries.test.ts@@ -1,3 +1,4 @@+// @vitest-environment nodeimport { describe, expect, it } from "vitest";import type { TaskMessagePayload } from "../types/events";@@ -142,6 +143,17 @@ describe("sortChatSessions", () => {sortChatSessions(input);expect(input.map((s) => s.id)).toEqual(snapshot);});++ it("preserves server order and session identities when activity times tie", () => {+ const first = session({ id: "first" });+ const second = session({ id: "second" });+ const pinned = session({ id: "pinned", pinned: true });++ const sorted = sortChatSessions([first, pinned, second]);+ expect(sorted).toEqual([pinned, first, second]);+ expect(sorted[1]).toBe(first);+ expect(sorted[2]).toBe(second);+ });});describe("countUnreadChatSessions", () => {diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.tsindex a07c3d0764..58eaf211c4 100644--- a/packages/core/chat/queries.ts+++ b/packages/core/chat/queries.ts@@ -96,12 +96,16 @@ function sessionActivityTime(s: ChatSession): number {* order when pin timestamps aren't carried in the list payload.*/export function sortChatSessions(sessions: ChatSession[]): ChatSession[] {- return [...sessions].sort((a, b) => {- const ap = a.pinned ? 1 : 0;- const bp = b.pinned ? 1 : 0;- if (ap !== bp) return bp - ap;- return sessionActivityTime(b) - sessionActivityTime(a);- });+ // Parse dates once per session, rather than on each comparison.+ return sessions+ .map((session) => ({ session, activity: sessionActivityTime(session) }))+ .sort((a, b) => {+ const ap = a.session.pinned ? 1 : 0;+ const bp = b.session.pinned ? 1 : 0;+ if (ap !== bp) return bp - ap;+ return b.activity - a.activity;+ })+ .map(({ session }) => session);}/**diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsxindex 2425d2df1b..4695e1a4b4 100644--- a/packages/views/chat/chat-page.tsx+++ b/packages/views/chat/chat-page.tsx@@ -256,7 +256,7 @@ export function ChatPage() {);const listBody = (- <div className="px-2 py-1">+ <div className="min-h-0 flex-1 px-2 py-1"><ChatThreadListsessions={c.sessions}agents={c.agents}@@ -445,7 +445,7 @@ export function ChatPage() {{noAgentPage ? (noAgentState) : (- <div className="flex-1 min-h-0 overflow-y-auto">{listBody}</div>+ <div className="flex min-h-0 flex-1 flex-col">{listBody}</div>)}</div>);@@ -460,7 +460,7 @@ export function ChatPage() {<div className="flex min-h-0 flex-1"><ListColumn collapsed={listCollapsed} width="list">{listHeader}- <div className="flex-1 min-h-0 overflow-y-auto">{listBody}</div>+ <div className="flex min-h-0 flex-1 flex-col">{listBody}</div></ListColumn><div className="flex h-full min-h-0 min-w-0 flex-1 flex-col">{listCollapsed && !c.currentSession && <PageHeader>{newChatButton}</PageHeader>}diff --git a/packages/views/chat/components/chat-thread-list.test.tsx b/packages/views/chat/components/chat-thread-list.test.tsxindex a8338b7ca5..5135b4e570 100644--- a/packages/views/chat/components/chat-thread-list.test.tsx+++ b/packages/views/chat/components/chat-thread-list.test.tsx@@ -1,5 +1,6 @@import { describe, expect, it, vi, beforeEach } from "vitest";import { fireEvent, render, screen } from "@testing-library/react";+import { VirtuosoMockContext } from "react-virtuoso";import { I18nProvider } from "@multica/core/i18n/react";import type { Agent, ChatSession } from "@multica/core/types";import enChat from "../../locales/en/chat.json";@@ -97,21 +98,47 @@ function renderList(} = {},) {render(- <I18nProvider locale="en" resources={TEST_RESOURCES}>- <ChatThreadList- sessions={renderedSessions}- agents={renderedAgents}- activeSessionId={activeSessionId}- onSelectSession={onSelectSession}- onArchive={onArchive}- />- </I18nProvider>,+ <VirtuosoMockContext.Provider value={{ viewportHeight: 560, itemHeight: 56 }}>+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <ChatThreadList+ sessions={renderedSessions}+ agents={renderedAgents}+ activeSessionId={activeSessionId}+ onSelectSession={onSelectSession}+ onArchive={onArchive}+ />+ </I18nProvider>+ </VirtuosoMockContext.Provider>,);return { onArchive, onSelectSession };}const ARCHIVE_LABEL = enChat.list.archive;+describe("ChatThreadList windowing", () => {+ it("mounts only a window of a long history without an archive footer", () => {+ renderList(null, {+ renderedSessions: Array.from({ length: 200 }, (_, i) => makeSession({ id: `history-${i}` })),+ });+ expect(screen.getByText("Chat history-0")).toBeInTheDocument();+ expect(screen.getAllByTestId("avatar-agent-1").length).toBeLessThan(30);+ expect(screen.queryByText("Chat history-199")).not.toBeInTheDocument();+ });++ it("keeps the archive entry reachable and windows archived sessions", () => {+ renderList(null, {+ renderedSessions: [+ ...sessions,+ ...Array.from({ length: 200 }, (_, i) => makeSession({ id: `archived-${i}`, status: "archived" })),+ ],+ });+ fireEvent.click(screen.getByRole("button", { name: /Archived.*200/ }));+ expect(screen.getByText("Chat archived-0")).toBeInTheDocument();+ expect(screen.getAllByTestId("avatar-agent-1").length).toBeLessThan(30);+ expect(screen.queryByText("Chat archived-199")).not.toBeInTheDocument();+ });+});+describe("ChatThreadList archive delegation", () => {beforeEach(() => {setActiveSession.mockClear();@@ -160,17 +187,7 @@ describe("ChatThreadList no_response preview (MUL-4351)", () => {message_kind: "no_response",},});- render(- <I18nProvider locale="en" resources={TEST_RESOURCES}>- <ChatThreadList- sessions={[session]}- agents={[agent]}- activeSessionId={null}- onSelectSession={vi.fn()}- onArchive={vi.fn()}- />- </I18nProvider>,- );+ renderList(null, { renderedSessions: [session] });expect(screen.getByText(enChat.list.no_response_preview)).toBeInTheDocument();// The stored English fallback body must not leak into the preview.expect(diff --git a/packages/views/chat/components/chat-thread-list.tsx b/packages/views/chat/components/chat-thread-list.tsxindex 202aeeb2b8..b5558436d3 100644--- a/packages/views/chat/components/chat-thread-list.tsx+++ b/packages/views/chat/components/chat-thread-list.tsx@@ -38,6 +38,7 @@ import { resolveClickIntent, useOptionalNavigation } from "../../navigation";import { createLogger } from "@multica/core/logger";import { removeChatMessageFromCaches } from "@multica/core/realtime";import { useLocale, useT } from "../../i18n";+import { SessionHistoryList } from "./session-history-list";const apiLogger = createLogger("chat.api");@@ -482,11 +483,11 @@ export function ChatThreadList({// here (via each row's hover actions).if (view === "archived") {return (- <>+ <div className="flex h-full min-h-0 flex-col"><buttontype="button"onClick={() => setView("history")}- className="flex w-full items-center gap-1.5 rounded-md px-2 py-2 text-left text-caption font-medium text-muted-foreground outline-none transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring"+ className="flex w-full shrink-0 items-center gap-1.5 rounded-md px-2 py-2 text-left text-caption font-medium text-muted-foreground outline-none transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring"><ChevronLeft className="size-4 shrink-0" /><span className="truncate">{t(($) => $.list.archived_title)}</span>@@ -494,8 +495,10 @@ export function ChatThreadList({{archivedSessions.length}</span></button>- {archivedSessions.map(renderRow)}- </>+ <div className="min-h-0 flex-1">+ <SessionHistoryList sessions={archivedSessions} renderRow={renderRow} />+ </div>+ </div>);}@@ -527,10 +530,11 @@ export function ChatThreadList({}return (- <>- {historySessions.map(renderRow)}- {archivedEntry}- </>+ <SessionHistoryList+ sessions={historySessions}+ renderRow={renderRow}+ footer={archivedEntry}+ />);}diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsxindex 31c8798376..cdbbe45698 100644--- a/packages/views/chat/components/chat-window.tsx+++ b/packages/views/chat/components/chat-window.tsx@@ -75,6 +75,7 @@ import { ChatInput } from "./chat-input";import { ChatQueue } from "./chat-queue";import { EmptyState } from "./chat-empty-state";import { SessionRenameInput } from "./session-rename-input";+import { SessionHistoryList } from "./session-history-list";import { ChatResizeHandles } from "./chat-resize-handles";import { useChatContextItems } from "./use-chat-context-items";import { useChatResize } from "./use-chat-resize";@@ -1581,7 +1582,7 @@ function SessionDropdown({</div><PopoverContentalign="start"- className="max-h-96 w-auto min-w-[max(16rem,var(--anchor-width,16rem))] max-w-96 gap-0 overflow-y-auto p-1"+ className="max-h-96 w-auto min-w-[max(16rem,var(--anchor-width,16rem))] max-w-96 gap-0 overflow-hidden p-1"onClick={(e) => e.stopPropagation()}>{historySessions.length === 0 ? (@@ -1593,7 +1594,12 @@ function SessionDropdown({<div className="px-1.5 py-1 text-caption font-medium text-muted-foreground">{t(($) => $.window.history_group)}</div>- {historySessions.map(renderRow)}+ <SessionHistoryList+ sessions={historySessions}+ renderRow={renderRow}+ estimatedRowHeight={44}+ maxHeight={320}+ /></div>)}</PopoverContent>diff --git a/packages/views/chat/components/session-history-list.tsx b/packages/views/chat/components/session-history-list.tsxnew file mode 100644index 0000000000..ddeefd180f--- /dev/null+++ b/packages/views/chat/components/session-history-list.tsx@@ -0,0 +1,44 @@+"use client";++import type { ReactNode } from "react";+import { Virtuoso, type Components } from "react-virtuoso";+import type { ChatSession } from "@multica/core/types";++type ListContext = { footer?: ReactNode };++// 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}</>,+};++export function SessionHistoryList({+ sessions,+ renderRow,+ footer,+ maxHeight,+ estimatedRowHeight = 56,+}: {+ sessions: ChatSession[];+ renderRow: (session: ChatSession) => ReactNode;+ footer?: ReactNode;+ maxHeight?: number;+ estimatedRowHeight?: number;+}) {+ return (+ <Virtuoso+ style={{+ height: maxHeight == null+ ? "100%"+ : Math.min(maxHeight, sessions.length * estimatedRowHeight),+ }}+ data={sessions}+ defaultItemHeight={estimatedRowHeight}+ increaseViewportBy={200}+ computeItemKey={(_, session) => session.id}+ itemContent={(_, session) => renderRow(session)}+ components={COMPONENTS}+ context={{ footer }}+ />+ );+}diff --git a/scripts/perf-compare.mjs b/scripts/perf-compare.mjsindex 2f56b7f722..d7f4cf236d 100755--- a/scripts/perf-compare.mjs+++ b/scripts/perf-compare.mjs@@ -228,7 +228,7 @@ async function measure(ref, label) {const measureStart = Date.now();let scenarioExit = 0;try {- run("pnpm", ["exec", "playwright", "test", "--config=playwright.perf.config.ts"], {+ run("pnpm", ["exec", "playwright", "test", "--config=playwright.perf.config.ts", "typing-under-live-runs.spec.ts"], {cwd: repoRoot,env: {...process.env,