Skip to content

🤯 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.

✨ feat(perf): add render profiling build and chat render budgets (#22936)

YuTengjing8c43f9f07275
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 2f3a45d1654..31018487805 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -265,3 +265,85 @@ jobs:
e2e/reports
e2e/screenshots
if-no-files-found: ignore
+
+ render-budget:
+ name: Render Budget
+ runs-on: ubuntu-latest
+ services:
+ postgres:
+ image: paradedb/paradedb:latest
+ env:
+ POSTGRES_PASSWORD: postgres
+ options: >-
+ --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
+
+ ports:
+ - 5432:5432
+
+ timeout-minutes: 30
+ steps:
+ - name: Checkout
+ env:
+ REF_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
+ REPOSITORY: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || github.repository }}
+ run: |
+ git init .
+ git remote add origin "https://github.com/${REPOSITORY}.git"
+ git fetch --no-tags --depth=1 origin "${REF_SHA}"
+ git checkout --force FETCH_HEAD
+
+ - name: Setup environment
+ uses: ./.github/actions/setup-env
+
+ - name: Install dependencies
+ run: pnpm install
+
+ - name: Generate OIDC test signing key
+ run: |
+ JWKS_KEY="$(bun -e "import { createTestOidcJwks } from './e2e/src/support/oidcTestKey'; process.stdout.write(createTestOidcJwks());")"
+ printf 'JWKS_KEY=%s\n' "$JWKS_KEY" >> "$GITHUB_ENV"
+
+ - name: Install Playwright browsers (with system deps)
+ run: bunx playwright install --with-deps chromium
+
+ - name: Run database migrations
+ run: bun run db:migrate
+
+ # React's profiling build makes <Profiler> report in a production bundle;
+ # the regular E2E job keeps the shipped bundle so its size gates stay exact.
+ - name: Build application (React profiling)
+ run: bun run build
+ env:
+ LOBE_REACT_PROFILING: '1'
+ SKIP_LINT: '1'
+
+ - name: Start E2E server
+ run: |
+ bunx next start -p 3006 > /tmp/lobehub-e2e-server.log 2>&1 &
+ for i in {1..60}; do
+ if curl -fsS http://localhost:3006 > /dev/null; then
+ exit 0
+ fi
+ sleep 1
+ done
+ cat /tmp/lobehub-e2e-server.log
+ exit 1
+
+ - name: Run render budget scenarios
+ working-directory: e2e
+ run: bun run test:perf
+ env:
+ BASE_URL: http://localhost:3006
+ E2E_REPORTS: '0'
+ HEADLESS: 'true'
+
+ - name: Upload render budget receipts
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@v6
+ with:
+ name: render-budget
+ path: |
+ e2e/reports/render-budget
+ e2e/screenshots
+ retention-days: 30
+ if-no-files-found: ignore
diff --git a/apps/desktop/vite.renderer.config.ts b/apps/desktop/vite.renderer.config.ts
index 631dc7b5ec7..3319526d38e 100644
--- a/apps/desktop/vite.renderer.config.ts
+++ b/apps/desktop/vite.renderer.config.ts
@@ -13,6 +13,7 @@ import {
createSharedRolldownOutput,
sharedModulePreload,
sharedOptimizeDeps,
+ sharedRendererAlias,
sharedRendererDedupe,
sharedRendererDefine,
sharedRendererPlugins,
@@ -267,6 +268,7 @@ export default defineConfig(async (env) => {
}) as PluginOption[]),
],
resolve: {
+ alias: sharedRendererAlias(),
dedupe: sharedRendererDedupe,
tsconfigPaths: !isCloudDesktop,
},
diff --git a/e2e/CLAUDE.md b/e2e/CLAUDE.md
index e8e69ac8430..0fd6b95b1b4 100644
--- a/e2e/CLAUDE.md
+++ b/e2e/CLAUDE.md
@@ -47,6 +47,21 @@ Related: [LOBE-2417](https://linear.app/lobehub/issue/LOBE-2417/建立核心产
@routes # 核心路由
```
+### 渲染预算(`@perf`)
+
+`@perf` 场景读取 React `<Profiler>` 的渲染次数和耗时,只能跑在 `LOBE_REACT_PROFILING=1` 构建上;普通套件会跳过它们,PR CI 的 `Render Budget` job 单独构建并运行,超预算即失败。
+
+```bash
+# 在项目根目录构建 profiling 版本并启动服务
+LOBE_REACT_PROFILING=1 SKIP_LINT=1 bun run build && bunx next start -p 3006
+
+# 在 e2e 目录运行(串行执行,回执写入 reports/render-budget/<scenario>.json)
+BASE_URL=http://localhost:3006 DATABASE_URL=... bun run test:perf
+```
+
+- 区域:`src/components/RenderProfiler` 包住侧栏(`sidebar`)、会话区(`conversation`,含消息区)和消息区(`messages`);页面通过 `window.__LOBE_RENDER_PROFILE__` 暴露 `begin` / `end` / `status`,profiling 构建在启动时自动开始 `boot` 场景。
+- 预算:`src/performance/chatRenderBudgets.ts`,按 p50 判定,本地与 CI(`CI` 环境变量)分别设置。调整预算时用多次运行的回执实测值,不要凭感觉改。
+
### 执行策略
```bash
diff --git a/e2e/cucumber.config.js b/e2e/cucumber.config.js
index d425386f77a..0fb7048615b 100644
--- a/e2e/cucumber.config.js
+++ b/e2e/cucumber.config.js
@@ -5,6 +5,9 @@ const reportsEnabled = !['0', 'false'].includes(String(process.env.E2E_REPORTS).
const parsedParallel = Number(process.env.E2E_PARALLEL || process.env.CUCUMBER_PARALLEL || 1);
const 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';
export default {
format: reportsEnabled
@@ -13,12 +16,13 @@ export default {
formatOptions: {
snippetInterface: 'async-await',
},
- parallel: canRunInParallel ? Math.max(1, requestedParallel) : 1,
+ // Perf samples run one at a time so parallel workers do not steal CPU from the measurement.
+ parallel: canRunInParallel && !perfRun ? Math.max(1, requestedParallel) : 1,
paths: ['src/features/**/*.feature'],
publishQuiet: true,
require: ['src/steps/**/!(*.test).ts', 'src/support/**/*.ts'],
requireModule: ['tsx/cjs'],
retry: 0,
- tags: 'not @skip',
+ tags: perfRun ? '@perf and not @skip' : 'not @skip and not @perf',
timeout: 30_000,
};
diff --git a/e2e/package.json b/e2e/package.json
index 346f4d2da72..c7f5902a20e 100644
--- a/e2e/package.json
+++ b/e2e/package.json
@@ -10,6 +10,7 @@
"test:community": "cucumber-js --config cucumber.config.js src/features/community/",
"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: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/chat-render-budget.feature b/e2e/src/features/performance/chat-render-budget.feature
new file mode 100644
index 00000000000..45bbe082493
--- /dev/null
+++ b/e2e/src/features/performance/chat-render-budget.feature
@@ -0,0 +1,29 @@
+@perf @render-budget
+Feature: 打开与切换 chat 的渲染预算
+ 作为用户,我希望打开 chat 页面和在话题之间切换时界面不卡顿:
+ 侧栏、会话区、消息区各自的渲染次数和渲染耗时,以及最长帧间隔都不超过预算。
+ 只在 LOBE_REACT_PROFILING=1 构建上运行(E2E_PERF=1),预算在 e2e/src/performance/chatRenderBudgets.ts。
+
+ Background:
+ Given 用户已登录系统
+ And 用户有一个带多个历史话题的 Agent
+
+ @PERF-CHAT-001
+ Scenario: 打开 chat 页面
+ When 用户多次打开该 Agent 的 chat 页面
+ Then "open" 场景的渲染不超过预算
+
+ @PERF-CHAT-002
+ Scenario: 切换到已缓存的话题
+ When 用户在已打开过的话题之间来回切换
+ Then "switchCached" 场景的渲染不超过预算
+
+ @PERF-CHAT-003
+ Scenario: 刷新页面后切换到话题
+ When 用户每次刷新页面后切换到另一个话题
+ Then "switchUncached" 场景的渲染不超过预算
+
+ @PERF-CHAT-004
+ Scenario: 冷启动后切换到话题
+ When 用户每次在全新的浏览器环境中打开 chat 后切换到另一个话题
+ Then "switchCold" 场景的渲染不超过预算
diff --git a/e2e/src/performance/chatFixture.ts b/e2e/src/performance/chatFixture.ts
new file mode 100644
index 00000000000..760390ea56f
--- /dev/null
+++ b/e2e/src/performance/chatFixture.ts
@@ -0,0 +1,128 @@
+import { randomBytes } from 'node:crypto';
+
+import { TEST_USER } from '../support/seedTestUser';
+
+export interface ChatFixture {
+ agentId: string;
+ /** Text of each topic's last message; visible once that topic's transcript has rendered. */
+ markers: string[];
+ topicIds: string[];
+}
+
+/** Enough topics that the uncached and cold rounds each switch to a topic not yet opened. */
+const TOPIC_COUNT = 8;
+/** Turns per topic. Each assistant reply carries markdown, a list and a code block. */
+const TURNS_PER_TOPIC = 12;
+
+const assistantReply = (topic: number, turn: number) => `### Step ${turn + 1} of topic ${topic + 1}
+
+Here is a summary of what changed and why it matters for the rollout:
+
+- The cache now keeps **${turn + 3}** entries per conversation.
+- Older entries are evicted in insertion order.
+- Readers see the newest entry first.
+
+\`\`\`ts
+export const pickEntry = (entries: string[], index: number) =>
+ entries.at(index % entries.length) ?? entries[0];
+\`\`\`
+
+The next step checks that the eviction keeps the newest ${turn + 1} replies visible.`;
+
+const connect = async () => {
+ const databaseUrl = process.env.DATABASE_URL;
+ if (!databaseUrl) throw new Error('DATABASE_URL not set');
+
+ const { default: pg } = await import('pg');
+ const client = new pg.Client({ connectionString: databaseUrl });
+ await client.connect();
+ return client;
+};
+
+/**
+ * Seeds one agent with `TOPIC_COUNT` topics of `TURNS_PER_TOPIC` turns straight
+ * into the database, so every run measures the same transcript sizes without
+ * driving the mocked LLM.
+ */
+export const seedChatFixture = async (): Promise<ChatFixture> => {
+ const client = await connect();
+ const suffix = randomBytes(6).toString('hex');
+ const agentId = `agent_e2e_perf_${suffix}`;
+ const topicIds: string[] = [];
+ const markers: string[] = [];
+ // Topics are listed newest first; stagger timestamps so the order is stable.
+ const base = Date.now() - TOPIC_COUNT * TURNS_PER_TOPIC * 2 * 1000;
+
+ try {
+ await client.query('BEGIN');
+ await client.query(
+ `INSERT INTO agents (id, slug, title, user_id, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, now(), now())`,
+ [agentId, `perf-agent-${suffix}`, 'Render Budget Agent', TEST_USER.id],
+ );
+
+ for (let topic = 0; topic < TOPIC_COUNT; topic += 1) {
+ const topicId = `tpc_e2e_perf_${suffix}_${topic}`;
+ const marker = `Render budget end of topic ${topic + 1} ${suffix}`;
+ const topicAt = new Date(base + topic * TURNS_PER_TOPIC * 2 * 1000);
+
+ await client.query(
+ `INSERT INTO topics (id, title, agent_id, user_id, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $5)`,
+ [topicId, `Render budget topic ${topic + 1}`, agentId, TEST_USER.id, topicAt.toISOString()],
+ );
+
+ let parentId: string | null = null;
+ for (let index = 0; index < TURNS_PER_TOPIC * 2; index += 1) {
+ const turn = Math.floor(index / 2);
+ const isUser = index % 2 === 0;
+ const isLast = index === TURNS_PER_TOPIC * 2 - 1;
+ const messageId = `msg_e2e_perf_${suffix}_${topic}_${index}`;
+ const content = isUser
+ ? `Question ${turn + 1}: how should the cache behave for topic ${topic + 1}?`
+ : `${assistantReply(topic, turn)}${isLast ? `\n\n${marker}` : ''}`;
+ const createdAt = new Date(topicAt.getTime() + index * 1000).toISOString();
+
+ await client.query(
+ `INSERT INTO messages (id, role, content, model, provider, user_id, agent_id, topic_id, parent_id, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10)`,
+ [
+ messageId,
+ isUser ? 'user' : 'assistant',
+ content,
+ isUser ? null : 'gpt-4o-mini',
+ isUser ? null : 'openai',
+ TEST_USER.id,
+ agentId,
+ topicId,
+ parentId,
+ createdAt,
+ ],
+ );
+ parentId = messageId;
+ }
+
+ topicIds.push(topicId);
+ markers.push(marker);
+ }
+
+ await client.query('COMMIT');
+ } catch (error) {
+ await client.query('ROLLBACK');
+ throw error;
+ } finally {
+ await client.end();
+ }
+
+ return { agentId, markers, topicIds };
+};
+
+/** Topics and messages cascade from the agent. */
+export const removeChatFixture = async (fixture: ChatFixture) => {
+ const client = await connect();
+ try {
+ await client.query('DELETE FROM agents WHERE id = $1', [fixture.agentId]);
+ } finally {
+ await client.end();
+ }
+};
diff --git a/e2e/src/performance/chatRenderBudgets.ts b/e2e/src/performance/chatRenderBudgets.ts
new file mode 100644
index 00000000000..b390a7c2929
--- /dev/null
+++ b/e2e/src/performance/chatRenderBudgets.ts
@@ -0,0 +1,103 @@
+import type { ChatRenderScenario, RunnerKind, ScenarioBudget } from './renderBudget';
+import { RENDER_REGIONS, type RenderRegion } from './renderProfile';
+
+/**
+ * Render budgets for opening and switching chats, gated on the p50 of each
+ * scenario's samples (`renders` / `actualDurationMs` per region, ms for the
+ * frame gap).
+ *
+ * Local baseline (2026-11-13, M5 Max, headless Chromium, 3 runs, p50 range; durations
+ * swing up to 2x with machine load):
+ *
+ * | scenario | sidebar | conversation | messages | frame gap |
+ * | -------------- | -------------- | ---------------- | --------------- | ---------- |
+ * | open | 19–21× 28–33ms | 59–69× 106–130ms | 34–35× 45–59ms | 133–150ms |
+ * | switchCached | 7× 5–10ms | 18× 34–57ms | 8× 11–22ms | 33–100ms |
+ * | switchUncached | 9× 8–13ms | 43× 59–93ms | 27× 36–56ms | 33–67ms |
+ * | switchCold | 9× 8–14ms | 43–45× 56–97ms | 26× 32–60ms | 33–83ms |
+ *
+ * Render counts barely move between runs, so their ceilings sit about 20%
+ * above the baseline and catch a new re-render loop. Durations move with
+ * machine load, so they allow about twice the baseline and catch only gross
+ * regressions. Re-measure with `bun run test:perf` (receipts in
+ * `reports/render-budget/`) before changing a number.
+ */
+const LOCAL: Record<ChatRenderScenario, ScenarioBudget> = {
+ open: {
+ maxFrameGapMs: 300,
+ regions: {
+ conversation: { actualDurationMs: 260, renders: 80 },
+ messages: { actualDurationMs: 120, renders: 42 },
+ sidebar: { actualDurationMs: 70, renders: 25 },
+ },
+ },
+ switchCached: {
+ maxFrameGapMs: 200,
+ regions: {
+ conversation: { actualDurationMs: 120, renders: 22 },
+ messages: { actualDurationMs: 50, renders: 10 },
+ sidebar: { actualDurationMs: 30, renders: 9 },
+ },
+ },
+ switchCold: {
+ maxFrameGapMs: 200,
+ regions: {
+ conversation: { actualDurationMs: 200, renders: 54 },
+ messages: { actualDurationMs: 120, renders: 32 },
+ sidebar: { actualDurationMs: 35, renders: 11 },
+ },
+ },
+ switchUncached: {
+ maxFrameGapMs: 170,
+ regions: {
+ conversation: { actualDurationMs: 190, renders: 52 },
+ messages: { actualDurationMs: 120, renders: 33 },
+ sidebar: { actualDurationMs: 30, renders: 11 },
+ },
+ },
+};
+
+/**
+ * GitHub-hosted `ubuntu-latest` runners. Render counts match local, so they
+ * reuse the local ceilings. Durations and frame gaps allow about 2.5 times the
+ * first CI receipt (PR #22936, 1 run, p50):
+ *
+ * | scenario | sidebar | conversation | messages | frame gap |
+ * | -------------- | --------- | ------------ | --------- | --------- |
+ * | open | 21× 67ms | 58× 211ms | 34× 95ms | 217ms |
+ * | switchCached | 7× 10ms | 19× 59ms | 8× 25ms | 83ms |
+ * | switchUncached | 9× 17ms | 46× 103ms | 28× 62ms | 83ms |
+ * | switchCold | 9× 17ms | 43× 111ms | 26× 68ms | 100ms |
+ *
+ * Receipts are uploaded as the `render-budget` artifact of the
+ * `Render Budget` job.
+ */
+const withCiTiming = (
+ scenario: ChatRenderScenario,
+ maxFrameGapMs: number,
+ durations: Record<RenderRegion, number>,
+): ScenarioBudget => ({
+ maxFrameGapMs,
+ regions: Object.fromEntries(
+ RENDER_REGIONS.map((region) => [
+ region,
+ { actualDurationMs: durations[region], renders: LOCAL[scenario].regions[region].renders },
+ ]),
+ ) as ScenarioBudget['regions'],
+});
+
+const CI: Record<ChatRenderScenario, ScenarioBudget> = {
+ open: withCiTiming('open', 550, { conversation: 530, messages: 240, sidebar: 170 }),
+ switchCached: withCiTiming('switchCached', 210, { conversation: 150, messages: 65, sidebar: 30 }),
+ switchCold: withCiTiming('switchCold', 250, { conversation: 280, messages: 170, sidebar: 45 }),
+ switchUncached: withCiTiming('switchUncached', 210, {
+ conversation: 260,
+ messages: 160,
+ sidebar: 45,
+ }),
+};
+
+export const CHAT_RENDER_BUDGETS: Record<RunnerKind, Record<ChatRenderScenario, ScenarioBudget>> = {
+ ci: CI,
+ local: LOCAL,
+};
diff --git a/e2e/src/performance/renderBudget.test.ts b/e2e/src/performance/renderBudget.test.ts
new file mode 100644
index 00000000000..4c6b293fb51
--- /dev/null
+++ b/e2e/src/performance/renderBudget.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ findBudgetViolations,
+ resolveRunnerKind,
+ type ScenarioBudget,
+ summarizeReports,
+} from './renderBudget';
+import type { RenderReport } from './renderProfile';
+
+const report = (renders: number, actualDurationMs: number, maxGapMs: number): RenderReport => {
+ const region = { actualDurationMs, maxActualDurationMs: 0, mounts: 0, renders, updates: renders };
+ return {
+ commitCount: renders,
+ durationMs: 0,
+ frames: { count: 10, maxGapMs },
+ label: 'switch',
+ longestAnimationFrameMs: 0,
+ regions: { conversation: region, messages: region, sidebar: region },
+ };
+};
+
+const budget = (renders: number, actualDurationMs: number, maxFrameGapMs: number) =>
+ ({
+ maxFrameGapMs,
+ regions: {
+ conversation: { actualDurationMs, renders },
+ messages: { actualDurationMs, renders },
+ sidebar: { actualDurationMs, renders },
+ },
+ }) satisfies ScenarioBudget;
+
+describe('summarizeReports', () => {
+ it('takes the nearest-rank median and keeps the worst sample', () => {
+ const summary = summarizeReports([report(3, 10, 20), report(9, 50, 200), report(4, 12, 18)]);
+
+ expect(summary.samples).toBe(3);
+ expect(summary.regions.sidebar.renders).toEqual({ max: 9, p50: 4 });
+ expect(summary.regions.sidebar.actualDurationMs).toEqual({ max: 50, p50: 12 });
+ expect(summary.maxFrameGapMs).toEqual({ max: 200, p50: 20 });
+ });
+
+ it('uses the lower middle sample for an even count', () => {
+ expect(summarizeReports([report(2, 0, 0), report(6, 0, 0)]).regions.messages.renders.p50).toBe(
+ 2,
+ );
+ });
+});
+
+describe('findBudgetViolations', () => {
+ it('passes a summary at the budget', () => {
+ const summary = summarizeReports([report(4, 12, 20)]);
+
+ expect(findBudgetViolations('switchCached', summary, budget(4, 12, 20))).toEqual([]);
+ });
+
+ it('names the scenario, region and metric of each overrun', () => {
+ const summary = summarizeReports([report(5, 12, 21)]);
+ const limits = budget(4, 12, 20);
+ limits.regions.messages.renders = 5;
+ limits.regions.conversation.renders = 5;
+
+ expect(findBudgetViolations('switchCold', summary, limits)).toEqual([
+ 'switchCold › sidebar: 5 renders (p50) > budget 4',
+ 'switchCold › longest frame gap 21ms (p50) > budget 20ms',
+ ]);
+ });
+});
+
+describe('resolveRunnerKind', () => {
+ it('selects CI budgets on CI runners', () => {
+ expect(resolveRunnerKind({ CI: 'true' })).toBe('ci');
+ expect(resolveRunnerKind({})).toBe('local');
+ });
+});
diff --git a/e2e/src/performance/renderBudget.ts b/e2e/src/performance/renderBudget.ts
new file mode 100644
index 00000000000..d5b1a5d9c50
--- /dev/null
+++ b/e2e/src/performance/renderBudget.ts
@@ -0,0 +1,100 @@
+import { RENDER_REGIONS, type RenderRegion, type RenderReport } from './renderProfile';
+
+export const CHAT_RENDER_SCENARIOS = [
+ /** Load the chat page with the browser cache warm (a returning user opening a chat link). */
+ 'open',
+ /** Switch to a topic whose messages are already in memory. */
+ 'switchCached',
+ /** First switch after a reload: memory is empty, the IndexedDB transcript replica is not. */
+ 'switchUncached',
+ /** First switch in a fresh browser profile: no HTTP cache, no IndexedDB, messages come from the server. */
+ 'switchCold',
+] as const;
+
+export type ChatRenderScenario = (typeof CHAT_RENDER_SCENARIOS)[number];
+
+export interface Stat {
+ max: number;
+ p50: number;
+}
+
+export interface ScenarioSummary {
+ maxFrameGapMs: Stat;
+ regions: Record<RenderRegion, { actualDurationMs: Stat; renders: Stat }>;
+ samples: number;
+}
+
+export interface RegionBudget {
+ /** Ceiling for the p50 of summed `actualDuration` across the scenario. */
+ actualDurationMs: number;
+ /** Ceiling for the p50 of commits that rendered inside the region. */
+ renders: number;
+}
+
+export interface ScenarioBudget {
+ /** Ceiling for the p50 of the longest gap between two animation frames. */
+ maxFrameGapMs: number;
+ regions: Record<RenderRegion, RegionBudget>;
+}
+
+export type RunnerKind = 'ci' | 'local';
+
+/** Nearest-rank percentile: always one of the measured samples, never an interpolation. */
+const stat = (values: number[]): Stat => {
+ const sorted = [...values].sort((a, b) => a - b);
+ const rank = Math.max(0, Math.ceil(sorted.length * 0.5) - 1);
+ return { max: sorted.at(-1) ?? 0, p50: sorted[rank] ?? 0 };
+};
+
+export const summarizeReports = (reports: RenderReport[]): ScenarioSummary => ({
+ maxFrameGapMs: stat(reports.map((report) => report.frames.maxGapMs)),
+ regions: Object.fromEntries(
+ RENDER_REGIONS.map((region) => [
+ region,
+ {
+ actualDurationMs: stat(reports.map((report) => report.regions[region].actualDurationMs)),
+ renders: stat(reports.map((report) => report.regions[region].renders)),
+ },
+ ]),
+ ) as ScenarioSummary['regions'],
+ samples: reports.length,
+});
+
+/**
+ * Budgets gate the p50 so one sample slowed by a busy runner does not fail the
+ * PR; the receipt keeps the max for investigation.
+ */
+export const findBudgetViolations = (
+ scenario: ChatRenderScenario,
+ summary: ScenarioSummary,
+ budget: ScenarioBudget,
+): string[] => {
+ const violations: string[] = [];
+
+ for (const region of RENDER_REGIONS) {
+ const actual = summary.regions[region];
+ const limit = budget.regions[region];
+
+ if (actual.renders.p50 > limit.renders) {
+ violations.push(
+ `${scenario} › ${region}: ${actual.renders.p50} renders (p50) > budget ${limit.renders}`,
+ );
+ }
+ if (actual.actualDurationMs.p50 > limit.actualDurationMs) {
+ violations.push(
+ `${scenario} › ${region}: ${actual.actualDurationMs.p50}ms render time (p50) > budget ${limit.actualDurationMs}ms`,
+ );
+ }
+ }
+
+ if (summary.maxFrameGapMs.p50 > budget.maxFrameGapMs) {
+ violations.push(
+ `${scenario} › longest frame gap ${summary.maxFrameGapMs.p50}ms (p50) > budget ${budget.maxFrameGapMs}ms`,
+ );
+ }
+
+ return violations;
+};
+
+export const resolveRunnerKind = (env: NodeJS.ProcessEnv = process.env): RunnerKind =>
+ env.CI ? 'ci' : 'local';
diff --git a/e2e/src/performance/renderProfile.ts b/e2e/src/performance/renderProfile.ts
new file mode 100644
index 00000000000..9f816671e62
--- /dev/null
+++ b/e2e/src/performance/renderProfile.ts
@@ -0,0 +1,93 @@
+import type { Page } from '@playwright/test';
+
+/**
+ * Mirrors `RenderProfileReport` in `src/libs/renderProfile/recorder.ts`. The E2E
+ * package cannot import app source, so the shape is repeated here.
+ */
+export const RENDER_REGIONS = ['sidebar', 'conversation', 'messages'] as const;
+
+export type RenderRegion = (typeof RENDER_REGIONS)[number];
+
+export interface RegionReport {
+ actualDurationMs: number;
+ maxActualDurationMs: number;
+ mounts: number;
+ renders: number;
+ updates: number;
+}
+
+export interface RenderReport {
+ commitCount: number;
+ durationMs: number;
+ frames: { count: number; maxGapMs: number };
+ label: string;
+ longestAnimationFrameMs: number;
+ regions: Record<RenderRegion, RegionReport>;
+}
+
+interface ProfileStatus {
+ active: boolean;
+ buildMode?: string;
+ lastCommitAt?: number;
+ now: number;
+}
+
+/** No React commit for this long means the switch has finished rendering. */
+const QUIET_MS = 500;
+const SETTLE_TIMEOUT_MS = 10_000;
+
+// Injected as source text: the tsx/esbuild transform wraps named inner
+// functions in a `__name` helper that does not exist in the page.
+const STATUS_SCRIPT = `(() => {
+ const profile = window.__LOBE_RENDER_PROFILE__;
+ if (!profile) return { active: false, now: performance.now() };
+ return { ...profile.status(), buildMode: profile.buildMode, now: performance.now() };
+})()`;
+
+const readStatus = (page: Page) => page.evaluate<ProfileStatus>(STATUS_SCRIPT);
+
+/**
+ * Fails fast when the server is not a `LOBE_REACT_PROFILING=1` build: an
+ * ordinary bundle never fires `<Profiler>` callbacks, so every count would be
+ * zero and every budget would pass.
+ */
+export const assertProfilingBuild = async (page: Page) => {
+ const status = await readStatus(page);
+ if (status.buildMode !== 'profiling') {
+ throw new Error(
+ `window.__LOBE_RENDER_PROFILE__ is ${status.buildMode ?? 'missing'}; ` +
+ 'build the app with LOBE_REACT_PROFILING=1 before running @perf scenarios',
+ );
+ }
+};
+
+export const beginProfile = (page: Page, label: string) =>
+ page.evaluate((name) => window.__LOBE_RENDER_PROFILE__!.begin(name), label);
+
+/** Waits until no region has committed for `QUIET_MS`, then ends the scenario. */
+export const endProfileWhenSettled = async (page: Page): Promise<RenderReport> => {
+ const deadline = Date.now() + SETTLE_TIMEOUT_MS;
+
+ for (;;) {
+ const status = await readStatus(page);
+ const lastCommitAt = status.lastCommitAt ?? 0;
+ if (status.now - lastCommitAt >= QUIET_MS) break;
+ if (Date.now() > deadline) {
+ throw new Error(`React kept committing for ${SETTLE_TIMEOUT_MS}ms after the action`);
+ }
+ await page.waitForTimeout(100);
+ }
+
+ return page.evaluate(() => window.__LOBE_RENDER_PROFILE__!.end() as RenderReport);
+};
+
+declare global {
+ interface Window {
+ __LOBE_RENDER_PROFILE__?: {
+ begin: (label: string) => void;
+ buildMode: string;
+ end: () => unknown;
+ status: () => { active: boolean; lastCommitAt?: number };
+ };
+ }
+}
diff --git a/e2e/src/steps/performance/chatRenderBudget.steps.ts b/e2e/src/steps/performance/chatRenderBudget.steps.ts
new file mode 100644
index 00000000000..f5991d0a406
--- /dev/null
+++ b/e2e/src/steps/performance/chatRenderBudget.steps.ts
@@ -0,0 +1,207 @@
+/**
+ * Render-budget scenarios for opening and switching chats. They need a server
+ * built with `LOBE_REACT_PROFILING=1` and run only under `E2E_PERF=1`; see
+ * `e2e/src/features/performance/chat-render-budget.feature`.
+ */
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { After, Given, Then, When } from '@cucumber/cucumber';
+import type { Page } from '@playwright/test';
+import { expect } from '@playwright/test';
+
+import {
+ type ChatFixture,
+ removeChatFixture,
+ seedChatFixture,
+} from '../../performance/chatFixture';
+import { CHAT_RENDER_BUDGETS } from '../../performance/chatRenderBudgets';
+import {
+ type ChatRenderScenario,
+ findBudgetViolations,
+ resolveRunnerKind,
+ summarizeReports,
+} from '../../performance/renderBudget';
+import {
+ assertProfilingBuild,
+ beginProfile,
+ endProfileWhenSettled,
+ type RenderReport,
+} from '../../performance/renderProfile';
+import type { CustomWorld } from '../../support/world';
+
+const OPEN_ITERATIONS = 5;
+const CACHED_SWITCHES = 9;
+const UNCACHED_SWITCHES = 5;
+const COLD_SWITCHES = 3;
+const LOOP_TIMEOUT = 240_000;
+
+const RECEIPT_DIR = path.join(process.cwd(), 'reports', 'render-budget');
+
+interface PerfContext {
+ fixture: ChatFixture;
+ reports: Partial<Record<ChatRenderScenario, RenderReport[]>>;
+}
+
+const perf = (world: CustomWorld): PerfContext => world.testContext.perf;
+
+const topicUrl = (fixture: ChatFixture, index: number) =>
+ `/agent/${fixture.agentId}/${fixture.topicIds[index]}`;
+
+const waitForTranscript = (page: Page, fixture: ChatFixture, index: number) =>
+ expect(page.getByText(fixture.markers[index]).first()).toBeVisible({ timeout: 30_000 });
+
+/**
+ * Loads a topic in a new document and returns the `boot` scenario the
+ * profiling build started before the first commit.
+ */
+const openChat = async (page: Page, fixture: ChatFixture, index: number) => {
+ await page.goto(topicUrl(fixture, index), { waitUntil: 'domcontentloaded' });
+ await waitForTranscript(page, fixture, index);
+ await assertProfilingBuild(page);
+ return endProfileWhenSettled(page);
+};
+
+const switchTopic = async (page: Page, fixture: ChatFixture, index: number) => {
+ const item = page.locator(
+ `[data-testid="topic-item"][data-topic-id="${fixture.topicIds[index]}"]`,
+ );
+ await expect(item).toBeVisible();
+ // Park the pointer on the empty composer area so hover cards stay closed.
+ await page.mouse.move(900, 650);
+
+ await beginProfile(page, `switch:${index}`);
+ await item.click();
+ await waitForTranscript(page, fixture, index);
+ return endProfileWhenSettled(page);
+};
+
+const record = (world: CustomWorld, scenario: ChatRenderScenario, report: RenderReport) => {
+ const reports = (perf(world).reports[scenario] ??= []);
+ reports.push(report);
+ console.log(
+ ` 📏 ${scenario} #${reports.length}: ` +
+ Object.entries(report.regions)
+ .map(([region, r]) => `${region} ${r.renders}× ${r.actualDurationMs}ms`)
+ .join(', ') +
+ `, max frame gap ${report.frames.maxGapMs}ms`,
+ );
+};
+
+// ============================================
+// Given
+// ============================================
+
+Given('用户有一个带多个历史话题的 Agent', async function (this: CustomWorld) {
+ this.testContext.perf = { fixture: await seedChatFixture(), reports: {} } satisfies PerfContext;
+});
+
+// ============================================
+// When
+// ============================================
+
+When(
+ '用户多次打开该 Agent 的 chat 页面',
+ { timeout: LOOP_TIMEOUT },
+ async function (this: CustomWorld) {
+ const { fixture } = perf(this);
+
+ // The first load fills the HTTP cache; `open` measures a returning user.
+ await openChat(this.page, fixture, 0);
+
+ for (let i = 0; i < OPEN_ITERATIONS; i += 1) {
+ record(this, 'open', await openChat(this.page, fixture, 0));
+ }
+ },
+);
+
+When(
+ '用户在已打开过的话题之间来回切换',
+ { timeout: LOOP_TIMEOUT },
+ async function (this: CustomWorld) {
+ const { fixture } = perf(this);
+ const rotation = [0, 1, 2];
+
+ await openChat(this.page, fixture, 0);
+ // Load the other topics once so every measured switch reads from memory.
+ await switchTopic(this.page, fixture, 1);
+ await switchTopic(this.page, fixture, 2);
+
+ for (let i = 0; i < CACHED_SWITCHES; i += 1) {
+ record(this, 'switchCached', await switchTopic(this.page, fixture, rotation[i % 3]));
+ }
+ },
+);
+
+When(
+ '用户每次刷新页面后切换到另一个话题',
+ { timeout: LOOP_TIMEOUT },
+ async function (this: CustomWorld) {
+ const { fixture } = perf(this);
+
+ // Visit every target once so its transcript sits in the IndexedDB replica.
+ await openChat(this.page, fixture, 0);
+ for (let i = 1; i <= UNCACHED_SWITCHES; i += 1) await switchTopic(this.page, fixture, i);
+
+ for (let i = 1; i <= UNCACHED_SWITCHES; i += 1) {
+ await openChat(this.page, fixture, i - 1);
+ record(this, 'switchUncached', await switchTopic(this.page, fixture, i));
+ }
+ },
+);
+
+When(
+ '用户每次在全新的浏览器环境中打开 chat 后切换到另一个话题',
+ { timeout: LOOP_TIMEOUT },
+ async function (this: CustomWorld) {
+ const { fixture } = perf(this);
+ const cookies = await this.browserContext.cookies();
+
+ for (let i = 1; i <= COLD_SWITCHES; i += 1) {
+ // A new context has no HTTP cache and no IndexedDB replica.
+ const context = await this.browser.newContext({
+ baseURL: this.baseUrl,
+ viewport: { height: 720, width: 1280 },
+ });
+ try {
+ await context.addCookies(cookies);
+ const page = await context.newPage();
+ page.setDefaultTimeout(30_000);
+ await openChat(page, fixture, 0);
+ record(this, 'switchCold', await switchTopic(page, fixture, i));
+ } finally {
+ await context.close();
+ }
+ }
+ },
+);
+
+// ============================================
+// Then
+// ============================================
+
+Then('{string} 场景的渲染不超过预算', function (this: CustomWorld, scenario: ChatRenderScenario) {
+ const reports = perf(this).reports[scenario] ?? [];
+ expect(reports.length, `no ${scenario} samples were recorded`).toBeGreaterThan(0);
+
+ const runner = resolveRunnerKind();
+ const budget = CHAT_RENDER_BUDGETS[runner][scenario];
+ const summary = summarizeReports(reports);
+ const violations = findBudgetViolations(scenario, summary, budget);
+
+ fs.mkdirSync(RECEIPT_DIR, { recursive: true });
+ fs.writeFileSync(
+ path.join(RECEIPT_DIR, `${scenario}.json`),
+ JSON.stringify({ budget, reports, runner, scenario, summary, violations }, null, 2),
+ );
+ console.log(` 📊 ${scenario} (${runner}) p50: ${JSON.stringify(summary)}`);
+
+ if (violations.length > 0) {
+ throw new Error(`Render budget exceeded:\n${violations.map((v) => ` - ${v}`).join('\n')}`);
+ }
+});
+
+After({ tags: '@render-budget' }, async function (this: CustomWorld) {
+ const context = this.testContext.perf as PerfContext | undefined;
+ if (context) await removeChatFixture(context.fixture);
+});
diff --git a/e2e/src/support/world.ts b/e2e/src/support/world.ts
index 822946752cd..9d357dcd696 100644
--- a/e2e/src/support/world.ts
+++ b/e2e/src/support/world.ts
@@ -62,14 +62,16 @@ export class CustomWorld extends World {
return this.testContext;
}
- async init() {
+ get baseUrl(): string {
const PORT = process.env.PORT ? Number(process.env.PORT) : 3006;
- const BASE_URL = process.env.BASE_URL || `http://localhost:${PORT}`;
+ return process.env.BASE_URL || `http://localhost:${PORT}`;
+ }
+ async init() {
this.browser = await getSharedBrowser();
this.browserContext = await this.browser.newContext({
- baseURL: BASE_URL,
+ baseURL: this.baseUrl,
viewport: { height: 720, width: 1280 },
});
diff --git a/plugins/vite/sharedRendererConfig.ts b/plugins/vite/sharedRendererConfig.ts
index c2aa3044ede..3c2e7d7cb88 100644
--- a/plugins/vite/sharedRendererConfig.ts
+++ b/plugins/vite/sharedRendererConfig.ts
@@ -539,6 +539,23 @@ export function sharedRendererPlugins(options: SharedRendererOptions) {
];
}
+/**
+ * `LOBE_REACT_PROFILING=1` builds the renderer against React's profiling build,
+ * so `<Profiler>` callbacks fire in a production bundle. Render-budget E2E runs
+ * read the counts through `window.__LOBE_RENDER_PROFILE__`.
+ */
+export const isReactProfilingBuild = () => process.env.LOBE_REACT_PROFILING === '1';
+
+/**
+ * Only `react-dom/client` is swapped: `react-dom/profiling` re-exports the client
+ * API and still imports `react-dom` for the shared internals, so `createPortal`
+ * and `flushSync` callers keep using the same renderer instance.
+ */
+export const sharedRendererAlias = () =>
+ isReactProfilingBuild()
+ ? [{ find: /^react-dom\/client$/, replacement: 'react-dom/profiling' }]
+ : [];
+
export function sharedRendererDefine(options: { isElectron: boolean; isMobile: boolean }) {
const nextPublicDefine = Object.fromEntries(
Object.entries(process.env)
@@ -551,6 +568,7 @@ export function sharedRendererDefine(options: { isElectron: boolean; isMobile: b
'__DEV__': process.env.NODE_ENV !== 'production' ? 'true' : 'false',
'__ELECTRON__': JSON.stringify(options.isElectron),
'__MOBILE__': JSON.stringify(options.isMobile),
+ '__REACT_PROFILING__': JSON.stringify(isReactProfilingBuild()),
'__REACT_SCAN__': process.env.REACT_SCAN === 'true' ? 'true' : 'false',
'__TEST__': 'false',
...nextPublicDefine,
diff --git a/src/components/RenderProfiler/index.tsx b/src/components/RenderProfiler/index.tsx
new file mode 100644
index 00000000000..138774d5837
--- /dev/null
+++ b/src/components/RenderProfiler/index.tsx
@@ -0,0 +1,31 @@
+import { Profiler, type ProfilerOnRenderCallback, type ReactNode } from 'react';
+
+import {
+ isRenderProfileEnabled,
+ recordRegionRender,
+ type RenderProfileRegion,
+} from '@/libs/renderProfile';
+
+interface RenderProfilerProps {
+ children: ReactNode;
+ region: RenderProfileRegion;
+}
+
+const onRender: ProfilerOnRenderCallback = (id, phase, actualDuration, _base, _start, commit) => {
+ recordRegionRender(id as RenderProfileRegion, phase, actualDuration, commit);
+};
+
+/**
+ * Counts renders of one screen region for render-budget E2E runs. Ordinary
+ * production builds fold `isRenderProfileEnabled()` to `false` and render the
+ * children directly, so the wrapper adds nothing to the tree there.
+ */
+export const RenderProfiler = ({ children, region }: RenderProfilerProps) => {
+ if (!isRenderProfileEnabled()) return children;
+
+ return (
+ <Profiler id={region} onRender={onRender}>
+ {children}
+ </Profiler>
+ );
+};
diff --git a/src/features/AgentSidebar/index.tsx b/src/features/AgentSidebar/index.tsx
index 4345aca98f7..a5dd2718f6b 100644
--- a/src/features/AgentSidebar/index.tsx
+++ b/src/features/AgentSidebar/index.tsx
@@ -1,3 +1,4 @@
+import { RenderProfiler } from '@/components/RenderProfiler';
import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import AgentSidebarContent from './Content';
@@ -5,7 +6,11 @@ import AgentSidebarContent from './Content';
const Sidebar = () => {
return (
<NavPanelPortal navKey="agent">
- <AgentSidebarContent />
+ {/* The portal only registers its children; NavPanelHost renders them, so
+ the profiler must travel with the content to see its renders. */}
+ <RenderProfiler region={'sidebar'}>
+ <AgentSidebarContent />
+ </RenderProfiler>
</NavPanelPortal>
);
};
diff --git a/src/initialize.ts b/src/initialize.ts
index 5bdb468a6a6..11ce3ec9b6d 100644
--- a/src/initialize.ts
+++ b/src/initialize.ts
@@ -7,6 +7,7 @@ import relativeTime from 'dayjs/plugin/relativeTime';
import utc from 'dayjs/plugin/utc';
import { enableMapSet, enablePatches } from 'immer';
+import { installRenderProfile } from '@/libs/renderProfile';
import { isChunkLoadError, notifyChunkError } from '@/utils/chunkError';
enablePatches();
@@ -39,6 +40,10 @@ if (typeof window !== 'undefined') {
});
}
+// Profiling builds start counting renders before the first commit, so a test
+// can read the first page open as the `boot` scenario.
+installRenderProfile();
+
if (__DEV__ && __REACT_SCAN__) {
void import('react-scan').then(({ scan }) => {
scan({ enabled: true, showToolbar: true });
diff --git a/src/libs/renderProfile/index.ts b/src/libs/renderProfile/index.ts
new file mode 100644
index 00000000000..48d74fcb36c
--- /dev/null
+++ b/src/libs/renderProfile/index.ts
@@ -0,0 +1,108 @@
+import {
+ RenderProfileRecorder,
+ type RenderProfileRegion,
+ type RenderProfileReport,
+ type RenderProfileStatus,
+} from './recorder';
+
+export {
+ RENDER_PROFILE_REGIONS,
+ type RenderProfileRegion,
+ type RenderProfileReport,
+ type RenderProfileStatus,
+} from './recorder';
+
+/**
+ * Label of the scenario a profiling build starts on its own at boot, so a test
+ * can measure the first page open, which begins before any test code can run in
+ * the document.
+ */
+export const BOOT_RENDER_PROFILE_LABEL = 'boot';
+
+export interface RenderProfileController {
+ begin: (label: string) => void;
+ /** `profiling`: production bundle on react-dom/profiling; `development`: Vite dev server. */
+ buildMode: 'development' | 'profiling';
+ end: () => RenderProfileReport;
+ status: () => RenderProfileStatus;
+}
+
+declare global {
+ interface Window {
+ __LOBE_RENDER_PROFILE__?: RenderProfileController;
+ }
+}
+
+/**
+ * True when `<Profiler>` callbacks fire: development builds, or a production
+ * build made with `LOBE_REACT_PROFILING=1`. Ordinary production bundles fold
+ * this to `false`, so the region wrappers render bare children and the
+ * installer returns before creating anything.
+ */
+export const isRenderProfileEnabled = () =>
+ __DEV__ || (typeof __REACT_PROFILING__ !== 'undefined' && __REACT_PROFILING__);
+
+let recorder: RenderProfileRecorder | undefined;
+let frameLoopRunning = false;
+
+/**
+ * One loop at a time: a scenario that begins before the previous loop sees its
+ * end would otherwise run two loops and count every frame twice.
+ */
+const startFrameLoop = (target: RenderProfileRecorder) => {
+ if (frameLoopRunning) return;
+ frameLoopRunning = true;
+
+ const tick = (timestamp: number) => {
+ if (!target.active) {
+ frameLoopRunning = false;
+ return;
+ }
+ target.recordAnimationFrame(timestamp);
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+};
+
+const observeLongAnimationFrames = (target: RenderProfileRecorder) => {
+ if (!PerformanceObserver.supportedEntryTypes?.includes('long-animation-frame')) return;
+
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) target.recordLongAnimationFrame(entry.duration);
+ }).observe({ type: 'long-animation-frame' });
+};
+
+/**
+ * Exposes `window.__LOBE_RENDER_PROFILE__` for render-budget E2E runs. A
+ * profiling build also starts the `boot` scenario immediately.
+ */
+export const installRenderProfile = () => {
+ if (!isRenderProfileEnabled() || typeof window === 'undefined' || recorder) return;
+
+ const target = new RenderProfileRecorder(() => performance.now());
+ recorder = target;
+ observeLongAnimationFrames(target);
+
+ const begin = (label: string) => {
+ target.begin(label);
+ startFrameLoop(target);
+ };
+
+ window.__LOBE_RENDER_PROFILE__ = {
+ begin,
+ buildMode: __DEV__ ? 'development' : 'profiling',
+ end: () => target.end(),
+ status: () => target.status(),
+ };
+
+ if (!__DEV__) begin(BOOT_RENDER_PROFILE_LABEL);
+};
+
+export const recordRegionRender = (
+ region: RenderProfileRegion,
+ phase: 'mount' | 'update' | 'nested-update',
+ actualDuration: number,
+ commitTime: number,
+) => {
+ recorder?.recordRender(region, phase, actualDuration, commitTime);
+};
diff --git a/src/libs/renderProfile/recorder.test.ts b/src/libs/renderProfile/recorder.test.ts
new file mode 100644
index 00000000000..d018b594775
--- /dev/null
+++ b/src/libs/renderProfile/recorder.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it } from 'vitest';
+
+import { RenderProfileRecorder } from './recorder';
+
+const createRecorder = () => {
+ let now = 0;
+ const recorder = new RenderProfileRecorder(() => now);
+ return {
+ recorder,
+ setNow: (value: number) => {
+ now = value;
+ },
+ };
+};
+
+describe('RenderProfileRecorder', () => {
+ it('aggregates renders per region and counts distinct commits', () => {
+ const { recorder, setNow } = createRecorder();
+ recorder.begin('switch');
+
+ // One commit touching both nested regions, then an update of the sidebar alone.
+ recorder.recordRender('messages', 'mount', 4, 10);
+ recorder.recordRender('conversation', 'mount', 6, 10);
+ recorder.recordRender('sidebar', 'update', 1.234, 20);
+ recorder.recordRender('sidebar', 'nested-update', 2, 30);
+ setNow(50);
+
+ const report = recorder.end();
+
+ expect(report).toMatchObject({ commitCount: 3, durationMs: 50, label: 'switch' });
+ expect(report.regions.sidebar).toEqual({
+ actualDurationMs: 3.23,
+ maxActualDurationMs: 2,
+ mounts: 0,
+ renders: 2,
+ updates: 2,
+ });
+ expect(report.regions.messages).toMatchObject({ mounts: 1, renders: 1, updates: 0 });
+ expect(report.regions.conversation.actualDurationMs).toBe(6);
+ });
+
+ it('reports the longest gap between animation frames', () => {
+ const { recorder } = createRecorder();
+ recorder.begin('switch');
+
+ for (const timestamp of [0, 16, 33, 120, 136]) recorder.recordAnimationFrame(timestamp);
+ recorder.recordLongAnimationFrame(80);
+ recorder.recordLongAnimationFrame(60);
+
+ expect(recorder.end()).toMatchObject({
+ frames: { count: 5, maxGapMs: 87 },
+ longestAnimationFrameMs: 80,
+ });
+ });
+
+ it('ignores samples outside a scenario and starts each scenario from zero', () => {
+ const { recorder } = createRecorder();
+ recorder.recordRender('sidebar', 'update', 5, 1);
+ recorder.recordAnimationFrame(0);
+
+ recorder.begin('first');
+ recorder.recordRender('sidebar', 'update', 5, 2);
+ recorder.end();
+
+ recorder.recordRender('sidebar', 'update', 5, 3);
+ recorder.begin('second');
+
+ expect(recorder.end()).toMatchObject({
+ commitCount: 0,
+ frames: { count: 0, maxGapMs: 0 },
+ regions: { sidebar: { renders: 0 } },
+ });
+ });
+
+ it('exposes the latest commit time while a scenario is active', () => {
+ const { recorder, setNow } = createRecorder();
+ recorder.begin('switch');
+ setNow(42);
+ recorder.recordRender('messages', 'update', 1, 7);
+
+ expect(recorder.status()).toEqual({
+ active: true,
+ commitCount: 1,
+ frameCount: 0,
+ label: 'switch',
+ lastCommitAt: 42,
+ });
+ });
+
+ it('rejects overlapping scenarios and ending without one', () => {
+ const { recorder } = createRecorder();
+
+ expect(() => recorder.end()).toThrow('No render profile is active');
+
+ recorder.begin('boot');
+ expect(() => recorder.begin('switch')).toThrow('"boot" is still active');
+ });
+});
diff --git a/src/libs/renderProfile/recorder.ts b/src/libs/renderProfile/recorder.ts
new file mode 100644
index 00000000000..3ac43541e23
--- /dev/null
+++ b/src/libs/renderProfile/recorder.ts
@@ -0,0 +1,173 @@
+/**
+ * Screen regions wrapped in a `<RenderProfiler>`. Render-budget E2E scenarios
+ * assert per-region budgets, so the list is closed: a new region needs a budget
+ * entry in `e2e/src/performance/chatRenderBudgets.ts` before its numbers gate a PR.
+ *
+ * `conversation` is the whole chat column (header, message list and composer),
+ * so its numbers include `messages`; React reports a commit to every
+ * `<Profiler>` above the component that rendered.
+ */
+export const RENDER_PROFILE_REGIONS = ['sidebar', 'conversation', 'messages'] as const;
+
+export type RenderProfileRegion = (typeof RENDER_PROFILE_REGIONS)[number];
+
+export type RenderProfilePhase = 'mount' | 'update' | 'nested-update';
+
+export interface RenderProfileRegionReport {
+ /** Sum of `actualDuration` over every commit that touched the region. */
+ actualDurationMs: number;
+ /** Slowest single commit of the region. */
+ maxActualDurationMs: number;
+ mounts: number;
+ /** Commits that rendered anything inside the region (mounts + updates). */
+ renders: number;
+ updates: number;
+}
+
+export interface RenderProfileReport {
+ /** Distinct React commits seen by any region. */
+ commitCount: number;
+ durationMs: number;
+ frames: {
+ count: number;
+ /** Longest gap between two consecutive animation frames, i.e. the worst visible stall. */
+ maxGapMs: number;
+ };
+ label: string;
+ /** Longest `long-animation-frame` entry; 0 when the browser lacks the API or none occurred. */
+ longestAnimationFrameMs: number;
+ regions: Record<RenderProfileRegion, RenderProfileRegionReport>;
+}
+
+export interface RenderProfileStatus {
+ active: boolean;
+ commitCount: number;
+ frameCount: number;
+ label?: string;
+ /** `performance.now()` of the latest commit, used by tests to wait for the UI to settle. */
+ lastCommitAt?: number;
+}
+
+const round = (value: number) => Math.round(value * 100) / 100;
+
+const emptyRegion = (): RenderProfileRegionReport => ({
+ actualDurationMs: 0,
+ maxActualDurationMs: 0,
+ mounts: 0,
+ renders: 0,
+ updates: 0,
+});
+
+/**
+ * Aggregates `<Profiler>` callbacks and frame timestamps for one scenario at a
+ * time. Counters are folded in place, so a scenario left running for the whole
+ * session (the automatic boot scenario) keeps constant memory.
+ */
+export class RenderProfileRecorder {
+ #commits = new Set<number>();
+ #frameCount = 0;
+ #label?: string;
+ #lastCommitAt?: number;
+ #lastFrameAt?: number;
+ #longestAnimationFrameMs = 0;
+ #maxFrameGapMs = 0;
+ #regions = {} as Record<RenderProfileRegion, RenderProfileRegionReport>;
+ #startedAt = 0;
+
+ constructor(private readonly now: () => number) {}
+
+ get active() {
+ return this.#label !== undefined;
+ }
+
+ begin(label: string) {
+ if (this.#label !== undefined) {
+ throw new Error(`Render profile "${this.#label}" is still active; end it first`);
+ }
+
+ this.#label = label;
+ this.#startedAt = this.now();
+ this.#commits = new Set();
+ this.#frameCount = 0;
+ this.#lastCommitAt = undefined;
+ this.#lastFrameAt = undefined;
+ this.#longestAnimationFrameMs = 0;
+ this.#maxFrameGapMs = 0;
+ this.#regions = Object.fromEntries(
+ RENDER_PROFILE_REGIONS.map((region) => [region, emptyRegion()]),
+ ) as Record<RenderProfileRegion, RenderProfileRegionReport>;
+ }
+
+ end(): RenderProfileReport {
+ const label = this.#label;
+ if (label === undefined) throw new Error('No render profile is active');
+
+ this.#label = undefined;
+
+ return {
+ commitCount: this.#commits.size,
+ durationMs: round(this.now() - this.#startedAt),
+ frames: { count: this.#frameCount, maxGapMs: round(this.#maxFrameGapMs) },
+ label,
+ longestAnimationFrameMs: round(this.#longestAnimationFrameMs),
+ regions: Object.fromEntries(
+ RENDER_PROFILE_REGIONS.map((region) => {
+ const report = this.#regions[region];
+ return [
+ region,
+ {
+ ...report,
+ actualDurationMs: round(report.actualDurationMs),
+ maxActualDurationMs: round(report.maxActualDurationMs),
+ },
+ ];
+ }),
+ ) as Record<RenderProfileRegion, RenderProfileRegionReport>,
+ };
+ }
+
+ recordAnimationFrame(timestamp: number) {
+ if (this.#label === undefined) return;
+
+ if (this.#lastFrameAt !== undefined) {
+ this.#maxFrameGapMs = Math.max(this.#maxFrameGapMs, timestamp - this.#lastFrameAt);
+ }
+ this.#lastFrameAt = timestamp;
+ this.#frameCount += 1;
+ }
+
+ recordLongAnimationFrame(durationMs: number) {
+ if (this.#label === undefined) return;
+
+ this.#longestAnimationFrameMs = Math.max(this.#longestAnimationFrameMs, durationMs);
+ }
+
+ recordRender(
+ region: RenderProfileRegion,
+ phase: RenderProfilePhase,
+ actualDuration: number,
+ commitTime: number,
+ ) {
+ if (this.#label === undefined) return;
+
+ const report = this.#regions[region];
+ report.renders += 1;
+ if (phase === 'mount') report.mounts += 1;
+ else report.updates += 1;
+ report.actualDurationMs += actualDuration;
+ report.maxActualDurationMs = Math.max(report.maxActualDurationMs, actualDuration);
+
+ this.#commits.add(commitTime);
+ this.#lastCommitAt = this.now();
+ }
+
+ status(): RenderProfileStatus {
+ return {
+ active: this.active,
+ commitCount: this.#commits.size,
+ frameCount: this.#frameCount,
+ label: this.#label,
+ lastCommitAt: this.#lastCommitAt,
+ };
+ }
+}
diff --git a/src/routes/(main)/agent/(chat)/_layout/index.tsx b/src/routes/(main)/agent/(chat)/_layout/index.tsx
index c48c3692383..db92946b224 100644
--- a/src/routes/(main)/agent/(chat)/_layout/index.tsx
+++ b/src/routes/(main)/agent/(chat)/_layout/index.tsx
@@ -2,13 +2,16 @@
import { Outlet } from 'react-router';
+import { RenderProfiler } from '@/components/RenderProfiler';
import ConversationWorkspace from '@/features/Conversation/Workspace';
import ChatHeader from '@/routes/(main)/agent/features/Conversation/Header';
const ChatLayout = () => (
- <ConversationWorkspace header={<ChatHeader />}>
- <Outlet />
- </ConversationWorkspace>
+ <RenderProfiler region={'conversation'}>
+ <ConversationWorkspace header={<ChatHeader />}>
+ <Outlet />
+ </ConversationWorkspace>
+ </RenderProfiler>
);
export default ChatLayout;
diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
index 5837bfad861..34a6bf77f77 100644
--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
@@ -5,6 +5,7 @@ import { memo, Suspense, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useBusinessConversationAnalytics } from '@/business/client/hooks/useBusinessConversationAnalytics';
+import { RenderProfiler } from '@/components/RenderProfiler';
import AgentHome from '@/features/AgentHome';
import { useSlugRouteSendGuard } from '@/features/AgentRoute/useSlugRouteSendGuard';
import {
@@ -159,33 +160,35 @@ const Conversation = memo(() => {
{topicPending ? (
<TopicMigrationPlaceholder agentId={context.agentId} topicId={context.topicId} />
) : (
- <ChatList
- printable
- headerSlot={<div aria-hidden className={styles.floatingHeaderSpacer} />}
- messageDeepLink={messageDeepLink}
- welcome={<AgentHome />}
- footerSlot={
- isSubagentThread ? (
- <Flexbox
- horizontal
- align={'center'}
- justify={'center'}
- paddingBlock={6}
- paddingInline={16}
- >
- <span
- style={{
- color: cssVar.colorTextDescription,
- fontSize: 12,
- textAlign: 'center',
- }}
+ <RenderProfiler region={'messages'}>
+ <ChatList
+ printable
+ headerSlot={<div aria-hidden className={styles.floatingHeaderSpacer} />}
+ messageDeepLink={messageDeepLink}
+ welcome={<AgentHome />}
+ footerSlot={
+ isSubagentThread ? (
+ <Flexbox
+ horizontal
+ align={'center'}
+ justify={'center'}
+ paddingBlock={6}
+ paddingInline={16}
>
- {t('thread.subagentReadOnlyHint')}
- </span>
- </Flexbox>
- ) : undefined
- }
- />
+ <span
+ style={{
+ color: cssVar.colorTextDescription,
+ fontSize: 12,
+ textAlign: 'center',
+ }}
+ >
+ {t('thread.subagentReadOnlyHint')}
+ </span>
+ </Flexbox>
+ ) : undefined
+ }
+ />
+ </RenderProfiler>
)}
</Flexbox>
</SplitDropZone>
diff --git a/src/types/global.d.ts b/src/types/global.d.ts
index ebcca521712..75a98ec42c7 100644
--- a/src/types/global.d.ts
+++ b/src/types/global.d.ts
@@ -41,6 +41,9 @@ declare global {
/** Vite define: running under Vitest */
const __TEST__: boolean;
+ /** Vite define: renderer built against react-dom/profiling (LOBE_REACT_PROFILING=1) */
+ const __REACT_PROFILING__: boolean;
+
/** Vite define: enable react-scan diagnostic runtime */
const __REACT_SCAN__: boolean;
diff --git a/vite.config.ts b/vite.config.ts
index 135b45086c8..33486bce1bb 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -17,6 +17,7 @@ import {
sharedOptimizeDeps,
sharedPwaGlobIgnores,
sharedPwaRuntimeCaching,
+ sharedRendererAlias,
sharedRendererDedupe,
sharedRendererDefine,
sharedRendererPlugins,
@@ -141,6 +142,7 @@ export default defineConfig({
bundledDev: false,
},
resolve: {
+ alias: sharedRendererAlias(),
dedupe: sharedRendererDedupe,
tsconfigPaths: true,
},