Add desktop perf trace automation #59
- @@ -33,0 +327,21 @@327+ "devtools.timeline",328+ "disabled-by-default-devtools.timeline",329+ "disabled-by-default-devtools.timeline.frame",330+ "blink.user_timing",331+ "v8",332+ "disabled-by-default-v8.cpu_profiler",333+ "disabled-by-default-v8.gc",334+ ],335+ record_mode: "record-until-full",336+ };337+338+ let tracePath = PERF_TRACE_OUT_PATH;339+ const startedAt = Date.now();340+ try {341+ console.log("[desktop-perf] waiting for initial load");342+ await waitForDidFinishLoad(window.webContents);343+ console.log("[desktop-perf] seeding renderer state");344+ await seedRendererState(window);345+ window.webContents.reload();346+ console.log("[desktop-perf] waiting for reload");347+ await waitForDidFinishLoad(window.webContents);
- apps/desktop/src/main.ts lines 55 to 58OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -31,3 +43,16 @@3143 let restartTimer: ReturnType<typeof setTimeout> | null = null;3244 let isQuitting = false;334546+function delay(ms: number): Promise<void> {47+ return new Promise((resolve) => setTimeout(resolve, ms));48+}49+50+function waitForDidFinishLoad(webContents: WebContents): Promise<void> {51+ if (!webContents.isLoading()) {52+ return Promise.resolve();53+ }54+55+ return new Promise((resolve) => {56+ const onLoad = () => resolve();57+ webContents.once("did-finish-load", onLoad);58+ });@@ -0,0 +265,21 @@265+ await sleep(1_500);266+ if (child.exitCode === null) {267+ try {268+ process.kill(-child.pid, "SIGKILL");269+ } catch {270+ child.kill("SIGKILL");271+ }272+ }273+}274+275+function detectPrNumber() {276+ const githubRef = process.env.GITHUB_REF ?? "";277+ const match = githubRef.match(/refs\/pull\/(\d+)\//);278+ if (match?.[1]) {279+ return match[1];280+ }281+282+ return execFileSync("gh", ["pr", "view", "--json", "number", "--jq", ".number"], {283+ cwd: repoRoot,284+ encoding: "utf8",285+ }).trim();scripts/desktop-perf-trace.mjs line 353OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +333,21 @@333+ },334+ null,335+ 2,336+ ),337+ );338+}339+340+async function main() {341+ const args = parseArgs(process.argv);342+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-");343+ const artifactsDir = path.join(os.tmpdir(), "t3code-perf-artifacts", `desktop-dev-${timestamp}`);344+ fs.mkdirSync(artifactsDir, { recursive: true });345+346+ const tracePath = path.join(artifactsDir, "trace.json");347+ const donePath = path.join(artifactsDir, "done.json");348+ const summaryPath = path.join(artifactsDir, "summary.md");349+ const logPath = path.join(artifactsDir, "run.log");350+ const stateDir = path.join(artifactsDir, "state");351+ prepareDesktopPerfState(stateDir);352+353+ const maxKeypressAvgMs = Number(process.env.T3CODE_PERF_MAX_KEYPRESS_AVG_MS ?? "12");
- .github/workflows/ci.yml lines 77 to 125Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -48,3 +52,13 @@4852 run: |4953 test -f apps/desktop/dist-electron/preload.js5054 grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js55+56+ - name: Desktop perf trace test57+ if: github.event_name != 'pull_request'58+ run: xvfb-run -a bun run test:desktop-perf59+60+ - name: Desktop perf trace test and PR summary61+ if: github.event_name == 'pull_request'62+ env:63+ GH_TOKEN: ${{ github.token }}64+ run: xvfb-run -a bun run test:desktop-perf:post@@ -0,0 +142,21 @@142+ minMb: round(mb(min), 1),143+ maxMb: round(mb(max), 1),144+ deltaMb: round(mb(last - first), 1),145+ };146+ })();147+148+ const longDispatchCount = dispatchRows.filter((row) => row.dur >= 50_000).length;149+150+ return {151+ keypress: aggregateDispatchType("keypress"),152+ textInput: aggregateDispatchType("textInput"),153+ input: aggregateDispatchType("input"),154+ keydown: aggregateDispatchType("keydown"),155+ dispatchDiscreteEvent: aggregateFunction("dispatchDiscreteEvent"),156+ performWorkUntilDeadline: aggregateFunction("performWorkUntilDeadline"),157+ longDispatchCount,158+ heap,159+ topUserTiming,160+ topDurationEvents,161+ };162+}
- @@ -0,0 +380,21 @@380+ fs.appendFileSync(logPath, text);381+ process.stdout.write(text);382+ };383+384+ child.stdout.on("data", appendLog);385+ child.stderr.on("data", appendLog);386+387+ let donePayload;388+ try {389+ donePayload = await waitForDoneFile(donePath, child, timeoutMs);390+ } finally {391+ await terminateProcessTree(child);392+ }393+394+ if (!donePayload || donePayload.status !== "ok") {395+ throw new Error(396+ `Desktop perf automation failed. ${donePayload?.error ?? "No completion payload written."}`,397+ );398+ }399+400+ const summary = summarizeTrace(tracePath);@@ -0,0 +283,21 @@283+ cwd: repoRoot,284+ encoding: "utf8",285+ }).trim();286+}287+288+function postSummaryToPr(summaryPath) {289+ const prNumber = detectPrNumber();290+ execFileSync(291+ "gh",292+ ["pr", "comment", prNumber, "--body-file", summaryPath, "--edit-last", "--create-if-none"],293+ {294+ cwd: repoRoot,295+ stdio: "inherit",296+ },297+ );298+}299+300+function prepareDesktopPerfState(stateDir) {301+ fs.mkdirSync(stateDir, { recursive: true });302+303+ const perfProjects = [
- @@ -31,3 +43,16 @@3143 let restartTimer: ReturnType<typeof setTimeout> | null = null;3244 let isQuitting = false;334546+function delay(ms: number): Promise<void> {47+ return new Promise((resolve) => setTimeout(resolve, ms));48+}49+50+function waitForDidFinishLoad(webContents: WebContents): Promise<void> {51+ if (!webContents.isLoading()) {52+ return Promise.resolve();53+ }54+55+ return new Promise((resolve) => {56+ const onLoad = () => resolve();57+ webContents.once("did-finish-load", onLoad);58+ });
- @@ -31,3 +39,12 @@3139 let restartTimer: ReturnType<typeof setTimeout> | null = null;3240 let isQuitting = false;334142+async function runPerfAutomationIfEnabled(window: BrowserWindow): Promise<void> {43+ if (!PERF_AUTOMATION_ENABLED) return;44+ try {45+ const { runDesktopPerfAutomation } = await import("./desktopPerfAutomation");46+ await runDesktopPerfAutomation(window);47+ } catch (error) {48+ const message = error instanceof Error ? error.message : String(error);49+ console.error("[desktop-perf] failed to load automation module:", message);50+ const doneOutPath = process.env.T3CODE_DESKTOP_PERF_DONE_OUT?.trim() ?? "";@@ -0,0 +340,21 @@340+ "disabled-by-default-devtools.timeline",341+ "disabled-by-default-devtools.timeline.frame",342+ "blink.user_timing",343+ "v8",344+ "disabled-by-default-v8.cpu_profiler",345+ "disabled-by-default-v8.gc",346+ ],347+ record_mode: "record-until-full",348+ };349+350+ let tracePath = PERF_TRACE_OUT_PATH;351+ const startedAt = Date.now();352+ try {353+ console.log("[desktop-perf] waiting for initial load");354+ await waitForDidFinishLoad(window.webContents, {355+ timeoutMs: 60_000,356+ label: "initial load",357+ });358+ console.log("[desktop-perf] seeding renderer state");359+ await seedRendererState(window);360+ window.webContents.reload();@@ -0,0 +385,21 @@385+ status: "ok",386+ tracePath,387+ interactions,388+ startedAt: new Date(startedAt).toISOString(),389+ completedAt: new Date(completedAt).toISOString(),390+ durationMs: completedAt - startedAt,391+ },392+ null,393+ 2,394+ ),395+ );396+ }397+ } catch (error) {398+ try {399+ tracePath = await contentTracing.stopRecording(PERF_TRACE_OUT_PATH);400+ } catch {401+ // Ignore errors while attempting to stop a recording that may not have started.402+ }403+ const message = error instanceof Error ? error.message : String(error);404+ console.error("[desktop-perf] automation failed:", message);405+ if (PERF_DONE_OUT_PATH.length > 0) {
juliusmarminge changed the title
- @@ -0,0 +278,21 @@278+ await sleep(1_500);279+ if (child.exitCode === null) {280+ try {281+ process.kill(-child.pid, "SIGKILL");282+ } catch {283+ child.kill("SIGKILL");284+ }285+ }286+}287+288+function detectPrNumber() {289+ const githubRef = process.env.GITHUB_REF ?? "";290+ const match = githubRef.match(/refs\/pull\/(\d+)\//);291+ if (match?.[1]) {292+ return match[1];293+ }294+295+ return execFileSync("gh", ["pr", "view", "--json", "number", "--jq", ".number"], {296+ cwd: repoRoot,297+ encoding: "utf8",298+ }).trim();@@ -0,0 +249,21 @@249+ if (fs.existsSync(donePath)) {250+ return JSON.parse(fs.readFileSync(donePath, "utf8"));251+ }252+ if (child.exitCode !== null) {253+ throw new Error(`desktop dev process exited early (code ${child.exitCode})`);254+ }255+ await sleep(500);256+ }257+ throw new Error(`Timed out waiting for done marker at ${donePath}`);258+}259+260+async function terminateProcessTree(child) {261+ if (child.exitCode !== null) return;262+263+ if (process.platform === "win32") {264+ try {265+ execFileSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });266+ } catch {267+ child.kill("SIGTERM");268+ }269+ return;
- @@ -0,0 +336,21 @@336+ }337+ await sleep(500);338+ }339+ throw new Error(`Timed out waiting for done marker at ${donePath}`);340+}341+342+async function terminateProcessTree(child) {343+ if (child.exitCode !== null) return;344+345+ if (process.platform === "win32") {346+ try {347+ execFileSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });348+ } catch {349+ child.kill("SIGTERM");350+ }351+ return;352+ }353+354+ try {355+ process.kill(-child.pid, "SIGTERM");356+ } catch {
- @@ -48,3 +52,4 @@4852 run: |4953 test -f apps/desktop/dist-electron/preload.js5054 grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js55+apps/desktop/scripts/dev-electron.mjs line 53OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -15,0 +33,21 @@33+ { path: "../server/dist/index.mjs", requireFresh: false },34+ ];35+36+ return new Promise((resolve, reject) => {37+ const tick = () => {38+ const missing = [];39+ const stale = [];40+41+ for (const bundleFile of bundleFiles) {42+ if (!fs.existsSync(bundleFile.path)) {43+ missing.push(bundleFile.path);44+ continue;45+ }46+ if (!bundleFile.requireFresh) {47+ continue;48+ }49+ try {50+ const stat = fs.statSync(bundleFile.path);51+ if (stat.mtimeMs < startedAt) {52+ stale.push(bundleFile.path);53+ }
- @@ -0,0 +157,21 @@157+ .toSorted((a, b) => b[1] - a[1])158+ .slice(0, 10)159+ .map(([name, count]) => ({ name, count }));160+161+ const topDurationEvents = [...durationByName.entries()]162+ .map(([name, value]) => ({163+ name,164+ count: value.count,165+ totalMs: round(toMs(value.dur), 2),166+ avgMs: round(toMs(value.dur / value.count)),167+ maxMs: round(toMs(value.max)),168+ }))169+ .toSorted((a, b) => b.totalMs - a.totalMs)170+ .slice(0, 10);171+172+ const heap = (() => {173+ if (updateCounters.length === 0) return null;174+ const first = updateCounters[0];175+ const last = updateCounters[updateCounters.length - 1];176+ const min = Math.min(...updateCounters);177+ const max = Math.max(...updateCounters);
- @@ -0,0 +773,21 @@773+ "Terminal split did not appear.",774+ 15_000,775+ );776+ splitCount += 1;777+ }778+779+ const commandMarker = `perfterm${Date.now().toString(36)}`;780+ const markerFilePath = path.join(os.tmpdir(), `t3code-desktop-perf-${commandMarker}`);781+ try {782+ fs.rmSync(markerFilePath, { force: true });783+ } catch {784+ // best effort cleanup for stale marker file785+ }786+787+ await focusActiveTerminalInput(window);788+ await sendTextInput(window.webContents, `echo ${commandMarker}`);789+ await pressEnter(window.webContents);790+ await delay(120);791+792+ await focusActiveTerminalInput(window);793+ await sendTextInput(window.webContents, `touch ${markerFilePath}`);
- apps/desktop/scripts/dev-electron.mjs line 28OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -15,0 +8,21 @@8+async function canConnect(host, probePort, timeoutMs = 1_000) {9+ return new Promise((resolve) => {10+ const socket = new net.Socket();11+ let settled = false;12+13+ const finish = (value) => {14+ if (settled) return;15+ settled = true;16+ socket.destroy();17+ resolve(value);18+ };19+20+ socket.setTimeout(timeoutMs);21+ socket.once("connect", () => finish(true));22+ socket.once("timeout", () => finish(false));23+ socket.once("error", () => finish(false));24+ socket.connect(probePort, host);25+ });26+}27+28+const f = (path) => path.join(import.meta.dirname, "..", path);
- apps/desktop/scripts/dev-electron.mjs line 28Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -15,0 +8,21 @@8+9+async function canConnect(host, probePort, timeoutMs = 1_000) {10+ return new Promise((resolve) => {11+ const socket = new net.Socket();12+ let settled = false;13+14+ const finish = (value) => {15+ if (settled) return;16+ settled = true;17+ socket.destroy();18+ resolve(value);19+ };20+21+ socket.setTimeout(timeoutMs);22+ socket.once("connect", () => finish(true));23+ socket.once("timeout", () => finish(false));24+ socket.once("error", () => finish(false));25+ socket.connect(probePort, host);26+ });27+}28+
- @@ -0,0 +218,21 @@218+ ? stat.threadId.slice(0, 15)219+ : "n/a";220+ const firstRenderMs =221+ typeof stat.firstRenderMs === "number"222+ ? stat.firstRenderMs223+ : typeof stat.renderMs === "number"224+ ? stat.renderMs225+ : "n/a";226+ const followUpRenderMs =227+ typeof stat.followUpRenderMs === "number" ? stat.followUpRenderMs : "n/a";228+ const followUpMinMs = typeof stat.followUpMinMs === "number" ? stat.followUpMinMs : "n/a";229+ const followUpMaxMs = typeof stat.followUpMaxMs === "number" ? stat.followUpMaxMs : "n/a";230+ const followUpSampleCount =231+ typeof stat.followUpSampleCount === "number" ? stat.followUpSampleCount : "n/a";232+ const deltaMs = typeof stat.deltaMs === "number" ? stat.deltaMs : "n/a";233+ const deltaPct = typeof stat.deltaPct === "number" ? stat.deltaPct : "n/a";234+ const followUpRange =235+ typeof followUpMinMs === "number" && typeof followUpMaxMs === "number"236+ ? `${followUpMinMs}-${followUpMaxMs} (${followUpSampleCount}x)`237+ : "n/a";238+ return `| ${pad(threadShort, THREAD_COL_WIDTH)} | ${pad(titleShort, TITLE_COL_WIDTH)} | ${stat.messageCount} | ${firstRenderMs} | ${followUpRenderMs} | ${followUpRange} | ${deltaMs} | ${deltaPct}% |`;@@ -10,6 +7,15 @@10- `tcp:${port}`,11- "file:dist-electron/main.js",12- "file:dist-electron/preload.js",13- "file:../server/dist/index.mjs",14- ],15-});7+const STARTUP_TIMEOUT_MS = Number(process.env.T3CODE_ELECTRON_STARTUP_TIMEOUT_MS ?? 120_000);8+9+async function canConnect(host, probePort, timeoutMs = 1_000) {10+ return new Promise((resolve) => {11+ const socket = new net.Socket();12+ let settled = false;13+14+ const finish = (value) => {15+ if (settled) return;16+ settled = true;17+ socket.destroy();18+ resolve(value);19+ };20+21+ socket.setTimeout(timeoutMs);
- @@ -0,0 +125,21 @@125+ return normalized;126+}127+128+function resolvePositiveIntegerEnv({ name, value, fallback }) {129+ const resolved = parseNumericEnv({130+ name,131+ value,132+ predicate: (parsed) => parsed > 0,133+ expectation: "positive number",134+ fallback,135+ });136+ if (!resolved) {137+ return fallback;138+ }139+ const normalized = Math.trunc(resolved.parsed);140+ if (normalized !== resolved.parsed) {141+ console.warn(142+ `[desktop-perf] non-integer ${name}="${resolved.raw}" truncated to ${normalized} for consistency`,143+ );144+ }145+ return normalized;@@ -15,0 +71,21 @@71+ label: "desktop/preload.cjs",72+ },73+ {74+ path: f("../server/dist/index.mjs"),75+ label: "server/index.mjs",76+ },77+ ];78+ let lastProgressLogAt = 0;79+80+ return new Promise((resolve, reject) => {81+ const tick = () => {82+ const states = bundleFiles.map(inspectBundleFile);83+ const missing = states.filter((state) => state.status === "missing");84+85+ if (missing.length === 0) {86+ resolve();87+ return;88+ }89+90+ const elapsedMs = Date.now() - startedAt;91+ if (elapsedMs >= timeoutMs) {@@ -0,0 +577,21 @@577+ const attemptedPath = path.resolve(rawCwd);578+ try {579+ fs.mkdirSync(attemptedPath, { recursive: true });580+ return attemptedPath;581+ } catch {582+ const safeName = (projectName || projectId || `project-${projectIndex + 1}`)583+ .toLowerCase()584+ .replace(/[^a-z0-9._-]+/g, "-")585+ .replace(/^-+|-+$/g, "")586+ .slice(0, 48);587+ const fallbackPath = path.join(588+ os.tmpdir(),589+ "t3code-desktop-perf-seed-projects",590+ `${String(projectIndex + 1).padStart(2, "0")}-${safeName || "project"}`,591+ );592+ fs.mkdirSync(fallbackPath, { recursive: true });593+ return fallbackPath;594+ }595+}596+597+function materializeRuntimeSeed(seedPath, artifactsDir) {
- @@ -70,3 +70,14 @@7070 return undefined;7171 }727273+function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {74+ socket.write(75+ `HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +76+ "Connection: close\r\n" +77+ "Content-Type: text/plain\r\n" +78+ `Content-Length: ${Buffer.byteLength(message)}\r\n` +79+ "\r\n" +80+ message,81+ );82+ socket.destroy();83+}@@ -228,5 +256,4 @@228256 });229257230258 if (isDevelopment) {231- void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);232- window.webContents.openDevTools({ mode: "detach" });259+ const devUrl = new URL(process.env.VITE_DEV_SERVER_URL as string);
- @@ -0,0 +458,21 @@458+ lines.push(`- ${entry.count}x ${entry.name}`);459+ }460+ lines.push("", "### Top Duration Events", "");461+ for (const entry of summary.topDurationEvents) {462+ lines.push(463+ `- ${entry.name}: total=${entry.totalMs}ms, avg=${entry.avgMs}ms, max=${entry.maxMs}ms, count=${entry.count}`,464+ );465+ }466+ lines.push("", "</details>", "");467+468+ return lines.join("\n");469+}470+471+async function waitForDoneFile(donePath, child, timeoutMs) {472+ const startedAt = Date.now();473+ while (Date.now() - startedAt < timeoutMs) {474+ if (fs.existsSync(donePath)) {475+ return JSON.parse(fs.readFileSync(donePath, "utf8"));476+ }477+ if (child.exitCode !== null) {478+ throw new Error(`desktop dev process exited early (code ${child.exitCode})`);
- @@ -1,3 +1,4 @@11 import { spawn } from "node:child_process";2-3-import waitOn from "wait-on";2+import fs from "node:fs";3+import net from "node:net";4+import path from "node:path";
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge closed this
Sign in to join this conversation.



Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
Walkthrough#
Adds end-to-end desktop performance automation: CI workflow steps and npm scripts to run perf traces, an Electron automation module that seeds state and records traces, a Bun/Node trace-runner that parses traces and can post PR summaries, and lightweight web UI perf attributes.
Changes#
.github/workflows/ci.ymlpackage.jsontest:desktop-perfandtest:desktop-perf:postscripts to invoke the trace runner script.apps/desktop/src/main.ts,apps/desktop/src/desktopPerfAutomation.tsT3CODE_DESKTOP_PERF_AUTOMATION/ PERF_AUTOMATION_ENABLED, state-dir env override, integratesrunDesktopPerfAutomation(window)to seed state, control tracing, perform scripted UI interactions, and emit trace/done artifacts; exports the automation function.scripts/desktop-perf-trace.mjsbun dev:desktopwith perf env, prepares synthetic state, streams logs, waits fordone.json, parsestrace.jsoninto aggregates/hotspots, applies thresholds, writessummary.md, and can post results to PRs.apps/web/src/components/ChatView.tsx,apps/web/src/components/Sidebar.tsxdata-perf-*attributes to message list, composer, toggles, model/reasoning items, and thread buttons for instrumentation only (no behavior changes).turbo.jsonT3CODE_DESKTOP_PERF_AUTOMATION,T3CODE_DESKTOP_PERF_TRACE_OUT,T3CODE_DESKTOP_PERF_DONE_OUT.Sequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~60 minutes
🚥 Pre-merge checks | ✅ 3 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (3 passed)
main✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.