🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✅ test(e2e): add local render budgets for long message lists (#22937)
YuTengjingfbff0a8fe525
diff --git a/e2e/CLAUDE.md b/e2e/CLAUDE.mdindex 0fd6b95b1b4..04d3ca07ece 100644--- a/e2e/CLAUDE.md+++ b/e2e/CLAUDE.md@@ -45,6 +45,8 @@ Related: [LOBE-2417](https://linear.app/lobehub/issue/LOBE-2417/建立核心产@home # Home 模块@community # 社区模块@routes # 核心路由+@perf # 渲染预算(React Profiler),见下方「渲染预算」+@perf-local # 仅本地的长列表渲染预算:默认套件和 CI 都不跑,`bun run test:perf:local` 单独串行跑,预算在 src/performance/budgets.ts```### 渲染预算(`@perf`)diff --git a/e2e/cucumber.config.js b/e2e/cucumber.config.jsindex 0fb7048615b..2b484266c8b 100644--- a/e2e/cucumber.config.js+++ b/e2e/cucumber.config.js@@ -6,8 +6,11 @@ const parsedParallel = Number(process.env.E2E_PARALLEL || process.env.CUCUMBER_Pconst requestedParallel = Number.isFinite(parsedParallel) ? parsedParallel : 1;const canRunInParallel = Boolean(process.env.BASE_URL);// `@perf` scenarios need a `LOBE_REACT_PROFILING=1` build and run on their own-// (`bun run test:perf`), so the ordinary suite skips them.-const perfRun = process.env.E2E_PERF === '1';+// (`bun run test:perf`, also the CI `Render Budget` job). `@perf-local` scenarios+// are local-only measuring tools (`bun run test:perf:local`) kept out of CI to save+// runner time. The ordinary suite skips both.+const perfTags = { 1: '@perf', local: '@perf-local' }[process.env.E2E_PERF ?? ''];+const perfRun = Boolean(perfTags);export default {format: reportsEnabled@@ -23,6 +26,6 @@ export default {require: ['src/steps/**/!(*.test).ts', 'src/support/**/*.ts'],requireModule: ['tsx/cjs'],retry: 0,- tags: perfRun ? '@perf and not @skip' : 'not @skip and not @perf',+ tags: perfRun ? `${perfTags} and not @skip` : 'not @skip and not @perf and not @perf-local',timeout: 30_000,};diff --git a/e2e/package.json b/e2e/package.jsonindex c7f5902a20e..d145d914504 100644--- a/e2e/package.json+++ b/e2e/package.json@@ -11,6 +11,7 @@"test:headed": "cross-env HEADLESS=false cucumber-js --config cucumber.config.js","test:oidc": "cucumber-js --config cucumber.config.js --tags '@oidc'","test:perf": "cross-env E2E_PERF=1 cucumber-js --config cucumber.config.js",+ "test:perf:local": "cross-env E2E_PERF=local cucumber-js --config cucumber.config.js","test:routes": "cucumber-js --config cucumber.config.js --tags '@routes'","test:routes:ci": "cucumber-js --config cucumber.config.js --tags '@routes and not @ci-skip'","test:smoke": "cucumber-js --config cucumber.config.js --tags '@smoke'",diff --git a/e2e/src/features/performance/long-message-list.feature b/e2e/src/features/performance/long-message-list.featurenew file mode 100644index 00000000000..e7f80c75011--- /dev/null+++ b/e2e/src/features/performance/long-message-list.feature@@ -0,0 +1,26 @@+@perf-local @agent @conversation+Feature: 长对话消息列表的渲染速度预算+ 作为用户,打开一个有几百上千条消息的对话时,我希望:+ - 最新一条消息很快出现在屏幕上,可以直接阅读+ - 用滚轮一路翻到最早的消息、再翻回底部的过程中不卡顿+ - 列表只渲染视口附近的消息,不因对话变长而越来越慢++ 对话包含工具调用、代码块、图片和表格,预算定义见 e2e/src/performance/budgets.ts。++ Background:+ Given 用户已登录系统++ @PERF-LONG-LIST-001 @P0+ Scenario Outline: 打开 <count> 条消息的对话并滚动到顶、再滚回底部都在预算内+ Given 用户有一个包含 <count> 条消息的长对话+ When 用户打开这个长对话+ Then 最新消息应在首屏可读预算内出现+ When 用户用滚轮从底部滚到对话最早的消息+ Then 这次滚动的帧间隔和消息行挂载数应在预算内+ When 用户用滚轮从顶部滚回对话最新的消息+ Then 这次滚动的帧间隔和消息行挂载数应在预算内++ Examples:+ | count |+ | 500 |+ | 1000 |diff --git a/e2e/src/performance/budgets.ts b/e2e/src/performance/budgets.tsnew file mode 100644index 00000000000..da9e17789b9--- /dev/null+++ b/e2e/src/performance/budgets.ts@@ -0,0 +1,52 @@+/**+ * Render budgets for a long message list (T-13850), checked by+ * `features/performance/long-message-list.feature`.+ *+ * - `firstReadableMs`: navigation start until the newest message shows its+ * text on screen. Includes the app boot and the message fetch, because that+ * is what the reader waits for. The step first opens the agent's empty chat+ * so app bundles and the server are warm; the topic's messages stay cold.+ * - `maxGapMs` / `longFrameShare`: the worst stall, and the share of frame+ * gaps above 50 ms, while the reader wheels through the whole topic.+ * - `maxMountedRows`: message rows in the DOM at once. Virtualization keeps+ * this flat regardless of topic length; losing it mounts every row.+ * - `rowMountsPerMessage`: row mounts during one full pass divided by the+ * messages in the topic. A pass mounts each row about once (a tool round of+ * three messages is one row, so a clean pass stays below 1); remount churn+ * from unstable keys or index shifts multiplies it.+ *+ * Counts never moved across local runs (2026-11-13, 3 runs each: mounted rows+ * 8 / 7, mounts per message 0.93-0.94 up and 0.79-0.80 down), so they get tight+ * ceilings shared by every machine. Timings swing between the same runs (first+ * readable 1.5-1.8 s after the warm-up, worst gap 50-200 ms, long-frame share+ * 0-2.2%), so their ceilings only catch a list that got far slower than any+ * baseline.+ *+ * This is a local tool (`bun run test:perf:local`), not a CI gate: the+ * scenario is tagged `@perf-local`, which neither the functional suite nor the+ * CI `Render Budget` job runs, so it costs no GitHub Actions time.+ */+export interface LongListTimingBudget {+ firstReadableMs: number;+ scroll: { longFrameShare: number; maxGapMs: number };+}++export interface LongListCountBudget {+ maxMountedRows: number;+ rowMountsPerMessage: number;+}++export type LongListSize = 500 | 1000;++/** The same for both sizes: what is mounted must not grow with topic length. */+const countBudget: LongListCountBudget = { maxMountedRows: 12, rowMountsPerMessage: 1.2 };++const timingBudget: Record<LongListSize, LongListTimingBudget> = {+ 500: { firstReadableMs: 3500, scroll: { longFrameShare: 0.05, maxGapMs: 400 } },+ 1000: { firstReadableMs: 3500, scroll: { longFrameShare: 0.05, maxGapMs: 400 } },+};++export const getLongListBudget = (size: LongListSize) => ({+ counts: countBudget,+ timing: timingBudget[size],+});diff --git a/e2e/src/performance/frameStats.test.ts b/e2e/src/performance/frameStats.test.tsnew file mode 100644index 00000000000..ac64876c3ae--- /dev/null+++ b/e2e/src/performance/frameStats.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';++import { summarizeFrames } from './frameStats';++describe('summarizeFrames', () => {+ it('reports steady 60 Hz frames without long frames', () => {+ const timestamps = Array.from({ length: 61 }, (_, i) => i * 16.7);++ expect(summarizeFrames(timestamps)).toEqual({+ frames: 61,+ longFrames: 0,+ maxGapMs: 16.7,+ p95GapMs: 16.7,+ });+ });++ it('counts each stall above 50 ms and keeps the worst one as the max gap', () => {+ const timestamps = [0, 16, 32, 132, 148, 164, 244];++ const stats = summarizeFrames(timestamps);++ expect(stats.longFrames).toBe(2);+ expect(stats.maxGapMs).toBe(100);+ });++ it('uses the nearest-rank 95th percentile so one stall in 20 gaps sets it', () => {+ const gaps = [...Array.from({ length: 19 }, () => 10), 90];+ const timestamps = gaps.reduce<number[]>((acc, gap) => [...acc, acc.at(-1)! + gap], [0]);++ expect(summarizeFrames(timestamps).p95GapMs).toBe(10);+ expect(summarizeFrames([...timestamps, timestamps.at(-1)! + 90]).p95GapMs).toBe(90);+ });++ it('returns zeros when fewer than two frames were sampled', () => {+ expect(summarizeFrames([5])).toEqual({ frames: 1, longFrames: 0, maxGapMs: 0, p95GapMs: 0 });+ });+});diff --git a/e2e/src/performance/frameStats.ts b/e2e/src/performance/frameStats.tsnew file mode 100644index 00000000000..19cec95215f--- /dev/null+++ b/e2e/src/performance/frameStats.ts@@ -0,0 +1,33 @@+/** A frame gap above this is a visible stall (three missed 60 Hz frames). */+export const LONG_FRAME_MS = 50;++export interface FrameStats {+ /** Frames sampled during the window. */+ frames: number;+ /** Frame gaps above {@link LONG_FRAME_MS}. */+ longFrames: number;+ /** Largest gap between two consecutive animation frames. */+ maxGapMs: number;+ /** 95th percentile gap between consecutive animation frames. */+ p95GapMs: number;+}++const round = (value: number) => Math.round(value * 10) / 10;++/** Summarize `requestAnimationFrame` timestamps collected in the page. */+export const summarizeFrames = (timestamps: number[]): FrameStats => {+ const gaps = timestamps.slice(1).map((value, i) => value - timestamps[i]);+ if (gaps.length === 0)+ return { frames: timestamps.length, longFrames: 0, maxGapMs: 0, p95GapMs: 0 };++ const sorted = [...gaps].sort((a, b) => a - b);+ // Nearest-rank percentile: the smallest gap at or above 95% of the samples.+ const p95 = sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * 0.95) - 1)];++ return {+ frames: timestamps.length,+ longFrames: gaps.filter((gap) => gap > LONG_FRAME_MS).length,+ maxGapMs: round(sorted.at(-1)!),+ p95GapMs: round(p95),+ };+};diff --git a/e2e/src/performance/longConversation.test.ts b/e2e/src/performance/longConversation.test.tsnew file mode 100644index 00000000000..2c9d2680fd5--- /dev/null+++ b/e2e/src/performance/longConversation.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest';++import { buildLongConversationRows, LAST_MESSAGE_MARKER } from './longConversation';++const ids = { agentId: 'agt_perf', topicId: 'tpc_perf', userId: 'user_perf' };++describe('buildLongConversationRows', () => {+ it('builds exactly the requested number of rows as one linear parent chain', () => {+ const { messages } = buildLongConversationRows(ids, 500);++ expect(messages).toHaveLength(500);+ expect(messages[0].parentId).toBeNull();+ for (let i = 1; i < messages.length; i++) {+ expect(messages[i].parentId).toBe(messages[i - 1].id);+ expect(messages[i].createdAt.getTime()).toBeGreaterThan(messages[i - 1].createdAt.getTime());+ }+ });++ it('pairs every tool call with a tool row and its plugin record', () => {+ const { messages, plugins } = buildLongConversationRows(ids, 1000);++ const toolCalls = messages.flatMap((row) => row.tools ?? []);+ const toolRows = messages.filter((row) => row.role === 'tool');++ expect(toolCalls).toHaveLength(100);+ expect(toolRows).toHaveLength(100);+ expect(plugins.map((plugin) => plugin.id)).toEqual(toolRows.map((row) => row.id));+ expect(plugins.map((plugin) => plugin.toolCallId)).toEqual(toolCalls.map((call) => call.id));+ for (const row of toolRows) {+ const parent = messages.find((message) => message.id === row.parentId);+ expect(parent?.tools?.length).toBe(1);+ }+ });++ it('ends on a plain assistant row that alone carries the newest-message marker', () => {+ const { lastMessageId, messages } = buildLongConversationRows(ids, 500);++ const last = messages.at(-1)!;+ expect(last.id).toBe(lastMessageId);+ expect(last.role).toBe('assistant');+ expect(last.tools).toBeNull();+ expect(messages.filter((row) => row.content.includes(LAST_MESSAGE_MARKER))).toEqual([last]);+ });++ it('includes code blocks and images in every cycle', () => {+ const { messages } = buildLongConversationRows(ids, 500);++ expect(messages.filter((row) => row.content.includes('```ts'))).toHaveLength(50);+ expect(messages.filter((row) => row.content.includes('![Dashboard screenshot]'))).toHaveLength(+ 50,+ );+ });++ it('rejects counts that would cut a cycle in half', () => {+ expect(() => buildLongConversationRows(ids, 505)).toThrow(/multiple of 10/);+ expect(() => buildLongConversationRows(ids, 0)).toThrow(/multiple of 10/);+ });+});diff --git a/e2e/src/performance/longConversation.ts b/e2e/src/performance/longConversation.tsnew file mode 100644index 00000000000..f8daa9de751--- /dev/null+++ b/e2e/src/performance/longConversation.ts@@ -0,0 +1,323 @@+/**+ * Long-conversation fixture for the message list render budget (`@perf`).+ *+ * The topic is written straight into PostgreSQL instead of being produced+ * through the UI: sending 1000 messages through the chat input would take+ * minutes and measure the send path, not the list.+ */++/** Messages per repeating cycle; message counts must be a multiple of it. */+export const CYCLE_MESSAGE_COUNT = 10;++/** Text in the newest message; the first-readable probe waits for it on screen. */+export const LAST_MESSAGE_MARKER = 'E2E-LONG-LIST-NEWEST-MESSAGE';++/** Static asset served by the app itself, so image rows never hit the network. */+export const IMAGE_FIXTURE_PATH = '/screenshots/shot-1.desktop.png';++export interface LongConversationIds {+ agentId: string;+ topicId: string;+ userId: string;+}++export interface SeedMessageRow {+ agentId: string;+ content: string;+ createdAt: Date;+ id: string;+ parentId: string | null;+ role: 'assistant' | 'tool' | 'user';+ tools: SeedToolCall[] | null;+ topicId: string;+ userId: string;+}++export interface SeedToolCall {+ apiName: string;+ arguments: string;+ id: string;+ identifier: string;+ type: 'builtin';+}++export interface SeedPluginRow {+ apiName: string;+ arguments: string;+ id: string;+ identifier: string;+ toolCallId: string;+ type: 'builtin';+ userId: string;+}++export interface LongConversationRows {+ lastMessageId: string;+ messages: SeedMessageRow[];+ plugins: SeedPluginRow[];+}++const CODE_BLOCK = [+ '```ts',+ 'interface Invoice {',+ ' amount: number;',+ ' currency: string;',+ ' dueAt: Date;',+ '}',+ '',+ 'export const totalByCurrency = (invoices: Invoice[]) => {',+ ' const totals = new Map<string, number>();',+ ' for (const invoice of invoices) {',+ ' totals.set(invoice.currency, (totals.get(invoice.currency) ?? 0) + invoice.amount);',+ ' }',+ ' return Object.fromEntries(totals);',+ '};',+ '```',+].join('\n');++const PARAGRAPH =+ 'Virtualized lists only mount the rows near the viewport, so the cost of a long ' ++ 'conversation should stay close to the cost of a short one. This paragraph is long ' ++ 'enough to wrap across several lines at the default reading width and give each row ' ++ 'a realistic height.';++/**+ * Build a linear conversation of `messageCount` rows that repeats one cycle of+ * the row shapes a real long topic contains:+ *+ * | round | rows | rendered as |+ * | ----- | ------------------------------------------- | ----------------------- |+ * | tool | user → assistant(tool call) → tool → answer | tool card + markdown |+ * | image | user → assistant with an image and a table | image + table |+ * | code | user → assistant with a code block | highlighted code block |+ * | text | user → assistant with plain paragraphs | plain markdown |+ *+ * The cycle ends on a plain-text assistant row so the newest message renders+ * as its own `[data-message-id]` row (tool rounds collapse into one group row).+ */+export const buildLongConversationRows = (+ ids: LongConversationIds,+ messageCount: number,+ startAt: Date = new Date(Date.UTC(2026, 0, 1)),+): LongConversationRows => {+ if (messageCount <= 0 || messageCount % CYCLE_MESSAGE_COUNT !== 0) {+ throw new Error(`messageCount must be a positive multiple of ${CYCLE_MESSAGE_COUNT}`);+ }++ const messages: SeedMessageRow[] = [];+ const plugins: SeedPluginRow[] = [];+ const base = { agentId: ids.agentId, topicId: ids.topicId, userId: ids.userId };++ const push = (+ role: SeedMessageRow['role'],+ content: string,+ tools: SeedToolCall[] | null = null,+ ): SeedMessageRow => {+ const index = messages.length;+ const row: SeedMessageRow = {+ ...base,+ content,+ // One second apart keeps ordering stable for every created_at sort.+ createdAt: new Date(startAt.getTime() + index * 1000),+ id: `${ids.topicId}_msg_${String(index).padStart(5, '0')}`,+ parentId: messages.at(-1)?.id ?? null,+ role,+ tools,+ };+ messages.push(row);+ return row;+ };++ for (let cycle = 0; cycle < messageCount / CYCLE_MESSAGE_COUNT; cycle++) {+ const isLastCycle = cycle === messageCount / CYCLE_MESSAGE_COUNT - 1;++ // Tool round: 4 rows.+ push('user', `Round ${cycle}: list the files in the workspace.`);+ const toolCallId = `call_${ids.topicId}_${cycle}`;+ const toolCall: SeedToolCall = {+ apiName: 'runCommand',+ arguments: JSON.stringify({ command: 'ls -la src', description: 'List source files' }),+ id: toolCallId,+ identifier: 'lobe-cloud-sandbox',+ type: 'builtin',+ };+ push('assistant', '', [toolCall]);+ const toolRow = push(+ 'tool',+ [+ 'total 24',+ 'drwxr-xr-x 5 user staff 160 index.ts',+ '-rw-r--r-- 1 user staff 812 a.ts',+ ].join('\n'),+ );+ plugins.push({+ apiName: toolCall.apiName,+ arguments: toolCall.arguments,+ id: toolRow.id,+ identifier: toolCall.identifier,+ toolCallId,+ type: 'builtin',+ userId: ids.userId,+ });+ push(+ 'assistant',+ `The workspace has **3** entries in round ${cycle}:\n\n- index.ts\n- a.ts\n- b.ts`,+ );++ // Image round: 2 rows.+ push('user', `Round ${cycle}: show me the dashboard screenshot.`);+ push(+ 'assistant',+ [+ `Here is the dashboard for round ${cycle}:`,+ '',+ ``,+ '',+ '| Metric | Value |',+ '| ------ | ----- |',+ '| Users | 1,024 |',+ '| Errors | 3 |',+ ].join('\n'),+ );++ // Code round: 2 rows.+ push('user', `Round ${cycle}: write a helper that sums invoices by currency.`);+ push('assistant', `Here is a helper:\n\n${CODE_BLOCK}`);++ // Plain text round: 2 rows.+ push('user', `Round ${cycle}: ${PARAGRAPH}`);+ push(+ 'assistant',+ `${PARAGRAPH}\n\n${PARAGRAPH}${isLastCycle ? `\n\n${LAST_MESSAGE_MARKER}` : ''}`,+ );+ }++ return { lastMessageId: messages.at(-1)!.id, messages, plugins };+};++/** Rows per multi-row INSERT; 10 columns × 200 rows stays well under the 65535 bind limit. */+const INSERT_BATCH_SIZE = 200;++interface QueryableClient {+ query: (text: string, values?: unknown[]) => Promise<unknown>;+}++const insertBatched = async <T>(+ client: QueryableClient,+ rows: T[],+ table: string,+ columns: string[],+ toValues: (row: T) => unknown[],+) => {+ for (let offset = 0; offset < rows.length; offset += INSERT_BATCH_SIZE) {+ const batch = rows.slice(offset, offset + INSERT_BATCH_SIZE);+ const values: unknown[] = [];+ const tuples = batch.map((row) => {+ const rowValues = toValues(row);+ const placeholders = rowValues.map((value) => {+ values.push(value);+ return `$${values.length}`;+ });+ return `(${placeholders.join(', ')})`;+ });+ // Batches are sequential on purpose: one pg client cannot pipeline queries.+ await client.query(+ `INSERT INTO ${table} (${columns.join(', ')}) VALUES ${tuples.join(', ')}`,+ values,+ );+ }+};++/**+ * Replace the long topic of `ids` with a fresh copy of `messageCount` rows.+ * Re-seeding per scenario keeps the topic identical across runs and workers.+ */+export const seedLongConversation = async (+ ids: LongConversationIds,+ messageCount: number,+): Promise<LongConversationRows> => {+ const databaseUrl = process.env.DATABASE_URL;+ if (!databaseUrl) throw new Error('DATABASE_URL is required to seed the long conversation');++ const rows = buildLongConversationRows(ids, messageCount);+ const { default: pg } = await import('pg');+ const client = new pg.Client({ connectionString: databaseUrl });++ try {+ await client.connect();+ await client.query('BEGIN');++ await client.query(+ `INSERT INTO agents (id, slug, title, user_id, model, provider)+ VALUES ($1, $2, 'Long List Budget', $3, 'gpt-4o-mini', 'openai')+ ON CONFLICT (id) DO NOTHING`,+ [ids.agentId, ids.agentId, ids.userId],+ );+ // Cascades to messages and message_plugins.+ await client.query('DELETE FROM topics WHERE id = $1', [ids.topicId]);+ await client.query(+ `INSERT INTO topics (id, title, user_id, agent_id, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5, $5)`,+ [+ ids.topicId,+ `Long list ${messageCount}`,+ ids.userId,+ ids.agentId,+ rows.messages.at(-1)!.createdAt,+ ],+ );++ await insertBatched(+ client,+ rows.messages,+ 'messages',+ [+ 'id',+ 'role',+ 'content',+ 'tools',+ 'user_id',+ 'topic_id',+ 'agent_id',+ 'parent_id',+ 'created_at',+ 'updated_at',+ ],+ (row) => [+ row.id,+ row.role,+ row.content,+ row.tools ? JSON.stringify(row.tools) : null,+ row.userId,+ row.topicId,+ row.agentId,+ row.parentId,+ row.createdAt,+ row.createdAt,+ ],+ );+ await insertBatched(+ client,+ rows.plugins,+ 'message_plugins',+ ['id', 'tool_call_id', 'type', 'api_name', 'arguments', 'identifier', 'user_id'],+ (row) => [+ row.id,+ row.toolCallId,+ row.type,+ row.apiName,+ row.arguments,+ row.identifier,+ row.userId,+ ],+ );++ await client.query('COMMIT');+ return rows;+ } catch (error) {+ await client.query('ROLLBACK').catch(() => {});+ throw error;+ } finally {+ await client.end();+ }+};diff --git a/e2e/src/performance/pageProbes.ts b/e2e/src/performance/pageProbes.tsnew file mode 100644index 00000000000..27a1bb45fb2--- /dev/null+++ b/e2e/src/performance/pageProbes.ts@@ -0,0 +1,133 @@+import type { Page } from '@playwright/test';++/**+ * In-page probes for the message list render budget.+ *+ * Every script is injected as source text: the tsx/esbuild transform wraps+ * named inner functions in a `__name` helper that does not exist in the page+ * (see `probes/scrollTrace.ts`).+ */++const FIRST_READABLE_KEY = '__lobehubE2EFirstReadable';+const WINDOW_KEY = '__lobehubE2ERenderWindow';++/** The virtua scroller of the conversation (`VLIST_CLASS_NAME`). */+export const SCROLLER_SELECTOR = '.conversation-vlist';+/** Root element of every rendered message row (`ChatItem`). */+const ROW_SELECTOR = '.message-wrapper';++/**+ * Register before navigation. Records `performance.now()` — milliseconds since+ * the navigation started — at the first animation frame in which the newest+ * message shows its marker text inside the viewport.+ */+export const installFirstReadableProbe = async (+ page: Page,+ target: { marker: string; messageId: string },+): Promise<void> => {+ await page.addInitScript(`(() => {+ const key = ${JSON.stringify(FIRST_READABLE_KEY)};+ const selector = ${JSON.stringify(`[data-message-id="${target.messageId}"]`)};+ const marker = ${JSON.stringify(target.marker)};+ const state = { at: null };+ window[key] = state;+ const check = () => {+ const el = document.querySelector(selector);+ if (el && el.textContent && el.textContent.includes(marker)) {+ const rect = el.getBoundingClientRect();+ if (rect.height > 0 && rect.bottom > 0 && rect.top < window.innerHeight) {+ state.at = performance.now();+ return;+ }+ }+ requestAnimationFrame(check);+ };+ requestAnimationFrame(check);+ })()`);+};++export const readFirstReadableMs = (page: Page): Promise<number | null> =>+ page.evaluate<number | null>(`window[${JSON.stringify(FIRST_READABLE_KEY)}]?.at ?? null`);++export interface RenderWindowSample {+ /** Largest number of message rows mounted at once during the window. */+ maxMountedRows: number;+ /** Message rows added to the DOM during the window (virtual list mounts). */+ rowMounts: number;+ /** `requestAnimationFrame` timestamps sampled during the window. */+ timestamps: number[];+}++/** Start sampling animation frames and message-row mounts. */+export const startRenderWindow = (page: Page): Promise<void> =>+ page.evaluate(`(() => {+ const key = ${JSON.stringify(WINDOW_KEY)};+ const rowSelector = ${JSON.stringify(ROW_SELECTOR)};+ const previous = window[key];+ if (previous) {+ cancelAnimationFrame(previous.raf);+ previous.observer.disconnect();+ }+ const state = { maxMountedRows: 0, raf: 0, rowMounts: 0, timestamps: [] };+ state.observer = new MutationObserver((records) => {+ for (const record of records) {+ for (const node of record.addedNodes) {+ if (!(node instanceof Element)) continue;+ if (node.matches(rowSelector)) state.rowMounts += 1;+ state.rowMounts += node.querySelectorAll(rowSelector).length;+ }+ }+ });+ state.observer.observe(document.body, { childList: true, subtree: true });+ const tick = (timestamp) => {+ state.timestamps.push(timestamp);+ const mounted = document.querySelectorAll(rowSelector).length;+ if (mounted > state.maxMountedRows) state.maxMountedRows = mounted;+ state.raf = requestAnimationFrame(tick);+ };+ state.raf = requestAnimationFrame(tick);+ window[key] = state;+ })()`);++export const stopRenderWindow = (page: Page): Promise<RenderWindowSample> =>+ page.evaluate<RenderWindowSample>(`(() => {+ const key = ${JSON.stringify(WINDOW_KEY)};+ const state = window[key];+ if (!state) return { maxMountedRows: 0, rowMounts: 0, timestamps: [] };+ cancelAnimationFrame(state.raf);+ state.observer.disconnect();+ delete window[key];+ return {+ maxMountedRows: state.maxMountedRows,+ rowMounts: state.rowMounts,+ timestamps: state.timestamps,+ };+ })()`);++export interface ScrollerState {+ clientHeight: number;+ /** Message ids currently mounted, in DOM order. */+ mountedIds: string[];+ scrollHeight: number;+ scrollTop: number;+}++export const readScrollerState = (page: Page): Promise<ScrollerState | null> =>+ page.evaluate<ScrollerState | null>(`(() => {+ const scroller = document.querySelector(${JSON.stringify(SCROLLER_SELECTOR)});+ if (!scroller) return null;+ return {+ clientHeight: scroller.clientHeight,+ mountedIds: [...scroller.querySelectorAll('[data-message-id]')].map((el) =>+ el.getAttribute('data-message-id'),+ ),+ scrollHeight: scroller.scrollHeight,+ scrollTop: scroller.scrollTop,+ };+ })()`);++/** Resolve after the next two animation frames, so layout and paint have run. */+export const nextFrames = (page: Page): Promise<void> =>+ page.evaluate(+ `new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())))`,+ );diff --git a/e2e/src/steps/performance/long-message-list.steps.ts b/e2e/src/steps/performance/long-message-list.steps.tsnew file mode 100644index 00000000000..3fa335b1b8e--- /dev/null+++ b/e2e/src/steps/performance/long-message-list.steps.ts@@ -0,0 +1,270 @@+/**+ * Long message list render budget (T-13850).+ *+ * Seeds a topic of 500 / 1000 messages, opens it, then wheels to the oldest+ * message and back while sampling animation frames and row mounts in the page.+ * Every measurement is written to `reports/perf/`, so a run leaves a receipt+ * even when the budget passes. Run it locally with `bun run test:perf:local`.+ */+import * as fs from 'node:fs';+import path from 'node:path';++import { Given, Then, When } from '@cucumber/cucumber';++import { getLongListBudget, type LongListSize } from '../../performance/budgets';+import { type FrameStats, summarizeFrames } from '../../performance/frameStats';+import {+ LAST_MESSAGE_MARKER,+ type LongConversationIds,+ seedLongConversation,+} from '../../performance/longConversation';+import {+ installFirstReadableProbe,+ nextFrames,+ readFirstReadableMs,+ readScrollerState,+ type RenderWindowSample,+ SCROLLER_SELECTOR,+ startRenderWindow,+ stopRenderWindow,+} from '../../performance/pageProbes';+import { TEST_USER } from '../../support/seedTestUser';+import type { CustomWorld } from '../../support/world';++const SCROLL_STEP_TIMEOUT = 180_000;+/** One wheel notch of a fast flick; small enough that every row passes the viewport. */+const WHEEL_DELTA_PX = 800;+/** Consecutive settled reads before an edge counts as reached (paging can still shift it). */+const SETTLED_READS = 5;+const EDGE_TOLERANCE_PX = 2;++interface ScrollPassReceipt extends FrameStats {+ direction: 'toBottom' | 'toTop';+ durationMs: number;+ /** Long frames over all sampled frame gaps. */+ longFrameShare: number;+ maxMountedRows: number;+ rowMounts: number;+ rowMountsPerMessage: number;+ wheelSteps: number;+}++interface LongListReceipt {+ firstMessageId: string;+ firstReadableMs: number | null;+ lastMessageId: string;+ passes: ScrollPassReceipt[];+ size: LongListSize;+ violations: string[];+}++const receiptOf = (world: CustomWorld): LongListReceipt => {+ const receipt = world.testContext.longListReceipt as LongListReceipt | undefined;+ if (!receipt) throw new Error('Long conversation was not seeded in this scenario');+ return receipt;+};++const writeReceipt = (receipt: LongListReceipt) => {+ const dir = path.join(process.cwd(), 'reports', 'perf');+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(+ path.join(dir, `long-message-list-${receipt.size}.json`),+ `${JSON.stringify(receipt, null, 2)}\n`,+ );+};++/** Record and report the violations of one check; the scenario fails on any. */+const enforce = (receipt: LongListReceipt, checks: Array<[ok: boolean, message: string]>) => {+ const violations = checks.filter(([ok]) => !ok).map(([, message]) => message);+ receipt.violations.push(...violations);+ writeReceipt(receipt);+ if (violations.length > 0) {+ throw new Error(+ `Long list (${receipt.size} messages) over budget:\n- ${violations.join('\n- ')}`,+ );+ }+};++Given(+ '用户有一个包含 {int} 条消息的长对话',+ { timeout: 60_000 },+ async function (this: CustomWorld, count: number) {+ const size = count as LongListSize;+ const ids: LongConversationIds = {+ // TEST_USER.id already carries the run and worker scope.+ agentId: `agt_longlist_${TEST_USER.id}`,+ topicId: `tpc_longlist_${size}_${TEST_USER.id}`,+ userId: TEST_USER.id,+ };+ const rows = await seedLongConversation(ids, size);++ this.testContext.longListIds = ids;+ this.testContext.longListReceipt = {+ firstMessageId: rows.messages[0].id,+ firstReadableMs: null,+ lastMessageId: rows.lastMessageId,+ passes: [],+ size,+ violations: [],+ } satisfies LongListReceipt;+ // Replace an earlier run's receipt now, so a scenario that dies early cannot leave it behind.+ writeReceipt(this.testContext.longListReceipt);+ console.log(` 📍 Seeded ${size} messages into ${ids.topicId}`);+ },+);++When('用户打开这个长对话', { timeout: 60_000 }, async function (this: CustomWorld) {+ const ids = this.testContext.longListIds as LongConversationIds;+ const receipt = receiptOf(this);++ // Warm the app bundles and server on the agent's empty chat first. Without it+ // the first scenario of each run paid 1-2 s of cold-start noise (2.8-6.5 s+ // vs 1.8-4.7 s for the second). The topic's messages stay uncached.+ await this.page.goto(`/agent/${ids.agentId}`, { waitUntil: 'domcontentloaded' });+ await this.page.locator('[data-testid="chat-input"]').first().waitFor({ timeout: 45_000 });++ await installFirstReadableProbe(this.page, {+ marker: LAST_MESSAGE_MARKER,+ messageId: receipt.lastMessageId,+ });+ await this.page.goto(`/agent/${ids.agentId}/${ids.topicId}`, { waitUntil: 'domcontentloaded' });++ // Wait without a budget here; the Then step judges the recorded time.+ try {+ await this.page.waitForFunction(+ `window.__lobehubE2EFirstReadable && window.__lobehubE2EFirstReadable.at !== null`,+ undefined,+ { timeout: 45_000 },+ );+ } catch {+ enforce(receipt, [[false, 'newest message never became readable within 45 s']]);+ }+ receipt.firstReadableMs = Math.round((await readFirstReadableMs(this.page))!);+ console.log(` 📍 Newest message readable after ${receipt.firstReadableMs} ms`);+});++Then('最新消息应在首屏可读预算内出现', async function (this: CustomWorld) {+ const receipt = receiptOf(this);+ const budget = getLongListBudget(receipt.size).timing.firstReadableMs;++ enforce(receipt, [+ [+ receipt.firstReadableMs !== null && receipt.firstReadableMs <= budget,+ `first readable ${receipt.firstReadableMs} ms > ${budget} ms`,+ ],+ ]);+});++const toPass = (+ receipt: LongListReceipt,+ direction: ScrollPassReceipt['direction'],+ sample: RenderWindowSample,+ startedAt: number,+ wheelSteps: number,+): ScrollPassReceipt => {+ const frames = summarizeFrames(sample.timestamps);+ return {+ ...frames,+ direction,+ durationMs: Date.now() - startedAt,+ longFrameShare:+ frames.frames > 1 ? Math.round((frames.longFrames / (frames.frames - 1)) * 1000) / 1000 : 0,+ maxMountedRows: sample.maxMountedRows,+ rowMounts: sample.rowMounts,+ rowMountsPerMessage: Math.round((sample.rowMounts / receipt.size) * 100) / 100,+ wheelSteps,+ };+};++const scrollToEdge = async (world: CustomWorld, direction: ScrollPassReceipt['direction']) => {+ const receipt = receiptOf(world);+ const edgeMessageId = direction === 'toTop' ? receipt.firstMessageId : receipt.lastMessageId;+ const scroller = world.page.locator(SCROLLER_SELECTOR).first();+ const box = await scroller.boundingBox();+ if (!box) throw new Error('Conversation scroller is not visible');++ // Upper part of the list: the chat input floats over its bottom edge.+ await world.page.mouse.move(box.x + box.width / 2, box.y + box.height * 0.4);+ await nextFrames(world.page);++ await startRenderWindow(world.page);+ const startedAt = Date.now();+ let wheelSteps = 0;+ let settled = 0;++ while (settled < SETTLED_READS) {+ if (Date.now() - startedAt > SCROLL_STEP_TIMEOUT - 20_000) {+ // Keep what was sampled so the receipt shows where the pass stalled.+ receipt.passes.push(+ toPass(receipt, direction, await stopRenderWindow(world.page), startedAt, wheelSteps),+ );+ enforce(receipt, [[false, `scroll ${direction} did not reach ${edgeMessageId} in time`]]);+ }++ // Wheel steps are sequential: each one depends on the position the last one left.+ await world.page.mouse.wheel(0, direction === 'toTop' ? -WHEEL_DELTA_PX : WHEEL_DELTA_PX);+ wheelSteps += 1;+ await nextFrames(world.page);+ const state = await readScrollerState(world.page);+ const atEdge =+ !!state &&+ state.mountedIds.includes(edgeMessageId) &&+ (direction === 'toTop'+ ? state.scrollTop <= EDGE_TOLERANCE_PX+ : state.scrollHeight - state.scrollTop - state.clientHeight <= EDGE_TOLERANCE_PX);+ settled = atEdge ? settled + 1 : 0;+ }++ const pass = toPass(+ receipt,+ direction,+ await stopRenderWindow(world.page),+ startedAt,+ wheelSteps,+ );+ receipt.passes.push(pass);+ console.log(` 📍 Scroll ${direction}: ${JSON.stringify(pass)}`);+};++When(+ '用户用滚轮从底部滚到对话最早的消息',+ { timeout: SCROLL_STEP_TIMEOUT },+ async function (this: CustomWorld) {+ await scrollToEdge(this, 'toTop');+ },+);++When(+ '用户用滚轮从顶部滚回对话最新的消息',+ { timeout: SCROLL_STEP_TIMEOUT },+ async function (this: CustomWorld) {+ await scrollToEdge(this, 'toBottom');+ },+);++Then('这次滚动的帧间隔和消息行挂载数应在预算内', async function (this: CustomWorld) {+ const receipt = receiptOf(this);+ const pass = receipt.passes.at(-1);+ if (!pass) throw new Error('No scroll pass was recorded');+ const { counts, timing } = getLongListBudget(receipt.size);+ const label = `scroll ${pass.direction}`;++ enforce(receipt, [+ [+ pass.maxGapMs <= timing.scroll.maxGapMs,+ `${label} max frame gap ${pass.maxGapMs} ms > ${timing.scroll.maxGapMs} ms`,+ ],+ [+ pass.longFrameShare <= timing.scroll.longFrameShare,+ `${label} long-frame share ${pass.longFrameShare} > ${timing.scroll.longFrameShare} (${pass.longFrames}/${pass.frames} frames)`,+ ],+ [+ pass.maxMountedRows <= counts.maxMountedRows,+ `${label} mounted rows ${pass.maxMountedRows} > ${counts.maxMountedRows}`,+ ],+ [+ pass.rowMountsPerMessage <= counts.rowMountsPerMessage,+ `${label} row mounts per message ${pass.rowMountsPerMessage} > ${counts.rowMountsPerMessage}`,+ ],+ ]);+});