Files
apes-sidebar/tests/e2e/perf.e2e.ts
T
Menghuan1918 ebfb207f08 test(perf): 稳态门禁(跨模块计时器/布局/请求 + 客户端定时器清单)
单模块用例各盯自己的 hook;这条只问跨模块的问题:把真实 Sidebar 壳挂起来、
什么都不给看时,它手里还握着多少会自己跑起来的东西。

- 非 blank 会话只允许存在**一条** 500ms 表(共享的宿主面板展开态),且不得存在 5s
  表(每 tab 轮询已收敛为按会话 + 可见性);收起工作台时壳自己不得发 session.cwd;
  隐藏页面时那条 500ms 表也必须消失,恢复即可重挂。
- 兜底入口在非 blank 会话渲染 null:宿主角落控件在场(measure() 能走到让位走查)
  时命中测试必须为 0——before 侧真机实测 1620 次,after 侧 0。
- 末节是**客户端 setInterval 站点清单**:8 个站点逐一登记「它什么时候停」,新增未
  登记的周期任务即红,登记了门控词却把门控删掉也红(绊线)。
- perf lane 新增 steady-state 指标与两条硬断言(兜底入口不渲染即不得命中测试、
  session.cwd 必须按会话而非按访问过的页签计数)。真机 A/B:500ms 表 3→1、
  5s 表 5→0、空闲窗 session.cwd 15→0、命中测试 1620→0、rect 5190→30。
2026-10-15 23:05:43 +08:00

457 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Perf lane: a MEASUREMENT harness, not a pass/fail gate (beyond the mount
* sanity it shares with the other lanes).
*
* It exists to put NUMBERS on the sidebar's client-side cost in a real
* mounted `dsh web` (the same scratch-profile boot as scripts/e2e-mount.sh):
*
* 1. mount latency — navigationStart → `[data-dsh-better-sidebar]`
* attached, sampled by an init-script probe (rAF loop, so it catches
* the attach even before Playwright's first poll);
* 2. longtasks — every >50ms main-thread task from first paint
* through the full built-in tab sweep (the heaviest mount surface);
* 3. bundle cost — per-resource transferSize/decodedBodySize/duration
* for everything sidebar-shaped the page fetched;
* 4. bottom-drag frames — rAF frame-interval p95/max while dragging the
* bottom strip (the layout-push hot path), plus the width-leak guard
* from the drag lane (this shell pushes no width at all: the right
* column belongs to DSH's native Sidebar).
* 5. steady-state recurring work — with visited native tabs left parked,
* how much work does the plugin keep alive while nobody interacts: live
* intervals by delay, forced-layout reads (getBoundingClientRect /
* getComputedStyle / elementsFromPoint) and `/sidebar/api/*` requests
* grouped by route. This is the only place the "an invisible tab keeps
* polling" class of regression is observable end to end, so it carries
* the lane's two hard assertions: `elementsFromPoint` must stay at 0
* while the blank-session fallback entry is not rendered, and
* `session.cwd` must be polled once per SESSION rather than once per
* mounted native tab body (four visited tabs would otherwise keep four
* pollers, each landing on the host's git-probing cwd resolver).
*
* Results print as single-line `PERF_JSON` records (plus a `PERF_SUMMARY`
* aggregate) so a shell run can `tee` the log and grep them out; the
* before/after comparison lives in docs/plans/2026-08-31-perf-optimization.md.
* Run it 3× and take the median of each metric — single-run numbers on a
* developer machine are noise, not baselines.
*/
import { mkdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test, expect, type APIRequestContext, type Page } from '@playwright/test'
import { PAGE_URL, createHostApi, hostRpc, sendFirstMessage } from './host'
/** This lane's own workspace (lanes run serially against one server — never
* share seed paths with mount/drag). */
const WORKSPACE_PATH = process.env.DSH_E2E_PERF_WORKSPACE ?? join(tmpdir(), 'dsh-e2e-perf-workspace')
/**
* Every tab type the composed guide must offer: the plugin's own four plus the
* host's `terminal`. This plugin deliberately ships neither terminal nor
* browser, so exactly one `terminal` entry proves it is not shadowing the host.
*
* `browser` is deliberately absent: DSH 0.1.7 mounts
* `@deepseek-ai/dsh-client-ui-sidebar-browser` only for the desktop profile and
* this lane drives the web profile, so demanding a `browser` entry would demand
* something the host itself stopped offering. mount.e2e.ts asserts the absence
* explicitly. The ids are the guides' `data-sidebar-right-guide-entry` keys.
*/
const NATIVE_TABS = ['files', 'git', 'subagent', 'sidechat', 'terminal'] as const
let api: APIRequestContext
async function seedSession(): Promise<void> {
mkdirSync(WORKSPACE_PATH, { recursive: true })
writeFileSync(join(WORKSPACE_PATH, 'seed.txt'), 'perf lane\n')
const workspace = await hostRpc<{ workspace: { workspaceId: string } }>(api, 'workspace.create', { path: WORKSPACE_PATH })
await hostRpc(api, 'session.create', { workspaceId: workspace.value.workspace.workspaceId })
}
test.beforeAll(async () => {
api = await createHostApi()
await seedSession()
})
test.afterAll(async () => {
await api?.dispose()
})
/** The longtask collector + mount-attach probe, injected before ANY page
* script runs (longtasks observed late are gone forever). */
const PERF_PROBE = `(() => {
const perf = { mountAt: null, longtasks: [] }
window.__perfProbe = perf
new PerformanceObserver(list => {
for (const entry of list.getEntries()) perf.longtasks.push({ start: entry.startTime, duration: entry.duration })
}).observe({ entryTypes: ['longtask'] })
const check = () => {
if (document.querySelector('[data-dsh-better-sidebar]') !== null) { perf.mountAt = performance.now(); return }
requestAnimationFrame(check)
}
requestAnimationFrame(check)
})()`
function percentile(values: number[], p: number): number {
if (values.length === 0) return 0
const sorted = [...values].sort((a, b) => a - b)
const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1))
return sorted[index]!
}
interface ResourceStat {
name: string
transferSize: number
decodedBodySize: number
duration: number
}
/** Dismiss whatever onboarding takeover is present (same dance as the other
* lanes) so the pointer can reach the sidebar's controls. */
async function dismissOnboarding(page: Page): Promise<void> {
try {
await expect
.poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 })
.toBeGreaterThan(0)
} catch {
console.warn('[e2e-perf] no onboarding takeover appeared; proceeding')
}
for (let round = 0; round < 8; round++) {
let dismissed = false
for (const name of ['Continue', 'Configure later']) {
const button = page.getByRole('button', { name, exact: true }).first()
if ((await button.count()) === 0) continue
try {
await button.click({ timeout: 4_000 })
dismissed = true
await page.waitForTimeout(1_000)
} catch {
// Masked by a takeover stacked above; retry in the next round.
}
}
if (!dismissed) break
}
}
test('measure: mount latency, longtasks and bundle cost through a full tab sweep', async ({ page }) => {
await page.addInitScript(PERF_PROBE)
await page.goto(PAGE_URL, { waitUntil: 'domcontentloaded' })
await expect(page.locator('#root > *')).not.toHaveCount(0, { timeout: 90_000 })
const sidebar = page.locator('[data-dsh-better-sidebar]')
await expect(sidebar).toBeAttached({ timeout: 90_000 })
const mountLatency = await page.evaluate(() =>
(window as unknown as { __perfProbe: { mountAt: number | null } }).__perfProbe.mountAt)
expect(mountLatency, 'the mount probe must have caught the attach').not.toBeNull()
await dismissOnboarding(page)
// The native Sidebar's way in lives in the conversation header's corner,
// which DSH renders only for a session with content.
await sendFirstMessage(page)
// Open DSH's native right Sidebar and sweep every plugin tab type through
// its guide page — the same crash-sweep surface as mount.e2e.ts, reused
// here as the workload (the plugin's content lives in the native surface on
// 0.1.5; the plugin's own panel keeps only its bottom workbench).
await page.locator('[data-sidebar-right-expand]').first().click()
const pane = page.locator('[data-sidebar-right-panel]')
await expect(pane).toBeVisible({ timeout: 90_000 })
const addTab = page.locator('[data-dockkit-add-tab]').first()
for (const kind of NATIVE_TABS) {
if (await page.locator('[data-sidebar-right-guide]').count() === 0) await addTab.click()
const entry = page.locator(`[data-sidebar-right-guide-entry="${kind}"]`)
await expect(entry, `native tab type "${kind}" must be offered by the guide`).toHaveCount(1)
await entry.click()
await page.waitForTimeout(1_500)
}
// Let the last tab settle (lazy chunks + first render) before reading.
await page.waitForTimeout(2_000)
const probe = await page.evaluate(() => (window as unknown as { __perfProbe: { mountAt: number | null; longtasks: Array<{ start: number; duration: number }> } }).__perfProbe)
const resources = await page.evaluate(() =>
performance.getEntriesByType('resource')
.filter(entry => /sidebar/.test(entry.name))
.map(entry => {
const resource = entry as PerformanceResourceTiming
return {
name: entry.name.replace(/^https?:\/\/[^/]+/, ''),
transferSize: resource.transferSize,
decodedBodySize: resource.decodedBodySize,
duration: entry.duration,
}
}) as ResourceStat[],
)
const longtasks = probe.longtasks ?? []
const record = {
metric: 'mount-sweep',
mountLatencyMs: mountLatency,
longtaskCount: longtasks.length,
longtaskTotalMs: Math.round(longtasks.reduce((sum, task) => sum + task.duration, 0)),
longtaskMaxMs: longtasks.reduce((max, task) => Math.max(max, task.duration), 0),
resourceCount: resources.length,
resourceTransferTotal: resources.reduce((sum, r) => sum + r.transferSize, 0),
resourceDecodedTotal: resources.reduce((sum, r) => sum + r.decodedBodySize, 0),
resources,
}
console.log(`PERF_JSON ${JSON.stringify(record)}`)
console.log(
`PERF_SUMMARY mount=${Math.round(mountLatency!)}ms longtasks=${record.longtaskCount}/${record.longtaskTotalMs}ms `
+ `resources=${record.resourceCount}/${(record.resourceTransferTotal / 1024).toFixed(0)}KiB`,
)
})
test('measure: bottom-strip drag frame pacing', async ({ page }) => {
await page.addInitScript(PERF_PROBE)
await page.goto(PAGE_URL, { waitUntil: 'domcontentloaded' })
await expect(page.locator('#root > *')).not.toHaveCount(0, { timeout: 90_000 })
const sidebar = page.locator('[data-dsh-better-sidebar]')
await expect(sidebar).toBeAttached({ timeout: 90_000 })
await dismissOnboarding(page)
// The workbench's expand/collapse control is registered into DSH's
// session-header utilities, which DSH renders only for a session with
// content — seed one message first, then address the toggle by its stable
// data attribute (it is NOT inside the plugin's own host).
await sendFirstMessage(page)
// The plugin pushes no width ever (the right column is DSH's native
// Sidebar), so the drag must never write --dsh-sidebar-width — the guard
// the drag lane locks, recorded here for the perf story.
// 同上:入口按「屏幕内可见」断言与点击(其它会话的隐藏副本不算数)。
const bottomExpand = page.locator('[data-dsh-bottom-toggle]:visible').first()
await expect(bottomExpand).toBeVisible()
await bottomExpand.click()
await expect
.poll(async () => {
const value = await page.evaluate(() => parseFloat(document.documentElement.style.getPropertyValue('--dsh-sidebar-height')) || 0)
return value
}, { timeout: 90_000 })
.toBeGreaterThan(0)
// Frame-pacing sampler: rAF timestamps during the drag only.
await page.evaluate(() => {
const frames: number[] = []
const pushWidths: number[] = []
const loop = (): void => {
frames.push(performance.now())
const width = parseFloat(document.documentElement.style.getPropertyValue('--dsh-sidebar-width'))
pushWidths.push(Number.isNaN(width) ? 0 : width)
requestAnimationFrame(loop)
}
requestAnimationFrame(loop)
;(window as unknown as { __dragFrames: number[]; __dragPushWidths: number[] }).__dragFrames = frames
;(window as unknown as { __dragPushWidths: number[] }).__dragPushWidths = pushWidths
})
// The panel slides down into place on expand: read the strip only after it
// settles at innerHeight - the pushed height (a mid-animation box makes the
// pointerdown land off-strip and the drag never starts).
await expect
.poll(async () => {
const probe = await page.evaluate(() => {
const bottom = document.querySelector('[data-dsh-better-sidebar] [data-dsh-bottom-panel]')
if (bottom === null) return null
const strip = [...bottom.querySelectorAll<HTMLElement>('*')].find(el => getComputedStyle(el).cursor === 'row-resize')
if (strip === undefined) return null
const r = strip.getBoundingClientRect()
const heightVar = parseFloat(document.documentElement.style.getPropertyValue('--dsh-sidebar-height')) || 0
return Math.abs((r.y + r.height / 2) - (window.innerHeight - heightVar))
})
return probe === null ? Number.NaN : probe
}, { timeout: 30_000 })
.toBeLessThanOrEqual(8)
const stripPoint = await page.evaluate(() => {
const bottom = document.querySelector('[data-dsh-better-sidebar] [data-dsh-bottom-panel]')
if (bottom === null) return null
const strip = [...bottom.querySelectorAll<HTMLElement>('*')].find(el => getComputedStyle(el).cursor === 'row-resize')
if (strip === undefined) return null
const r = strip.getBoundingClientRect()
return { x: r.x + r.width / 2, y: r.y + r.height / 2 }
})
expect(stripPoint, 'the bottom drag strip must be present').not.toBeNull()
const t0 = await page.evaluate(() => performance.now())
await page.mouse.move(stripPoint!.x, stripPoint!.y)
await page.mouse.down()
for (let i = 1; i <= 12; i++) {
await page.mouse.move(stripPoint!.x, stripPoint!.y - i * 8, { steps: 2 })
await page.waitForTimeout(40)
}
await page.mouse.up()
const t1 = await page.evaluate(() => performance.now())
await page.waitForTimeout(300)
const { frames, widths } = await page.evaluate(() => ({
frames: (window as unknown as { __dragFrames: number[] }).__dragFrames,
widths: (window as unknown as { __dragPushWidths: number[] }).__dragPushWidths,
}))
const dragFrames = frames.filter(t => t >= t0 && t <= t1)
const intervals: number[] = []
for (let i = 1; i < dragFrames.length; i++) intervals.push(dragFrames[i]! - dragFrames[i - 1]!)
const dragWidths = widths.slice(Math.max(0, frames.indexOf(dragFrames[0] ?? frames[0]!)))
const record = {
metric: 'bottom-drag',
frames: dragFrames.length,
intervalMedianMs: Math.round(percentile(intervals, 50)),
intervalP95Ms: Math.round(percentile(intervals, 95)),
intervalMaxMs: Math.round(Math.max(0, ...intervals)),
pushWidthLeakMax: Math.max(0, ...dragWidths),
}
console.log(`PERF_JSON ${JSON.stringify(record)}`)
console.log(
`PERF_SUMMARY drag-frames=${record.frames} p50=${record.intervalMedianMs}ms p95=${record.intervalP95Ms}ms `
+ `max=${record.intervalMaxMs}ms widthLeak=${record.pushWidthLeakMax}px`,
)
expect(record.pushWidthLeakMax, 'the plugin must never push a width during the bottom drag').toBe(0)
})
/**
* Steady-state probe (installed before ANY page script, so every later
* `setInterval` is accounted for).
*
* Timers are tracked live (id → delay) instead of merely counted at creation,
* and the three forced-layout entry points are wrapped so a poller that reads
* layout on a timer cannot hide. Attribution is deliberately by DELAY +
* behaviour rather than by script URL: plugins on this host may be served from
* an aggregated bundle, so a stack test would be a false negative waiting to
* happen. `elementsFromPoint` is the fingerprinted call — only the blank-session
* dock fallback's retreat walk uses it.
*/
const STEADY_PROBE = `(() => {
const live = new Map()
const createdByDelay = {}
const nativeSet = window.setInterval
window.setInterval = function (handler, delay) {
const id = nativeSet.apply(this, arguments)
const key = Number(delay) || 0
live.set(id, key)
createdByDelay[key] = (createdByDelay[key] ?? 0) + 1
return id
}
const nativeClear = window.clearInterval
window.clearInterval = function (id) {
live.delete(id)
return nativeClear.apply(this, arguments)
}
const counts = { rect: 0, style: 0, hit: 0 }
const nativeRect = Element.prototype.getBoundingClientRect
Element.prototype.getBoundingClientRect = function () {
counts.rect += 1
return nativeRect.apply(this, arguments)
}
const nativeStyle = window.getComputedStyle
window.getComputedStyle = function () {
counts.style += 1
return nativeStyle.apply(this, arguments)
}
if (typeof document.elementsFromPoint === 'function') {
const nativeHit = document.elementsFromPoint
document.elementsFromPoint = function () {
counts.hit += 1
return nativeHit.apply(this, arguments)
}
}
window.__steady = {
counts,
createdByDelay,
snapshot: () => {
const liveByDelay = {}
for (const delay of live.values()) liveByDelay[delay] = (liveByDelay[delay] ?? 0) + 1
return { counts: { ...counts }, createdByDelay: { ...createdByDelay }, liveByDelay, liveTotal: live.size }
},
reset: () => { counts.rect = 0; counts.style = 0; counts.hit = 0 },
}
})()`
test('measure: steady-state recurring work while the visited session is parked', async ({ page }) => {
await page.addInitScript(PERF_PROBE)
await page.addInitScript(STEADY_PROBE)
// Requests by route for the whole test, so the idle window can be compared
// against the mount/sweep phase.
const routeCounts = new Map<string, number>()
let idleStart = 0
const idleRouteCounts = new Map<string, number>()
page.on('request', (request) => {
const url = request.url()
if (!url.includes('/sidebar/api/')) return
const route = url.split('/sidebar/api/')[1]?.split('?')[0] ?? 'unknown'
routeCounts.set(route, (routeCounts.get(route) ?? 0) + 1)
if (idleStart !== 0) idleRouteCounts.set(route, (idleRouteCounts.get(route) ?? 0) + 1)
})
await page.goto(PAGE_URL, { waitUntil: 'domcontentloaded' })
await expect(page.locator('#root > *')).not.toHaveCount(0, { timeout: 90_000 })
await expect(page.locator('[data-dsh-better-sidebar]')).toBeAttached({ timeout: 90_000 })
await dismissOnboarding(page)
await sendFirstMessage(page)
// Visit every plugin tab type so their bodies are mounted and then left
// parked — the shape `keepMounted` turns into permanent work under the
// pre-fix code (one `session.cwd` poller per body, forever).
await page.locator('[data-sidebar-right-expand]').first().click()
await expect(page.locator('[data-sidebar-right-panel]')).toBeVisible({ timeout: 90_000 })
const addTab = page.locator('[data-dockkit-add-tab]').first()
for (const kind of NATIVE_TABS) {
if (kind === 'terminal') continue // the host's own tab, not part of this measurement
if (await page.locator('[data-sidebar-right-guide]').count() === 0) await addTab.click()
const entry = page.locator(`[data-sidebar-right-guide-entry="${kind}"]`)
await expect(entry, `native tab type "${kind}" must be offered by the guide`).toHaveCount(1)
await entry.click()
await page.waitForTimeout(1_500)
}
await page.waitForTimeout(2_000)
// Park it: close the host's right Sidebar so nothing of the plugin is on
// screen except the shell, then measure the idle window.
await page.locator('[data-sidebar-right-toggle]').first().click().catch(() => {})
await page.waitForTimeout(1_000)
await page.evaluate(() => (window as unknown as { __steady: { reset: () => void } }).__steady.reset())
idleStart = Date.now()
await page.waitForTimeout(15_000)
const steady = await page.evaluate(() =>
(window as unknown as { __steady: { snapshot: () => unknown } }).__steady.snapshot(),
) as { counts: { rect: number; style: number; hit: number }; createdByDelay: Record<string, number>; liveByDelay: Record<string, number>; liveTotal: number }
const idleRoutes = Object.fromEntries(idleRouteCounts)
const sessionCwdIdle = idleRouteCounts.get('session.cwd') ?? 0
const record = {
metric: 'steady-state',
windowMs: 15_000,
liveByDelay: steady.liveByDelay,
createdByDelay: steady.createdByDelay,
liveTotal: steady.liveTotal,
forcedLayout: steady.counts,
routesAll: Object.fromEntries(routeCounts),
routesIdle: idleRoutes,
sessionCwdIdle,
visitedTabs: NATIVE_TABS.filter(kind => kind !== 'terminal').length,
}
console.log(`PERF_JSON ${JSON.stringify(record)}`)
console.log(
`PERF_SUMMARY steady-state 15s: live500=${steady.liveByDelay[500] ?? 0} `
+ `rect=${steady.counts.rect} style=${steady.counts.style} hitTest=${steady.counts.hit} `
+ `session.cwd=${sessionCwdIdle}`,
)
// Fingerprint call of the blank-session fallback's retreat walk. In a
// session with content that entry is not rendered, so the plugin must not
// hit-test at all; the budget is not 0 only because the HOST also uses
// `elementsFromPoint` (its chat and PDF-preview bundles) and a stray
// event-driven call must not fail this lane. Pre-fix the fallback's own
// 2 Hz walk alone lands ~150 hits in this window.
expect(
steady.counts.hit,
'the dock fallback must not measure (elementsFromPoint) while it renders nothing',
).toBeLessThan(40)
// One poller per SESSION, not per mounted tab body: four visited tabs on an
// unshared 5 s poller would report ~12 here, a shared one reports ~3.
const visited = record.visitedTabs
expect(
sessionCwdIdle,
`session.cwd must be polled once per session (${visited} visited tabs must not multiply it)`,
).toBeLessThanOrEqual(visited)
})