chore: add a desktop performance harness #21190
ClosedAlyx-ML(GitHub profile, opens in a new tab)wants to merge 1 commit into
main fromrefs/pull/21190/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -0,0 +317,21 @@317+ if (message.id !== undefined) {318+ this.pending.get(message.id)?.(message);319+ this.pending.delete(message.id);320+ } else {321+ for (const listener of this.listeners.get(message.method) ?? []) listener(message.params);322+ }323+ });324+ }325+326+ static async connect(url: string): Promise<Cdp> {327+ const socket = new WebSocket(url);328+ await new Promise((resolve, reject) => {329+ socket.addEventListener("open", resolve, { once: true });330+ socket.addEventListener("error", reject, { once: true });331+ });332+ return new Cdp(socket);333+ }334+335+ async send(method: string, params: Record<string, unknown> = {}): Promise<any> {336+ const id = ++this.nextId;337+ const reply = await new Promise<{ result?: any; error?: unknown }>((resolve) => {@@ -0,0 +1578,21 @@1578+ launches.push(await measureLaunch(app, home, out, 9351));1579+ launches.sort((a, b) => a.usableMs - b.usableMs);1580+ log(`launch done in ${round((performance.now() - started) / 1000, 0)}s`);1581+ const firstOpenLongChat = await measureFirstOpen(app, home, out, 9353);1582+ const session = await measureSession(app, home, out, 9352, deep);1583+ const results = {1584+ app,1585+ date: new Date().toISOString(),1586+ bundle,1587+ launch: launches[1]!,1588+ firstOpenLongChat,1589+ ...session,1590+ };1591+ const resultsPath = NodePath.join(out, "results.json");1592+ NodeFS.writeFileSync(resultsPath, `${JSON.stringify(results, null, 2)}\n`);1593+ log(`measured in ${round((performance.now() - started) / 1000, 0)}s, wrote ${resultsPath}`);1594+ const baseline = flag("baseline");1595+ const { app: _app, date: _date, ...scenes } = results;1596+ const before = baseline1597+ ? (({ app: _a, date: _d, ...rest }) => rest)(JSON.parse(NodeFS.readFileSync(baseline, "utf8")))1598+ : undefined;@@ -0,0 +435,21 @@435+ readonly spawnedAt: number;436+ readonly cdp: Cdp;437+ readonly pageAt: number;438+}439+440+function appExecutable(app: string) {441+ const macos = NodePath.join(app, "Contents/MacOS");442+ return NodePath.join(macos, NodeFS.readdirSync(macos)[0]!);443+}444+445+async function launch(app: string, home: string, port: number): Promise<RunningApp> {446+ const spawnedAt = performance.now();447+ // A scratch HOME has no login keychain; without the mock keychain Electron's448+ // safeStorage blocks the main thread on a macOS keychain dialog.449+ // The main-process inspector drives native window state, which page CDP cannot.450+ const child = NodeChildProcess.spawn(451+ appExecutable(app),452+ [`--remote-debugging-port=${port}`, `--inspect=${port + 1000}`, "--use-mock-keychain"],453+ {454+ cwd: home,455+ env: { ...process.env, HOME: home, T3CODE_DISABLE_AUTO_UPDATE: "1" },@@ -0,0 +1514,21 @@1514+ // The build shells out to `vp`, which lives in the workspace bin.1515+ env: {1516+ ...process.env,1517+ PATH: `${NodePath.join(repoRoot, "node_modules/.bin")}:${process.env.PATH}`,1518+ },1519+ stdio: ["ignore", "pipe", "pipe"],1520+ },1521+ );1522+ const stage = run("find", [1523+ NodeOS.tmpdir(),1524+ "-maxdepth",1525+ "1",1526+ "-name",1527+ "t3code-desktop-mac-stage-*",1528+ "-newer",1529+ NodePath.join(repoRoot, "package.json"),1530+ ])1531+ .trim()1532+ .split("\n")1533+ .filter(Boolean)1534+ .sort((a, b) => NodeFS.statSync(b).mtimeMs - NodeFS.statSync(a).mtimeMs)[0];
- @@ -0,0 +303,21 @@303+}304+305+class Cdp {306+ private nextId = 0;307+ private readonly pending = new Map<308+ number,309+ (message: { result?: any; error?: unknown }) => void310+ >();311+ private readonly listeners = new Map<string, Array<(params: any) => void>>();312+ private readonly socket: WebSocket;313+ private constructor(socket: WebSocket) {314+ this.socket = socket;315+ socket.addEventListener("message", (event) => {316+ const message = JSON.parse(String(event.data));317+ if (message.id !== undefined) {318+ this.pending.get(message.id)?.(message);319+ this.pending.delete(message.id);320+ } else {321+ for (const listener of this.listeners.get(message.method) ?? []) listener(message.params);322+ }323+ });@@ -0,0 +474,21 @@474+ );475+ if (page) {476+ const pageAt = performance.now();477+ return { child, port, spawnedAt, pageAt, cdp: await Cdp.connect(page.webSocketDebuggerUrl) };478+ }479+ if (performance.now() - spawnedAt > 60_000) throw new Error("no page target after 60s");480+ await sleep(25);481+ }482+}483+484+async function quit(app: RunningApp) {485+ app.cdp.close();486+ app.child.kill("SIGTERM");487+ const exited = new Promise((resolve) => app.child.once("exit", resolve));488+ if (489+ app.child.exitCode === null &&490+ (await Promise.race([exited.then(() => true), sleep(15_000).then(() => false)])) === false491+ ) {492+ app.child.kill("SIGKILL");493+ await exited;494+ }@@ -0,0 +569,21 @@569+ run(570+ appExecutable(app),571+ [serverEntry, "doctor", "--fix", "--base-dir", NodePath.join(home, ".t3")],572+ {573+ env: { ...process.env, HOME: home, ELECTRON_RUN_AS_NODE: "1" },574+ },575+ );576+}577+578+// A copy of the template after one ordinary ~2 minute session of this app, so579+// measurements start where a returning user's would: the open-time PRAGMA580+// optimize has analyzed the grown tables and startup maintenance has run.581+// Otherwise every measured launch re-analyzes 1.5M rows from a cold cache.582+async function warmedHome(app: string, template: string, out: string) {583+ const asar = NodeFS.statSync(NodePath.join(app, "Contents/Resources/app.asar"));584+ const key = NodeCrypto.createHash("sha1")585+ .update(`${NodeFS.realpathSync(app)}:${asar.size}:${asar.mtimeMs}`)586+ .digest("hex")587+ .slice(0, 10);588+ const home = NodePath.join(out, `home-warm-${key}`);589+ if (NodeFS.existsSync(NodePath.join(home, ".warmed"))) return home;@@ -0,0 +955,21 @@955+ slowestFramesMs,956+ slowestFrameMs: slowestFramesMs[0] ?? 0,957+ slowestTask,958+ mainThreadBusyPct: round(959+ (tasks.reduce((sum, value) => sum + value, 0) / (seconds * 1000)) * 100,960+ 2,961+ ),962+ framesPerSec: round(count("DrawFrame") / seconds, 2),963+ paintsPerSec: round(count("Paint") / seconds, 2),964+ timersPerSec: round(count("TimerFire") / seconds, 2),965+ droppedFrames: dropped,966+ };967+}968+969+// Event Timing: input-to-next-paint for every interaction slower than 16 ms.970+const OBSERVE_INPUT = `(() => {971+ window.__perfInput = [];972+ new PerformanceObserver((list) => {973+ for (const entry of list.getEntries()) window.__perfInput.push({ name: entry.name, duration: entry.duration });974+ }).observe({ type: "event", durationThreshold: 16 });975+})()`;@@ -0,0 +1007,21 @@1007+1008+async function measureLaunch(app: string, template: string, out: string, port: number) {1009+ const home = freshHome(template, NodePath.join(out, "home-launch"));1010+ const session = await launch(app, home, port);1011+ const { value: usableAt, trace } = await traced(session.cdp, async () => {1012+ const at = await session.cdp.waitFor(1013+ `!!${COMPOSER} && document.querySelectorAll("[data-thread-item]").length >= 4`,1014+ 60_000,1015+ 10,1016+ );1017+ await sleep(1500);1018+ return at;1019+ });1020+ const result = {1021+ windowMs: round(session.pageAt - session.spawnedAt, 0),1022+ usableMs: round(usableAt - session.spawnedAt, 0),1023+ ...trace,1024+ memoryMB: footprintByRole(session.child.pid!),1025+ };1026+ await quit(session);1027+ return result;
Alyx-ML(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed