Add desktop perf trace automation and CI reporting
- add automated Electron renderer perf tracing with seeded state and scripted UI interactions - add `test:desktop-perf` and `test:desktop-perf:post` scripts to generate, validate, and summarize traces - run desktop perf trace in CI and post/update PR perf summaries on pull requests
This commit is contained in:
1 parent
9e877f592b
commit
a1177c736c
7 files changed
+856
-8
No files matched your search
@@ -6,6 +6,10 @@ on:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Test, Build
|
||||
@@ -48,3 +52,13 @@ jobs:
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
|
||||
- name: Desktop perf trace test
|
||||
if: github.event_name != 'pull_request'
|
||||
run: xvfb-run -a bun run test:desktop-perf
|
||||
|
||||
- name: Desktop perf trace test and PR summary
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: xvfb-run -a bun run test:desktop-perf:post
|
||||
+381
-3
@@ -5,7 +5,16 @@ import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
contentTracing,
|
||||
dialog,
|
||||
ipcMain,
|
||||
Menu,
|
||||
shell,
|
||||
type WebContents,
|
||||
} from "electron";
|
||||
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { fixPath } from "./fixPath";
|
||||
@@ -19,8 +28,11 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
|
||||
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
|
||||
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
|
||||
const STATE_DIR = process.env.T3CODE_STATE_DIR?.trim() || path.join(os.homedir(), ".t3", "userdata");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const PERF_AUTOMATION_ENABLED = process.env.T3CODE_DESKTOP_PERF_AUTOMATION === "1";
|
||||
const PERF_TRACE_OUT_PATH = process.env.T3CODE_DESKTOP_PERF_TRACE_OUT?.trim() ?? "";
|
||||
const PERF_DONE_OUT_PATH = process.env.T3CODE_DESKTOP_PERF_DONE_OUT?.trim() ?? "";
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess | null = null;
|
||||
@@ -31,6 +43,367 @@ let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
function waitForDidFinishLoad(webContents: WebContents): Promise<void> {
|
||||
if (!webContents.isLoading()) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const onLoad = () => resolve();
|
||||
webContents.once("did-finish-load", onLoad);
|
||||
});
|
||||
}
|
||||
|
||||
interface PerfPersistedMessage {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
text: string;
|
||||
createdAt: string;
|
||||
streaming: false;
|
||||
}
|
||||
|
||||
interface PerfPersistedThread {
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
terminalOpen: false;
|
||||
messages: PerfPersistedMessage[];
|
||||
createdAt: string;
|
||||
lastVisitedAt: string;
|
||||
}
|
||||
|
||||
interface PerfPersistedProject {
|
||||
id: string;
|
||||
name: string;
|
||||
cwd: string;
|
||||
model: string;
|
||||
expanded: true;
|
||||
}
|
||||
|
||||
interface PerfPersistedState {
|
||||
version: 7;
|
||||
runtimeMode: "approval-required";
|
||||
projects: PerfPersistedProject[];
|
||||
threads: PerfPersistedThread[];
|
||||
activeThreadId: string | null;
|
||||
}
|
||||
|
||||
function buildPerfSeedState(): PerfPersistedState {
|
||||
const now = Date.now();
|
||||
const projects: PerfPersistedProject[] = [
|
||||
{
|
||||
id: "perf-project-1",
|
||||
name: "codething-mvp",
|
||||
cwd: "/tmp/perf/codething-mvp",
|
||||
model: "gpt-5-codex",
|
||||
expanded: true,
|
||||
},
|
||||
{
|
||||
id: "perf-project-2",
|
||||
name: "contracts-bench",
|
||||
cwd: "/tmp/perf/contracts-bench",
|
||||
model: "gpt-5-codex",
|
||||
expanded: true,
|
||||
},
|
||||
];
|
||||
|
||||
const threads: PerfPersistedThread[] = [];
|
||||
let threadOrdinal = 0;
|
||||
|
||||
for (const project of projects) {
|
||||
for (let threadIndex = 0; threadIndex < 5; threadIndex += 1) {
|
||||
const threadId = `${project.id}-thread-${threadIndex + 1}`;
|
||||
const threadCreatedAt = new Date(now - (threadOrdinal + 1) * 45_000).toISOString();
|
||||
const messages: PerfPersistedMessage[] = [];
|
||||
const exchangeCount = 6;
|
||||
for (let exchangeIndex = 0; exchangeIndex < exchangeCount; exchangeIndex += 1) {
|
||||
const msgBaseOffsetMs =
|
||||
(threadOrdinal * exchangeCount + exchangeIndex + 1) * 4_500 + threadIndex * 850;
|
||||
const userCreatedAt = new Date(now - msgBaseOffsetMs - 1_500).toISOString();
|
||||
const assistantCreatedAt = new Date(now - msgBaseOffsetMs).toISOString();
|
||||
messages.push({
|
||||
id: `${threadId}-user-${exchangeIndex + 1}`,
|
||||
role: "user",
|
||||
text: `Investigate renderer performance pattern ${exchangeIndex + 1} for ${project.name}.`,
|
||||
createdAt: userCreatedAt,
|
||||
streaming: false,
|
||||
});
|
||||
messages.push({
|
||||
id: `${threadId}-assistant-${exchangeIndex + 1}`,
|
||||
role: "assistant",
|
||||
text: [
|
||||
`Profiling note ${exchangeIndex + 1}:`,
|
||||
"- Checked event dispatch and render cadence.",
|
||||
"- Compared selector interactions and thread switches.",
|
||||
"- Captured actionable optimization candidates.",
|
||||
].join("\n"),
|
||||
createdAt: assistantCreatedAt,
|
||||
streaming: false,
|
||||
});
|
||||
}
|
||||
|
||||
threads.push({
|
||||
id: threadId,
|
||||
projectId: project.id,
|
||||
title: `${project.name} perf thread ${threadIndex + 1}`,
|
||||
model: "gpt-5-codex",
|
||||
terminalOpen: false,
|
||||
messages,
|
||||
createdAt: threadCreatedAt,
|
||||
lastVisitedAt: new Date(now - threadOrdinal * 2_000).toISOString(),
|
||||
});
|
||||
threadOrdinal += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
version: 7,
|
||||
runtimeMode: "approval-required",
|
||||
projects,
|
||||
threads,
|
||||
activeThreadId: threads[0]?.id ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function seedRendererState(window: BrowserWindow): Promise<void> {
|
||||
const state = buildPerfSeedState();
|
||||
const script = `
|
||||
(() => {
|
||||
const key = "t3code:renderer-state:v7";
|
||||
localStorage.setItem(key, JSON.stringify(${JSON.stringify(state)}));
|
||||
return true;
|
||||
})();
|
||||
`;
|
||||
await window.webContents.executeJavaScript(script, true);
|
||||
}
|
||||
|
||||
async function runRendererPerfInteractions(
|
||||
window: BrowserWindow,
|
||||
): Promise<{ threadClicks: number; typedChars: number; selectedModel: string | null }> {
|
||||
const script = `
|
||||
(async () => {
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const must = (condition, message) => {
|
||||
if (!condition) throw new Error(message);
|
||||
};
|
||||
|
||||
const clickElement = (node) => {
|
||||
if (!(node instanceof HTMLElement)) return false;
|
||||
node.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true, cancelable: true }));
|
||||
node.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));
|
||||
node.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true }));
|
||||
node.click();
|
||||
return true;
|
||||
};
|
||||
|
||||
const threadButtons = Array.from(document.querySelectorAll("[data-perf-thread-id]"));
|
||||
must(threadButtons.length >= 4, "Expected seeded thread rows to be rendered.");
|
||||
|
||||
const clickCount = Math.min(8, threadButtons.length);
|
||||
for (let index = 0; index < clickCount; index += 1) {
|
||||
clickElement(threadButtons[index]);
|
||||
await sleep(80);
|
||||
}
|
||||
|
||||
const scroller = document.querySelector("[data-perf-messages-scroll]");
|
||||
if (scroller instanceof HTMLElement) {
|
||||
scroller.scrollTo({ top: scroller.scrollHeight, behavior: "instant" });
|
||||
await sleep(60);
|
||||
scroller.scrollTo({ top: 0, behavior: "instant" });
|
||||
await sleep(60);
|
||||
}
|
||||
|
||||
const textarea = document.querySelector("[data-perf-composer-input]");
|
||||
must(textarea instanceof HTMLTextAreaElement, "Composer textarea missing.");
|
||||
textarea.focus();
|
||||
|
||||
const valueDescriptor = Object.getOwnPropertyDescriptor(
|
||||
HTMLTextAreaElement.prototype,
|
||||
"value",
|
||||
);
|
||||
const setValue = valueDescriptor?.set;
|
||||
must(typeof setValue === "function", "Textarea value setter unavailable.");
|
||||
const inputText = "Benchmarking typing and selector workflows in desktop mode.";
|
||||
|
||||
for (const character of inputText) {
|
||||
textarea.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: character, bubbles: true, cancelable: true }),
|
||||
);
|
||||
setValue.call(textarea, textarea.value + character);
|
||||
textarea.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
|
||||
textarea.dispatchEvent(
|
||||
new KeyboardEvent("keyup", { key: character, bubbles: true, cancelable: true }),
|
||||
);
|
||||
await sleep(8);
|
||||
}
|
||||
|
||||
const selectOption = async (triggerSelector, optionSelector, label) => {
|
||||
const trigger = document.querySelector(triggerSelector);
|
||||
must(trigger instanceof HTMLElement, label + " trigger not found.");
|
||||
clickElement(trigger);
|
||||
await sleep(130);
|
||||
|
||||
const options = Array.from(document.querySelectorAll(optionSelector)).filter(
|
||||
(node) => node instanceof HTMLElement,
|
||||
);
|
||||
must(options.length > 0, label + " options not found.");
|
||||
const preferred = options[1] ?? options[0];
|
||||
clickElement(preferred);
|
||||
await sleep(130);
|
||||
return preferred.textContent?.trim() ?? null;
|
||||
};
|
||||
|
||||
const selectedModel = await selectOption(
|
||||
"[data-perf-model-trigger]",
|
||||
"[data-perf-model-option]",
|
||||
"Model",
|
||||
);
|
||||
await selectOption(
|
||||
"[data-perf-reasoning-trigger]",
|
||||
"[data-perf-reasoning-option]",
|
||||
"Reasoning",
|
||||
);
|
||||
|
||||
const diffToggle = document.querySelector("[data-perf-diff-toggle]");
|
||||
if (diffToggle instanceof HTMLElement) {
|
||||
clickElement(diffToggle);
|
||||
await sleep(70);
|
||||
clickElement(diffToggle);
|
||||
await sleep(70);
|
||||
}
|
||||
|
||||
const runtimeToggle = document.querySelector("[data-perf-runtime-toggle]");
|
||||
if (runtimeToggle instanceof HTMLElement) {
|
||||
clickElement(runtimeToggle);
|
||||
await sleep(100);
|
||||
}
|
||||
|
||||
return {
|
||||
threadClicks: clickCount,
|
||||
typedChars: inputText.length,
|
||||
selectedModel,
|
||||
};
|
||||
})();
|
||||
`;
|
||||
|
||||
return window.webContents.executeJavaScript(script, true);
|
||||
}
|
||||
|
||||
async function runPerfAutomation(window: BrowserWindow): Promise<void> {
|
||||
if (!PERF_AUTOMATION_ENABLED) return;
|
||||
console.log("[desktop-perf] automation mode enabled");
|
||||
if (PERF_DONE_OUT_PATH.length > 0) {
|
||||
console.log(`[desktop-perf] done marker path: ${PERF_DONE_OUT_PATH}`);
|
||||
}
|
||||
console.log(`[desktop-perf] trace path: ${PERF_TRACE_OUT_PATH}`);
|
||||
|
||||
if (PERF_TRACE_OUT_PATH.length === 0) {
|
||||
const error = new Error("T3CODE_DESKTOP_PERF_TRACE_OUT is required for perf automation.");
|
||||
console.error("[desktop-perf] " + error.message);
|
||||
if (PERF_DONE_OUT_PATH.length > 0) {
|
||||
fs.mkdirSync(path.dirname(PERF_DONE_OUT_PATH), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
PERF_DONE_OUT_PATH,
|
||||
JSON.stringify(
|
||||
{
|
||||
status: "error",
|
||||
error: error.message,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const traceConfig = {
|
||||
included_categories: [
|
||||
"devtools.timeline",
|
||||
"disabled-by-default-devtools.timeline",
|
||||
"disabled-by-default-devtools.timeline.frame",
|
||||
"blink.user_timing",
|
||||
"v8",
|
||||
"disabled-by-default-v8.cpu_profiler",
|
||||
"disabled-by-default-v8.gc",
|
||||
],
|
||||
record_mode: "record-until-full",
|
||||
};
|
||||
|
||||
let tracePath = PERF_TRACE_OUT_PATH;
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
console.log("[desktop-perf] waiting for initial load");
|
||||
await waitForDidFinishLoad(window.webContents);
|
||||
console.log("[desktop-perf] seeding renderer state");
|
||||
await seedRendererState(window);
|
||||
window.webContents.reload();
|
||||
console.log("[desktop-perf] waiting for reload");
|
||||
await waitForDidFinishLoad(window.webContents);
|
||||
await delay(300);
|
||||
|
||||
fs.mkdirSync(path.dirname(PERF_TRACE_OUT_PATH), { recursive: true });
|
||||
console.log("[desktop-perf] starting trace recording");
|
||||
await contentTracing.startRecording(traceConfig);
|
||||
console.log("[desktop-perf] running scripted interactions");
|
||||
const interactions = await runRendererPerfInteractions(window);
|
||||
await delay(300);
|
||||
console.log("[desktop-perf] stopping trace recording");
|
||||
tracePath = await contentTracing.stopRecording(PERF_TRACE_OUT_PATH);
|
||||
const completedAt = Date.now();
|
||||
|
||||
console.log(`[desktop-perf] trace recorded at ${tracePath}`);
|
||||
if (PERF_DONE_OUT_PATH.length > 0) {
|
||||
fs.mkdirSync(path.dirname(PERF_DONE_OUT_PATH), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
PERF_DONE_OUT_PATH,
|
||||
JSON.stringify(
|
||||
{
|
||||
status: "ok",
|
||||
tracePath,
|
||||
interactions,
|
||||
startedAt: new Date(startedAt).toISOString(),
|
||||
completedAt: new Date(completedAt).toISOString(),
|
||||
durationMs: completedAt - startedAt,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
try {
|
||||
tracePath = await contentTracing.stopRecording(PERF_TRACE_OUT_PATH);
|
||||
} catch {
|
||||
// Ignore errors while attempting to stop a recording that may not have started.
|
||||
}
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error("[desktop-perf] automation failed:", message);
|
||||
if (PERF_DONE_OUT_PATH.length > 0) {
|
||||
fs.mkdirSync(path.dirname(PERF_DONE_OUT_PATH), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
PERF_DONE_OUT_PATH,
|
||||
JSON.stringify(
|
||||
{
|
||||
status: "error",
|
||||
error: message,
|
||||
tracePath,
|
||||
startedAt: new Date(startedAt).toISOString(),
|
||||
completedAt: new Date().toISOString(),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const probe = net.createServer();
|
||||
@@ -229,7 +602,9 @@ function createWindow(): BrowserWindow {
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
if (!PERF_AUTOMATION_ENABLED) {
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
}
|
||||
} else {
|
||||
if (!fs.existsSync(WEB_ENTRY)) {
|
||||
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
|
||||
@@ -255,6 +630,9 @@ async function bootstrap(): Promise<void> {
|
||||
registerIpcHandlers();
|
||||
startBackend();
|
||||
mainWindow = createWindow();
|
||||
if (mainWindow && PERF_AUTOMATION_ENABLED) {
|
||||
void runPerfAutomation(mainWindow);
|
||||
}
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
|
||||
@@ -1344,6 +1344,7 @@ export default function ChatView() {
|
||||
{/* Messages */}
|
||||
<div
|
||||
ref={messagesScrollRef}
|
||||
data-perf-messages-scroll
|
||||
className="min-h-0 flex-1 overflow-y-auto px-5 py-4"
|
||||
onScroll={onMessagesScroll}
|
||||
>
|
||||
@@ -1426,6 +1427,7 @@ export default function ChatView() {
|
||||
)}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
data-perf-composer-input
|
||||
className="w-full resize-none bg-transparent text-[14px] leading-relaxed text-foreground placeholder:text-muted-foreground/35 focus:outline-none"
|
||||
rows={2}
|
||||
value={prompt}
|
||||
@@ -1482,6 +1484,7 @@ export default function ChatView() {
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
size="sm"
|
||||
type="button"
|
||||
data-perf-runtime-toggle
|
||||
disabled={isSwitchingRuntimeMode}
|
||||
onClick={() =>
|
||||
void handleRuntimeModeChange(
|
||||
@@ -1682,6 +1685,7 @@ const ChatHeader = memo(function ChatHeader({
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
data-perf-diff-toggle
|
||||
className={cn(
|
||||
"text-muted-foreground/70 hover:text-foreground/80",
|
||||
diffOpen && "bg-accent text-accent-foreground",
|
||||
@@ -2008,12 +2012,12 @@ const ModelPicker = memo(function ModelPicker(props: {
|
||||
value={props.model}
|
||||
onValueChange={(value) => (value ? props.onModelChange(value) : undefined)}
|
||||
>
|
||||
<SelectTrigger size="sm" variant="ghost">
|
||||
<SelectTrigger size="sm" variant="ghost" data-perf-model-trigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup alignItemWithTrigger={false}>
|
||||
{MODEL_OPTIONS.map(({ slug, name }) => (
|
||||
<SelectItem key={slug} value={slug}>
|
||||
<SelectItem key={slug} value={slug} data-perf-model-option={slug}>
|
||||
{name}
|
||||
</SelectItem>
|
||||
))}
|
||||
@@ -2031,12 +2035,12 @@ const ReasoningEffortPicker = memo(function ReasoningEffortPicker(props: {
|
||||
value={props.effort}
|
||||
onValueChange={(value) => (value ? props.onEffortChange(value) : undefined)}
|
||||
>
|
||||
<SelectTrigger variant="ghost" size="sm">
|
||||
<SelectTrigger variant="ghost" size="sm" data-perf-reasoning-trigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup alignItemWithTrigger={false}>
|
||||
{REASONING_OPTIONS.map((effort) => (
|
||||
<SelectItem key={effort} value={effort}>
|
||||
<SelectItem key={effort} value={effort} data-perf-reasoning-option={effort}>
|
||||
{effort}
|
||||
{effort === DEFAULT_REASONING ? " (default)" : ""}
|
||||
</SelectItem>
|
||||
|
||||
@@ -505,6 +505,7 @@ export default function Sidebar() {
|
||||
<button
|
||||
key={thread.id}
|
||||
type="button"
|
||||
data-perf-thread-id={thread.id}
|
||||
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 ${
|
||||
isActive
|
||||
? "bg-accent text-foreground"
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
"lint": "oxlint --report-unused-disable-directives",
|
||||
"test": "turbo run test",
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"test:desktop-perf": "node scripts/desktop-perf-trace.mjs",
|
||||
"test:desktop-perf:post": "node scripts/desktop-perf-trace.mjs --post-pr",
|
||||
"fmt": "oxfmt",
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts",
|
||||
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo",
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
import { spawn, execFileSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(__dirname, "..");
|
||||
const marker = "<!-- desktop-perf-trace-summary -->";
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = new Set(argv.slice(2));
|
||||
return {
|
||||
postPr: args.has("--post-pr"),
|
||||
};
|
||||
}
|
||||
|
||||
function toMs(us) {
|
||||
return us / 1000;
|
||||
}
|
||||
|
||||
function round(n, digits = 3) {
|
||||
return Number(n.toFixed(digits));
|
||||
}
|
||||
|
||||
function mb(bytes) {
|
||||
return bytes / (1024 * 1024);
|
||||
}
|
||||
|
||||
function summarizeTrace(tracePath) {
|
||||
const payload = JSON.parse(fs.readFileSync(tracePath, "utf8"));
|
||||
const events = payload.traceEvents;
|
||||
|
||||
const durationByName = new Map();
|
||||
const dispatchRows = [];
|
||||
const functionRows = [];
|
||||
const userTiming = new Map();
|
||||
const updateCounters = [];
|
||||
|
||||
for (const event of events) {
|
||||
if (event.name === "UpdateCounters" && event.args?.data) {
|
||||
const heap = event.args.data.jsHeapSizeUsed;
|
||||
if (typeof heap === "number") {
|
||||
updateCounters.push(heap);
|
||||
}
|
||||
}
|
||||
|
||||
if (event.cat === "blink.user_timing" && typeof event.name === "string") {
|
||||
userTiming.set(event.name, (userTiming.get(event.name) ?? 0) + 1);
|
||||
}
|
||||
|
||||
if (event.ph !== "X" || typeof event.dur !== "number" || typeof event.name !== "string") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const byName = durationByName.get(event.name) ?? { count: 0, dur: 0, max: 0 };
|
||||
byName.count += 1;
|
||||
byName.dur += event.dur;
|
||||
byName.max = Math.max(byName.max, event.dur);
|
||||
durationByName.set(event.name, byName);
|
||||
|
||||
if (event.name === "EventDispatch") {
|
||||
const type = event.args?.data?.type ?? "";
|
||||
dispatchRows.push({ type, dur: event.dur });
|
||||
}
|
||||
|
||||
if (event.name === "FunctionCall") {
|
||||
const functionName = event.args?.data?.functionName ?? "(unknown)";
|
||||
functionRows.push({ functionName, dur: event.dur });
|
||||
}
|
||||
}
|
||||
|
||||
const aggregateDispatchType = (type) => {
|
||||
const rows = dispatchRows.filter((row) => row.type === type);
|
||||
if (rows.length === 0) {
|
||||
return {
|
||||
count: 0,
|
||||
totalMs: 0,
|
||||
avgMs: 0,
|
||||
maxMs: 0,
|
||||
};
|
||||
}
|
||||
const totalDur = rows.reduce((sum, row) => sum + row.dur, 0);
|
||||
const maxDur = rows.reduce((max, row) => Math.max(max, row.dur), 0);
|
||||
return {
|
||||
count: rows.length,
|
||||
totalMs: round(toMs(totalDur)),
|
||||
avgMs: round(toMs(totalDur / rows.length)),
|
||||
maxMs: round(toMs(maxDur)),
|
||||
};
|
||||
};
|
||||
|
||||
const aggregateFunction = (name) => {
|
||||
const rows = functionRows.filter((row) => row.functionName === name);
|
||||
if (rows.length === 0) {
|
||||
return {
|
||||
count: 0,
|
||||
totalMs: 0,
|
||||
avgMs: 0,
|
||||
maxMs: 0,
|
||||
};
|
||||
}
|
||||
const totalDur = rows.reduce((sum, row) => sum + row.dur, 0);
|
||||
const maxDur = rows.reduce((max, row) => Math.max(max, row.dur), 0);
|
||||
return {
|
||||
count: rows.length,
|
||||
totalMs: round(toMs(totalDur)),
|
||||
avgMs: round(toMs(totalDur / rows.length)),
|
||||
maxMs: round(toMs(maxDur)),
|
||||
};
|
||||
};
|
||||
|
||||
const topUserTiming = [...userTiming.entries()]
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 10)
|
||||
.map(([name, count]) => ({ name, count }));
|
||||
|
||||
const topDurationEvents = [...durationByName.entries()]
|
||||
.map(([name, value]) => ({
|
||||
name,
|
||||
count: value.count,
|
||||
totalMs: round(toMs(value.dur), 2),
|
||||
avgMs: round(toMs(value.dur / value.count)),
|
||||
maxMs: round(toMs(value.max)),
|
||||
}))
|
||||
.sort((a, b) => b.totalMs - a.totalMs)
|
||||
.slice(0, 10);
|
||||
|
||||
const heap = (() => {
|
||||
if (updateCounters.length === 0) return null;
|
||||
const first = updateCounters[0];
|
||||
const last = updateCounters[updateCounters.length - 1];
|
||||
const min = Math.min(...updateCounters);
|
||||
const max = Math.max(...updateCounters);
|
||||
return {
|
||||
firstMb: round(mb(first), 1),
|
||||
lastMb: round(mb(last), 1),
|
||||
minMb: round(mb(min), 1),
|
||||
maxMb: round(mb(max), 1),
|
||||
deltaMb: round(mb(last - first), 1),
|
||||
};
|
||||
})();
|
||||
|
||||
const longDispatchCount = dispatchRows.filter((row) => row.dur >= 50_000).length;
|
||||
|
||||
return {
|
||||
keypress: aggregateDispatchType("keypress"),
|
||||
textInput: aggregateDispatchType("textInput"),
|
||||
input: aggregateDispatchType("input"),
|
||||
keydown: aggregateDispatchType("keydown"),
|
||||
dispatchDiscreteEvent: aggregateFunction("dispatchDiscreteEvent"),
|
||||
performWorkUntilDeadline: aggregateFunction("performWorkUntilDeadline"),
|
||||
longDispatchCount,
|
||||
heap,
|
||||
topUserTiming,
|
||||
topDurationEvents,
|
||||
};
|
||||
}
|
||||
|
||||
function createMarkdownSummary({ tracePath, donePayload, summary, thresholds }) {
|
||||
const lines = [
|
||||
marker,
|
||||
"## Desktop Dev Perf Trace",
|
||||
"",
|
||||
`- Command: \`bun dev:desktop\``,
|
||||
`- Trace: \`${tracePath}\``,
|
||||
`- Started: ${donePayload.startedAt ?? "n/a"}`,
|
||||
`- Completed: ${donePayload.completedAt ?? "n/a"}`,
|
||||
`- Duration: ${donePayload.durationMs ?? "n/a"} ms`,
|
||||
"",
|
||||
"### Interaction Run",
|
||||
"",
|
||||
`- Thread clicks: ${donePayload.interactions?.threadClicks ?? "n/a"}`,
|
||||
`- Typed chars: ${donePayload.interactions?.typedChars ?? "n/a"}`,
|
||||
`- Model selected: ${donePayload.interactions?.selectedModel ?? "n/a"}`,
|
||||
"",
|
||||
"### Input Event Metrics",
|
||||
"",
|
||||
"| Event | Count | Avg (ms) | Max (ms) | Total (ms) |",
|
||||
"| --- | ---: | ---: | ---: | ---: |",
|
||||
`| keypress | ${summary.keypress.count} | ${summary.keypress.avgMs} | ${summary.keypress.maxMs} | ${summary.keypress.totalMs} |`,
|
||||
`| textInput | ${summary.textInput.count} | ${summary.textInput.avgMs} | ${summary.textInput.maxMs} | ${summary.textInput.totalMs} |`,
|
||||
`| input | ${summary.input.count} | ${summary.input.avgMs} | ${summary.input.maxMs} | ${summary.input.totalMs} |`,
|
||||
`| keydown | ${summary.keydown.count} | ${summary.keydown.avgMs} | ${summary.keydown.maxMs} | ${summary.keydown.totalMs} |`,
|
||||
"",
|
||||
"### Scheduler/Event Hotspots",
|
||||
"",
|
||||
`- dispatchDiscreteEvent: ${summary.dispatchDiscreteEvent.totalMs}ms total (${summary.dispatchDiscreteEvent.count} calls)`,
|
||||
`- performWorkUntilDeadline: ${summary.performWorkUntilDeadline.totalMs}ms total (${summary.performWorkUntilDeadline.count} calls)`,
|
||||
`- EventDispatch spikes >= 50ms: ${summary.longDispatchCount}`,
|
||||
"",
|
||||
"### Threshold Check",
|
||||
"",
|
||||
`- keypress avg <= ${thresholds.maxKeypressAvgMs}ms: ${
|
||||
summary.keypress.avgMs <= thresholds.maxKeypressAvgMs ? "pass" : "fail"
|
||||
}`,
|
||||
`- keypress max <= ${thresholds.maxKeypressMaxMs}ms: ${
|
||||
summary.keypress.maxMs <= thresholds.maxKeypressMaxMs ? "pass" : "fail"
|
||||
}`,
|
||||
`- long dispatch spikes <= ${thresholds.maxLongDispatchCount}: ${
|
||||
summary.longDispatchCount <= thresholds.maxLongDispatchCount ? "pass" : "fail"
|
||||
}`,
|
||||
"",
|
||||
];
|
||||
|
||||
if (summary.heap) {
|
||||
lines.push("### Heap Counters", "");
|
||||
lines.push(
|
||||
`- first=${summary.heap.firstMb}MB, last=${summary.heap.lastMb}MB, min=${summary.heap.minMb}MB, max=${summary.heap.maxMb}MB, delta=${summary.heap.deltaMb}MB`,
|
||||
"",
|
||||
);
|
||||
}
|
||||
|
||||
lines.push("### Top User Timing Marks", "");
|
||||
for (const entry of summary.topUserTiming) {
|
||||
lines.push(`- ${entry.count}x ${entry.name}`);
|
||||
}
|
||||
lines.push("", "### Top Duration Events", "");
|
||||
for (const entry of summary.topDurationEvents) {
|
||||
lines.push(
|
||||
`- ${entry.name}: total=${entry.totalMs}ms, avg=${entry.avgMs}ms, max=${entry.maxMs}ms, count=${entry.count}`,
|
||||
);
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
async function waitForDoneFile(donePath, child, timeoutMs) {
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
if (fs.existsSync(donePath)) {
|
||||
return JSON.parse(fs.readFileSync(donePath, "utf8"));
|
||||
}
|
||||
if (child.exitCode !== null) {
|
||||
throw new Error(`desktop dev process exited early (code ${child.exitCode})`);
|
||||
}
|
||||
await sleep(500);
|
||||
}
|
||||
throw new Error(`Timed out waiting for done marker at ${donePath}`);
|
||||
}
|
||||
|
||||
async function terminateProcessTree(child) {
|
||||
if (child.exitCode !== null) return;
|
||||
|
||||
if (process.platform === "win32") {
|
||||
try {
|
||||
execFileSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
} catch {
|
||||
child.kill("SIGTERM");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
process.kill(-child.pid, "SIGTERM");
|
||||
} catch {
|
||||
child.kill("SIGTERM");
|
||||
}
|
||||
|
||||
await sleep(1_500);
|
||||
if (child.exitCode === null) {
|
||||
try {
|
||||
process.kill(-child.pid, "SIGKILL");
|
||||
} catch {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function detectPrNumber() {
|
||||
const githubRef = process.env.GITHUB_REF ?? "";
|
||||
const match = githubRef.match(/refs\/pull\/(\d+)\//);
|
||||
if (match?.[1]) {
|
||||
return match[1];
|
||||
}
|
||||
|
||||
return execFileSync("gh", ["pr", "view", "--json", "number", "--jq", ".number"], {
|
||||
cwd: repoRoot,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
}
|
||||
|
||||
function postSummaryToPr(summaryPath) {
|
||||
const prNumber = detectPrNumber();
|
||||
execFileSync(
|
||||
"gh",
|
||||
["pr", "comment", prNumber, "--body-file", summaryPath, "--edit-last", "--create-if-none"],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function prepareDesktopPerfState(stateDir) {
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
|
||||
const perfProjects = [
|
||||
{
|
||||
id: "perf-project-1",
|
||||
cwd: "/tmp/perf/codething-mvp",
|
||||
name: "codething-mvp",
|
||||
},
|
||||
{
|
||||
id: "perf-project-2",
|
||||
cwd: "/tmp/perf/contracts-bench",
|
||||
name: "contracts-bench",
|
||||
},
|
||||
];
|
||||
|
||||
for (const project of perfProjects) {
|
||||
fs.mkdirSync(project.cwd, { recursive: true });
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
fs.writeFileSync(
|
||||
path.join(stateDir, "projects.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
version: 1,
|
||||
projects: perfProjects.map((project) => ({
|
||||
id: project.id,
|
||||
cwd: project.cwd,
|
||||
name: project.name,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv);
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const artifactsDir = path.join(os.tmpdir(), "t3code-perf-artifacts", `desktop-dev-${timestamp}`);
|
||||
fs.mkdirSync(artifactsDir, { recursive: true });
|
||||
|
||||
const tracePath = path.join(artifactsDir, "trace.json");
|
||||
const donePath = path.join(artifactsDir, "done.json");
|
||||
const summaryPath = path.join(artifactsDir, "summary.md");
|
||||
const logPath = path.join(artifactsDir, "run.log");
|
||||
const stateDir = path.join(artifactsDir, "state");
|
||||
prepareDesktopPerfState(stateDir);
|
||||
|
||||
const maxKeypressAvgMs = Number(process.env.T3CODE_PERF_MAX_KEYPRESS_AVG_MS ?? "12");
|
||||
const maxKeypressMaxMs = Number(process.env.T3CODE_PERF_MAX_KEYPRESS_MAX_MS ?? "24");
|
||||
const maxLongDispatchCount = Number(process.env.T3CODE_PERF_MAX_LONG_DISPATCH_COUNT ?? "0");
|
||||
const timeoutMs = Number(process.env.T3CODE_PERF_TIMEOUT_MS ?? "240000");
|
||||
|
||||
const child = spawn("bun", ["dev:desktop"], {
|
||||
cwd: repoRoot,
|
||||
detached: process.platform !== "win32",
|
||||
env: {
|
||||
...process.env,
|
||||
T3CODE_DESKTOP_PERF_AUTOMATION: "1",
|
||||
T3CODE_DESKTOP_PERF_TRACE_OUT: tracePath,
|
||||
T3CODE_DESKTOP_PERF_DONE_OUT: donePath,
|
||||
T3CODE_DEV_INSTANCE: `desktop-perf-${timestamp}`,
|
||||
T3CODE_LOG_WS_EVENTS: "0",
|
||||
T3CODE_STATE_DIR: stateDir,
|
||||
},
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
const logs = [];
|
||||
const appendLog = (chunk) => {
|
||||
const text = chunk.toString();
|
||||
logs.push(text);
|
||||
if (logs.length > 1200) {
|
||||
logs.splice(0, logs.length - 1200);
|
||||
}
|
||||
fs.appendFileSync(logPath, text);
|
||||
process.stdout.write(text);
|
||||
};
|
||||
|
||||
child.stdout.on("data", appendLog);
|
||||
child.stderr.on("data", appendLog);
|
||||
|
||||
let donePayload;
|
||||
try {
|
||||
donePayload = await waitForDoneFile(donePath, child, timeoutMs);
|
||||
} finally {
|
||||
await terminateProcessTree(child);
|
||||
}
|
||||
|
||||
if (!donePayload || donePayload.status !== "ok") {
|
||||
throw new Error(
|
||||
`Desktop perf automation failed. ${donePayload?.error ?? "No completion payload written."}`,
|
||||
);
|
||||
}
|
||||
|
||||
const summary = summarizeTrace(tracePath);
|
||||
const markdown = createMarkdownSummary({
|
||||
tracePath,
|
||||
donePayload,
|
||||
summary,
|
||||
thresholds: {
|
||||
maxKeypressAvgMs,
|
||||
maxKeypressMaxMs,
|
||||
maxLongDispatchCount,
|
||||
},
|
||||
});
|
||||
fs.writeFileSync(summaryPath, markdown);
|
||||
|
||||
console.log(`\nPerf summary written to ${summaryPath}\n`);
|
||||
console.log(markdown);
|
||||
|
||||
const thresholdFailures = [];
|
||||
if (summary.keypress.avgMs > maxKeypressAvgMs) {
|
||||
thresholdFailures.push(
|
||||
`keypress avg ${summary.keypress.avgMs}ms exceeds ${maxKeypressAvgMs}ms`,
|
||||
);
|
||||
}
|
||||
if (summary.keypress.maxMs > maxKeypressMaxMs) {
|
||||
thresholdFailures.push(
|
||||
`keypress max ${summary.keypress.maxMs}ms exceeds ${maxKeypressMaxMs}ms`,
|
||||
);
|
||||
}
|
||||
if (summary.longDispatchCount > maxLongDispatchCount) {
|
||||
thresholdFailures.push(
|
||||
`long EventDispatch count ${summary.longDispatchCount} exceeds ${maxLongDispatchCount}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (args.postPr) {
|
||||
postSummaryToPr(summaryPath);
|
||||
}
|
||||
|
||||
if (thresholdFailures.length > 0) {
|
||||
throw new Error(`Performance thresholds failed:\n- ${thresholdFailures.join("\n- ")}`);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error("\nDesktop perf trace test failed:\n" + message);
|
||||
process.exit(1);
|
||||
});
|
||||
+4
-1
@@ -11,7 +11,10 @@
|
||||
"T3CODE_NO_BROWSER",
|
||||
"T3CODE_STATE_DIR",
|
||||
"T3CODE_AUTH_TOKEN",
|
||||
"T3CODE_DESKTOP_WS_URL"
|
||||
"T3CODE_DESKTOP_WS_URL",
|
||||
"T3CODE_DESKTOP_PERF_AUTOMATION",
|
||||
"T3CODE_DESKTOP_PERF_TRACE_OUT",
|
||||
"T3CODE_DESKTOP_PERF_DONE_OUT"
|
||||
],
|
||||
"tasks": {
|
||||
"build": {
|
||||
|
||||
Reference in new issue
Block a user