Open History to see the last commit
1import { spawn, execFileSync } from "node:child_process";
2import fs from "node:fs";
3import os from "node:os";
4import path from "node:path";
5
6const repoRoot = path.resolve(import.meta.dirname, "..");
7const marker = "<!-- desktop-perf-trace-summary -->";
8const defaultSeedRelativePath = "apps/desktop/scripts/perf-seed.json";
9const defaultPerfProjects = [
10 {
11 id: "perf-project-1",
12 cwd: "/tmp/perf/codething-mvp",
13 name: "codething-mvp",
14 },
15 {
16 id: "perf-project-2",
17 cwd: "/tmp/perf/contracts-bench",
18 name: "contracts-bench",
19 },
20];
21
22function sleep(ms) {
23 return new Promise((resolve) => setTimeout(resolve, ms));
24}
25
26function parseArgs(argv) {
27 let postPr = false;
28 let seedPath = null;
29
30 for (let index = 2; index < argv.length; index += 1) {
31 const arg = argv[index];
32 if (arg === "--post-pr") {
33 postPr = true;
34 continue;
35 }
36 if (arg === "--seed") {
37 const value = argv[index + 1];
38 if (!value || value.startsWith("--")) {
39 throw new Error("--seed requires a file path");
40 }
41 seedPath = value;
42 index += 1;
43 continue;
44 }
45 if (arg.startsWith("--seed=")) {
46 const value = arg.slice("--seed=".length).trim();
47 if (value.length === 0) {
48 throw new Error("--seed= requires a non-empty path");
49 }
50 seedPath = value;
51 continue;
52 }
53 throw new Error(`Unknown argument: ${arg}`);
54 }
55
56 return {
57 postPr,
58 seedPath,
59 };
60}
61
62function toMs(us) {
63 return us / 1000;
64}
65
66function round(n, digits = 3) {
67 return Number(n.toFixed(digits));
68}
69
70function mb(bytes) {
71 return bytes / (1024 * 1024);
72}
73
74function parseNumericEnv({ name, value, predicate, expectation, fallback }) {
75 if (typeof value !== "string") {
76 return null;
77 }
78 const raw = value.trim();
79 if (raw.length === 0) {
80 console.warn(
81 `[desktop-perf] invalid ${name}="${value}" (expected ${expectation}); using ${fallback}`,
82 );
83 return null;
84 }
85 const parsed = Number(raw);
86 if (Number.isFinite(parsed) && predicate(parsed)) {
87 return {
88 parsed,
89 raw,
90 };
91 }
92 console.warn(
93 `[desktop-perf] invalid ${name}="${value}" (expected ${expectation}); using ${fallback}`,
94 );
95 return null;
96}
97
98function resolveNonNegativeNumberEnv({ name, value, fallback }) {
99 const resolved = parseNumericEnv({
100 name,
101 value,
102 predicate: (parsed) => parsed >= 0,
103 expectation: "non-negative number",
104 fallback,
105 });
106 return resolved?.parsed ?? fallback;
107}
108
109function resolveNonNegativeIntegerEnv({ name, value, fallback }) {
110 const resolved = parseNumericEnv({
111 name,
112 value,
113 predicate: (parsed) => parsed >= 0,
114 expectation: "non-negative number",
115 fallback,
116 });
117 if (!resolved) {
118 return fallback;
119 }
120 const normalized = Math.trunc(resolved.parsed);
121 if (normalized !== resolved.parsed) {
122 console.warn(
123 `[desktop-perf] non-integer ${name}="${resolved.raw}" truncated to ${normalized} for consistency`,
124 );
125 }
126 return normalized;
127}
128
129function resolvePositiveIntegerEnv({ name, value, fallback }) {
130 const resolved = parseNumericEnv({
131 name,
132 value,
133 predicate: (parsed) => parsed > 0,
134 expectation: "positive number",
135 fallback,
136 });
137 if (!resolved) {
138 return fallback;
139 }
140 const normalized = Math.trunc(resolved.parsed);
141 if (normalized !== resolved.parsed) {
142 console.warn(
143 `[desktop-perf] non-integer ${name}="${resolved.raw}" truncated to ${normalized} for consistency`,
144 );
145 }
146 return normalized;
147}
148
149function summarizeTrace(tracePath) {
150 const payload = JSON.parse(fs.readFileSync(tracePath, "utf8"));
151 const events = payload.traceEvents;
152
153 const durationByName = new Map();
154 const dispatchRows = [];
155 const functionRows = [];
156 const userTiming = new Map();
157 const updateCounters = [];
158
159 for (const event of events) {
160 if (event.name === "UpdateCounters" && event.args?.data) {
161 const heap = event.args.data.jsHeapSizeUsed;
162 if (typeof heap === "number") {
163 updateCounters.push(heap);
164 }
165 }
166
167 if (event.cat === "blink.user_timing" && typeof event.name === "string") {
168 userTiming.set(event.name, (userTiming.get(event.name) ?? 0) + 1);
169 }
170
171 if (event.ph !== "X" || typeof event.dur !== "number" || typeof event.name !== "string") {
172 continue;
173 }
174
175 const byName = durationByName.get(event.name) ?? { count: 0, dur: 0, max: 0 };
176 byName.count += 1;
177 byName.dur += event.dur;
178 byName.max = Math.max(byName.max, event.dur);
179 durationByName.set(event.name, byName);
180
181 if (event.name === "EventDispatch") {
182 const type = event.args?.data?.type ?? "";
183 dispatchRows.push({ type, dur: event.dur });
184 }
185
186 if (event.name === "FunctionCall") {
187 const functionName = event.args?.data?.functionName ?? "(unknown)";
188 functionRows.push({ functionName, dur: event.dur });
189 }
190 }
191
192 const aggregateDispatchType = (type) => {
193 const rows = dispatchRows.filter((row) => row.type === type);
194 if (rows.length === 0) {
195 return {
196 count: 0,
197 totalMs: 0,
198 avgMs: 0,
199 maxMs: 0,
200 };
201 }
202 const totalDur = rows.reduce((sum, row) => sum + row.dur, 0);
203 const maxDur = rows.reduce((max, row) => Math.max(max, row.dur), 0);
204 return {
205 count: rows.length,
206 totalMs: round(toMs(totalDur)),
207 avgMs: round(toMs(totalDur / rows.length)),
208 maxMs: round(toMs(maxDur)),
209 };
210 };
211
212 const aggregateFunction = (name) => {
213 const rows = functionRows.filter((row) => row.functionName === name);
214 if (rows.length === 0) {
215 return {
216 count: 0,
217 totalMs: 0,
218 avgMs: 0,
219 maxMs: 0,
220 };
221 }
222 const totalDur = rows.reduce((sum, row) => sum + row.dur, 0);
223 const maxDur = rows.reduce((max, row) => Math.max(max, row.dur), 0);
224 return {
225 count: rows.length,
226 totalMs: round(toMs(totalDur)),
227 avgMs: round(toMs(totalDur / rows.length)),
228 maxMs: round(toMs(maxDur)),
229 };
230 };
231
232 const topUserTiming = [...userTiming.entries()]
233 .toSorted((a, b) => b[1] - a[1])
234 .slice(0, 10)
235 .map(([name, count]) => ({ name, count }));
236
237 const topDurationEvents = [...durationByName.entries()]
238 .map(([name, value]) => ({
239 name,
240 count: value.count,
241 totalMs: round(toMs(value.dur), 2),
242 avgMs: round(toMs(value.dur / value.count)),
243 maxMs: round(toMs(value.max)),
244 }))
245 .toSorted((a, b) => b.totalMs - a.totalMs)
246 .slice(0, 10);
247
248 const heap = (() => {
249 if (updateCounters.length === 0) return null;
250 const first = updateCounters[0];
251 const last = updateCounters[updateCounters.length - 1];
252 const min = Math.min(...updateCounters);
253 const max = Math.max(...updateCounters);
254 return {
255 firstMb: round(mb(first), 1),
256 lastMb: round(mb(last), 1),
257 minMb: round(mb(min), 1),
258 maxMb: round(mb(max), 1),
259 deltaMb: round(mb(last - first), 1),
260 };
261 })();
262
263 const longDispatchCount = dispatchRows.filter((row) => row.dur >= 50_000).length;
264
265 return {
266 keypress: aggregateDispatchType("keypress"),
267 textInput: aggregateDispatchType("textInput"),
268 input: aggregateDispatchType("input"),
269 keydown: aggregateDispatchType("keydown"),
270 dispatchDiscreteEvent: aggregateFunction("dispatchDiscreteEvent"),
271 performWorkUntilDeadline: aggregateFunction("performWorkUntilDeadline"),
272 longDispatchCount,
273 heap,
274 topUserTiming,
275 topDurationEvents,
276 };
277}
278
279const pad = (value, width) => String(value).padEnd(width, " ");
280
281function evaluateThresholds(summary, thresholds) {
282 const checks = [
283 {
284 label: "keypress avg",
285 actual: summary.keypress.avgMs,
286 threshold: thresholds.maxKeypressAvgMs,
287 ok: summary.keypress.avgMs <= thresholds.maxKeypressAvgMs,
288 },
289 {
290 label: "keypress max",
291 actual: summary.keypress.maxMs,
292 threshold: thresholds.maxKeypressMaxMs,
293 ok: summary.keypress.maxMs <= thresholds.maxKeypressMaxMs,
294 },
295 {
296 label: "long EventDispatch spikes",
297 actual: summary.longDispatchCount,
298 threshold: thresholds.maxLongDispatchCount,
299 ok: summary.longDispatchCount <= thresholds.maxLongDispatchCount,
300 },
301 ];
302
303 const failures = checks
304 .filter((check) => !check.ok)
305 .map((check) => `${check.label} ${check.actual} exceeds ${check.threshold}`);
306
307 return {
308 checks,
309 failures,
310 passed: failures.length === 0,
311 };
312}
313
314function createMarkdownSummary({ tracePath, donePayload, summary, thresholds, thresholdCheck }) {
315 const THREAD_COL_WIDTH = 8;
316 const TITLE_COL_WIDTH = 15;
317 const largeThreadRenderStats = Array.isArray(donePayload.interactions?.largeThreadRenderStats)
318 ? donePayload.interactions.largeThreadRenderStats
319 : [];
320 const formatThreadRenderRow = (stat) => {
321 const threadShort =
322 typeof stat.threadId === "string" ? stat.threadId.slice(0, THREAD_COL_WIDTH) : "n/a";
323 const titleShort =
324 typeof stat.threadTitleShort === "string"
325 ? stat.threadTitleShort
326 : typeof stat.threadId === "string"
327 ? stat.threadId.slice(0, 15)
328 : "n/a";
329 const firstRenderMs =
330 typeof stat.firstRenderMs === "number"
331 ? stat.firstRenderMs
332 : typeof stat.renderMs === "number"
333 ? stat.renderMs
334 : "n/a";
335 const followUpRenderMs =
336 typeof stat.followUpRenderMs === "number" ? stat.followUpRenderMs : "n/a";
337 const followUpMinMs = typeof stat.followUpMinMs === "number" ? stat.followUpMinMs : "n/a";
338 const followUpMaxMs = typeof stat.followUpMaxMs === "number" ? stat.followUpMaxMs : "n/a";
339 const followUpSampleCount =
340 typeof stat.followUpSampleCount === "number" ? stat.followUpSampleCount : "n/a";
341 const deltaMs = typeof stat.deltaMs === "number" ? stat.deltaMs : "n/a";
342 const deltaPct = typeof stat.deltaPct === "number" ? stat.deltaPct : "n/a";
343 const followUpRange =
344 typeof followUpMinMs === "number" && typeof followUpMaxMs === "number"
345 ? `${followUpMinMs}-${followUpMaxMs} (${followUpSampleCount}x)`
346 : "n/a";
347 return `| ${pad(threadShort, THREAD_COL_WIDTH)} | ${pad(titleShort, TITLE_COL_WIDTH)} | ${stat.messageCount} | ${firstRenderMs} | ${followUpRenderMs} | ${followUpRange} | ${deltaMs} | ${deltaPct}% |`;
348 };
349 const benchmarkThreadIds = Array.isArray(donePayload.interactions?.benchmarkThreadIds)
350 ? donePayload.interactions.benchmarkThreadIds
351 : [];
352 const seedSource =
353 donePayload.seed?.source === "file"
354 ? `file (\`${donePayload.seed?.path ?? "unknown"}\`)`
355 : (donePayload.seed?.source ?? "generated");
356 const topDurationHead = summary.topDurationEvents.slice(0, 3);
357 const topDurationSummary =
358 topDurationHead.length === 0
359 ? "none"
360 : topDurationHead.map((entry) => `${entry.name} (${entry.totalMs}ms total)`).join(", ");
361 const actionLines = thresholdCheck.passed
362 ? [
363 "- Action: no threshold regressions detected in this run.",
364 "- Follow-up: keep watching top duration events for drift in future traces.",
365 ]
366 : [
367 "- Action: threshold regression detected; profile and optimize the failing path(s) before merge.",
368 ...thresholdCheck.failures.map((failure) => `- Failing metric: ${failure}`),
369 ];
370 const lines = [
371 marker,
372 "## Desktop Dev Perf Trace",
373 "",
374 `- Status: ${thresholdCheck.passed ? "PASS" : "FAIL"}`,
375 `- Thresholds: keypress avg ${summary.keypress.avgMs}/${thresholds.maxKeypressAvgMs}ms, keypress max ${summary.keypress.maxMs}/${thresholds.maxKeypressMaxMs}ms, long dispatch spikes ${summary.longDispatchCount}/${thresholds.maxLongDispatchCount}`,
376 `- Coverage: seed=${seedSource}; projects=${donePayload.seed?.projectCount ?? "n/a"}; threads=${donePayload.seed?.threadCount ?? "n/a"}; benchmark threads exercised=${benchmarkThreadIds.length}`,
377 `- Interaction volume: thread clicks=${donePayload.interactions?.threadClicks ?? "n/a"}, typed chars=${donePayload.interactions?.typedChars ?? "n/a"}`,
378 `- Top hotspots: ${topDurationSummary}`,
379 "",
380 ...actionLines,
381 "",
382 "<details>",
383 "<summary>Detailed trace metrics and diagnostics</summary>",
384 "",
385 "### Run Metadata",
386 "",
387 `- Command: \`bun dev:desktop\``,
388 `- Trace: \`${tracePath}\``,
389 `- Started: ${donePayload.startedAt ?? "n/a"}`,
390 `- Completed: ${donePayload.completedAt ?? "n/a"}`,
391 `- Duration: ${donePayload.durationMs ?? "n/a"} ms`,
392 "",
393 "### Interaction Run",
394 "",
395 `- Thread clicks: ${donePayload.interactions?.threadClicks ?? "n/a"}`,
396 `- Typed chars: ${donePayload.interactions?.typedChars ?? "n/a"}`,
397 `- Benchmark thread ids exercised: ${benchmarkThreadIds.length > 0 ? benchmarkThreadIds.join(", ") : "none"}`,
398 `- Model selected: ${donePayload.interactions?.selectedModel ?? "n/a"}`,
399 `- Terminal opened by shortcut: ${donePayload.interactions?.terminal?.openedByShortcut ?? "n/a"}`,
400 `- Terminal shortcut modifier: ${donePayload.interactions?.terminal?.modifierUsed ?? "n/a"}`,
401 `- Terminal splits: ${donePayload.interactions?.terminal?.splitCount ?? "n/a"}`,
402 `- Terminal command executed: ${donePayload.interactions?.terminal?.commandFileTouched ?? "n/a"}`,
403 `- Terminal output observed: ${donePayload.interactions?.terminal?.commandEchoObserved ?? "n/a"}`,
404 `- Terminal marker: ${donePayload.interactions?.terminal?.commandMarker ?? "n/a"}`,
405 `- Terminal interactions enabled: ${donePayload.config?.runTerminalInteractions ?? "n/a"}`,
406 `- Optional renderer interactions enabled: ${donePayload.config?.runOptionalRendererInteractions ?? "n/a"}`,
407 `- Benchmark sweep enabled: ${donePayload.config?.runBenchmarkThreadSweep ?? "n/a"}`,
408 `- Benchmark follow-up pass count: ${donePayload.config?.benchmarkFollowUpPassCount ?? "n/a"}`,
409 "",
410 "### Threshold Config",
411 "",
412 `- keypress avg max: ${thresholds.maxKeypressAvgMs}ms`,
413 `- keypress max max: ${thresholds.maxKeypressMaxMs}ms`,
414 `- long EventDispatch spike cap: ${thresholds.maxLongDispatchCount}`,
415 "",
416 "### Benchmark Thread Render",
417 "",
418 "| Thread | Title (15) | Messages | First Nav (ms) | Follow-up Median (ms) | Follow-up Range | Delta (ms) | Delta (%) |",
419 "| --- | --- | ---: | ---: | ---: | --- | ---: | ---: |",
420 ...(largeThreadRenderStats.length > 0
421 ? largeThreadRenderStats.map((stat) => formatThreadRenderRow(stat))
422 : ["| n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a |"]),
423 "",
424 "### Input Event Metrics",
425 "",
426 "| Event | Count | Avg (ms) | Max (ms) | Total (ms) |",
427 "| --- | ---: | ---: | ---: | ---: |",
428 `| keypress | ${summary.keypress.count} | ${summary.keypress.avgMs} | ${summary.keypress.maxMs} | ${summary.keypress.totalMs} |`,
429 `| textInput | ${summary.textInput.count} | ${summary.textInput.avgMs} | ${summary.textInput.maxMs} | ${summary.textInput.totalMs} |`,
430 `| input | ${summary.input.count} | ${summary.input.avgMs} | ${summary.input.maxMs} | ${summary.input.totalMs} |`,
431 `| keydown | ${summary.keydown.count} | ${summary.keydown.avgMs} | ${summary.keydown.maxMs} | ${summary.keydown.totalMs} |`,
432 "",
433 "### Scheduler/Event Hotspots",
434 "",
435 `- dispatchDiscreteEvent: ${summary.dispatchDiscreteEvent.totalMs}ms total (${summary.dispatchDiscreteEvent.count} calls)`,
436 `- performWorkUntilDeadline: ${summary.performWorkUntilDeadline.totalMs}ms total (${summary.performWorkUntilDeadline.count} calls)`,
437 `- EventDispatch spikes >= 50ms: ${summary.longDispatchCount}`,
438 "",
439 "### Threshold Check",
440 "",
441 ...thresholdCheck.checks.map(
442 (check) =>
443 `- ${check.label} <= ${check.threshold}: ${check.ok ? "pass" : `fail (actual ${check.actual})`}`,
444 ),
445 "",
446 ];
447
448 if (summary.heap) {
449 lines.push("### Heap Counters", "");
450 lines.push(
451 `- 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`,
452 "",
453 );
454 }
455
456 lines.push("### Top User Timing Marks", "");
457 for (const entry of summary.topUserTiming) {
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
471async 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})`);
479 }
480 // oxlint-disable-next-line no-await-in-loop
481 await sleep(500);
482 }
483 throw new Error(`Timed out waiting for done marker at ${donePath}`);
484}
485
486function tailLogText(logChunks, lineCount = 120) {
487 const lines = logChunks.join("").split(/\r?\n/);
488 return lines.slice(-lineCount).join("\n").trim();
489}
490
491function inferDesktopPerfTimeoutHint(logChunks) {
492 const joined = logChunks.join("");
493 const lowered = joined.toLowerCase();
494
495 if (lowered.includes("waiting for bundles") && lowered.includes("outdated:")) {
496 return "Desktop bundles were present but older than desktop source files; dev bundler did not refresh outputs in time.";
497 }
498 if (lowered.includes("waiting for bundles") && lowered.includes("stale:")) {
499 return "Desktop bundles were detected as stale by startup freshness checks.";
500 }
501 if (lowered.includes("error while loading shared libraries")) {
502 return "Electron failed to start due missing Linux shared libraries.";
503 }
504 if (lowered.includes("setuid_sandbox_host.cc") || lowered.includes("chrome-sandbox")) {
505 return "Electron sandbox setup failed on Linux CI (setuid sandbox helper).";
506 }
507 if (lowered.includes("no usable sandbox")) {
508 return "Electron sandbox failed to initialize in CI.";
509 }
510 if (lowered.includes("port is already in use")) {
511 return "Dev server port collision prevented Electron from loading the renderer.";
512 }
513 if (!joined.includes("[desktop-perf]")) {
514 return "Desktop perf automation never started; Electron likely did not boot successfully.";
515 }
516 if (joined.includes("[desktop-perf]") && !joined.includes("[desktop-perf] trace recorded")) {
517 return "Desktop perf automation started but did not complete trace recording.";
518 }
519
520 return "Desktop perf automation timed out before writing the done marker.";
521}
522
523async function terminateProcessTree(child) {
524 if (child.exitCode !== null) return;
525
526 if (process.platform === "win32") {
527 try {
528 execFileSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
529 } catch {
530 child.kill("SIGTERM");
531 }
532 return;
533 }
534
535 try {
536 process.kill(-child.pid, "SIGTERM");
537 } catch {
538 child.kill("SIGTERM");
539 }
540
541 await sleep(1_500);
542 if (child.exitCode === null) {
543 try {
544 process.kill(-child.pid, "SIGKILL");
545 } catch {
546 child.kill("SIGKILL");
547 }
548 }
549}
550
551function detectPrNumber() {
552 const githubRef = process.env.GITHUB_REF ?? "";
553 const match = githubRef.match(/refs\/pull\/(\d+)\//);
554 if (match?.[1]) {
555 return match[1];
556 }
557
558 return execFileSync("gh", ["pr", "view", "--json", "number", "--jq", ".number"], {
559 cwd: repoRoot,
560 encoding: "utf8",
561 }).trim();
562}
563
564function postSummaryToPr(summaryPath) {
565 const prNumber = detectPrNumber();
566 execFileSync(
567 "gh",
568 ["pr", "comment", prNumber, "--body-file", summaryPath, "--edit-last", "--create-if-none"],
569 {
570 cwd: repoRoot,
571 stdio: "inherit",
572 },
573 );
574}
575
576function prepareDesktopPerfState(stateDir, perfProjects = defaultPerfProjects) {
577 fs.mkdirSync(stateDir, { recursive: true });
578
579 for (const project of perfProjects) {
580 try {
581 fs.mkdirSync(project.cwd, { recursive: true });
582 } catch {
583 // Some seeded paths may point to unavailable locations in CI; registry entries still work.
584 }
585 }
586
587 const now = new Date().toISOString();
588 fs.writeFileSync(
589 path.join(stateDir, "projects.json"),
590 JSON.stringify(
591 {
592 version: 1,
593 projects: perfProjects.map((project) => ({
594 id: project.id,
595 cwd: project.cwd,
596 name: project.name,
597 createdAt: now,
598 updatedAt: now,
599 })),
600 },
601 null,
602 2,
603 ),
604 );
605}
606
607function resolveSeedPath(seedPathArg) {
608 const candidateArg = seedPathArg ?? process.env.T3CODE_DESKTOP_PERF_SEED_PATH ?? "";
609 if (!candidateArg || candidateArg.trim().length === 0) {
610 const resolvedDefault = path.resolve(repoRoot, defaultSeedRelativePath);
611 if (!fs.existsSync(resolvedDefault)) {
612 throw new Error(
613 `Default desktop perf seed file is required but missing: ${resolvedDefault}. Pass --seed to override.`,
614 );
615 }
616 return resolvedDefault;
617 }
618
619 const resolved = path.isAbsolute(candidateArg)
620 ? candidateArg
621 : path.resolve(repoRoot, candidateArg);
622 if (!fs.existsSync(resolved)) {
623 throw new Error(`Seed file not found: ${resolved}`);
624 }
625 return resolved;
626}
627
628function normalizeProjectPathForRuntime(rawCwd, projectName, projectId, projectIndex) {
629 const attemptedPath = path.resolve(rawCwd);
630 try {
631 fs.mkdirSync(attemptedPath, { recursive: true });
632 return attemptedPath;
633 } catch {
634 const safeName = (projectName || projectId || `project-${projectIndex + 1}`)
635 .toLowerCase()
636 .replace(/[^a-z0-9._-]+/g, "-")
637 .replace(/^-+|-+$/g, "")
638 .slice(0, 48);
639 const fallbackPath = path.join(
640 os.tmpdir(),
641 "t3code-desktop-perf-seed-projects",
642 `${String(projectIndex + 1).padStart(2, "0")}-${safeName || "project"}`,
643 );
644 fs.mkdirSync(fallbackPath, { recursive: true });
645 return fallbackPath;
646 }
647}
648
649function materializeRuntimeSeed(seedPath, artifactsDir) {
650 const raw = JSON.parse(fs.readFileSync(seedPath, "utf8"));
651 if (!raw || typeof raw !== "object" || !Array.isArray(raw.projects)) {
652 return { runtimeSeedPath: seedPath, projects: null };
653 }
654
655 const rewrittenProjects = [];
656 let rewroteAnyProject = false;
657 for (let index = 0; index < raw.projects.length; index += 1) {
658 const project = raw.projects[index];
659 if (!project || typeof project !== "object") {
660 rewrittenProjects.push(project);
661 continue;
662 }
663
664 const id = typeof project.id === "string" ? project.id : "";
665 const name = typeof project.name === "string" ? project.name : "";
666 const cwd = typeof project.cwd === "string" ? project.cwd : "";
667 if (id.length === 0 || name.length === 0 || cwd.length === 0) {
668 rewrittenProjects.push(project);
669 continue;
670 }
671
672 const runtimeCwd = normalizeProjectPathForRuntime(cwd, name, id, index);
673 if (runtimeCwd !== cwd) {
674 rewroteAnyProject = true;
675 }
676 rewrittenProjects.push({
677 ...project,
678 cwd: runtimeCwd,
679 });
680 }
681
682 if (!rewroteAnyProject) {
683 const projects = rewrittenProjects
684 .map((project) => {
685 if (!project || typeof project !== "object") return null;
686 const id = typeof project.id === "string" ? project.id : "";
687 const cwd = typeof project.cwd === "string" ? project.cwd : "";
688 const name = typeof project.name === "string" ? project.name : "";
689 if (id.length === 0 || cwd.length === 0 || name.length === 0) return null;
690 return { id, cwd, name };
691 })
692 .filter((project) => project !== null);
693
694 return {
695 runtimeSeedPath: seedPath,
696 projects: projects.length > 0 ? projects : null,
697 };
698 }
699
700 const runtimeSeedPath = path.join(artifactsDir, "perf-seed.runtime.json");
701 fs.writeFileSync(
702 runtimeSeedPath,
703 JSON.stringify(
704 {
705 ...raw,
706 projects: rewrittenProjects,
707 },
708 null,
709 2,
710 ),
711 );
712
713 const projects = rewrittenProjects
714 .map((project) => {
715 if (!project || typeof project !== "object") return null;
716 const id = typeof project.id === "string" ? project.id : "";
717 const cwd = typeof project.cwd === "string" ? project.cwd : "";
718 const name = typeof project.name === "string" ? project.name : "";
719 if (id.length === 0 || cwd.length === 0 || name.length === 0) return null;
720 return { id, cwd, name };
721 })
722 .filter((project) => project !== null);
723
724 return {
725 runtimeSeedPath,
726 projects: projects.length > 0 ? projects : null,
727 };
728}
729
730async function main() {
731 const args = parseArgs(process.argv);
732 const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
733 const artifactsDir = path.join(os.tmpdir(), "t3code-perf-artifacts", `desktop-dev-${timestamp}`);
734 fs.mkdirSync(artifactsDir, { recursive: true });
735
736 const tracePath = path.join(artifactsDir, "trace.json");
737 const donePath = path.join(artifactsDir, "done.json");
738 const summaryPath = path.join(artifactsDir, "summary.md");
739 const logPath = path.join(artifactsDir, "run.log");
740 const stateDir = path.join(artifactsDir, "state");
741 const seedPath = resolveSeedPath(args.seedPath);
742 const materializedSeed = seedPath ? materializeRuntimeSeed(seedPath, artifactsDir) : null;
743 const runtimeSeedPath = materializedSeed?.runtimeSeedPath ?? seedPath;
744 const seedProjects = materializedSeed?.projects ?? null;
745 if (seedPath && runtimeSeedPath && runtimeSeedPath !== seedPath) {
746 console.log(
747 `[desktop-perf] rewrote seed project cwd paths for runtime compatibility: ${runtimeSeedPath}`,
748 );
749 }
750 prepareDesktopPerfState(stateDir, seedProjects ?? defaultPerfProjects);
751
752 const maxKeypressAvgMs = resolveNonNegativeNumberEnv({
753 name: "T3CODE_PERF_MAX_KEYPRESS_AVG_MS",
754 value: process.env.T3CODE_PERF_MAX_KEYPRESS_AVG_MS,
755 fallback: 12,
756 });
757 const maxKeypressMaxMs = resolveNonNegativeNumberEnv({
758 name: "T3CODE_PERF_MAX_KEYPRESS_MAX_MS",
759 value: process.env.T3CODE_PERF_MAX_KEYPRESS_MAX_MS,
760 fallback: 24,
761 });
762 const maxLongDispatchCount = resolveNonNegativeIntegerEnv({
763 name: "T3CODE_PERF_MAX_LONG_DISPATCH_COUNT",
764 value: process.env.T3CODE_PERF_MAX_LONG_DISPATCH_COUNT,
765 fallback: 0,
766 });
767 const timeoutMs = resolvePositiveIntegerEnv({
768 name: "T3CODE_PERF_TIMEOUT_MS",
769 value: process.env.T3CODE_PERF_TIMEOUT_MS,
770 fallback: 420000,
771 });
772 console.log(
773 `[desktop-perf] thresholds: keypressAvg<=${maxKeypressAvgMs}ms, keypressMax<=${maxKeypressMaxMs}ms, longDispatch<=${maxLongDispatchCount}, timeoutMs=${timeoutMs}`,
774 );
775
776 const child = spawn("bun", ["dev:desktop"], {
777 cwd: repoRoot,
778 detached: process.platform !== "win32",
779 env: {
780 ...process.env,
781 T3CODE_DESKTOP_PERF_AUTOMATION: "1",
782 T3CODE_DESKTOP_PERF_TRACE_OUT: tracePath,
783 T3CODE_DESKTOP_PERF_DONE_OUT: donePath,
784 ...(runtimeSeedPath ? { T3CODE_DESKTOP_PERF_SEED_PATH: runtimeSeedPath } : {}),
785 T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP:
786 process.env.T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP ?? "1",
787 T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES:
788 process.env.T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES ?? "1",
789 T3CODE_DEV_INSTANCE: `desktop-perf-${timestamp}`,
790 T3CODE_LOG_WS_EVENTS: "0",
791 T3CODE_STATE_DIR: stateDir,
792 },
793 stdio: ["ignore", "pipe", "pipe"],
794 });
795
796 const logs = [];
797 const appendLog = (chunk) => {
798 const text = chunk.toString();
799 logs.push(text);
800 if (logs.length > 1200) {
801 logs.splice(0, logs.length - 1200);
802 }
803 fs.appendFileSync(logPath, text);
804 process.stdout.write(text);
805 };
806
807 child.stdout.on("data", appendLog);
808 child.stderr.on("data", appendLog);
809
810 let donePayload;
811 try {
812 donePayload = await waitForDoneFile(donePath, child, timeoutMs);
813 } catch (error) {
814 const baseMessage = error instanceof Error ? error.message : String(error);
815 const hint = inferDesktopPerfTimeoutHint(logs);
816 const logTail = tailLogText(logs);
817 throw new Error(
818 [
819 baseMessage,
820 `Hint: ${hint}`,
821 `Artifacts dir: ${artifactsDir}`,
822 `Run log: ${logPath}`,
823 logTail.length > 0 ? `Recent log tail:\n${logTail}` : "Recent log tail: <empty>",
824 ].join("\n"),
825 { cause: error },
826 );
827 } finally {
828 await terminateProcessTree(child);
829 }
830
831 if (!donePayload || donePayload.status !== "ok") {
832 throw new Error(
833 `Desktop perf automation failed. ${donePayload?.error ?? "No completion payload written."}`,
834 );
835 }
836
837 const interactionChecks = [];
838 const threadClicks = Number(donePayload.interactions?.threadClicks ?? 0);
839 const typedChars = Number(donePayload.interactions?.typedChars ?? 0);
840 if (threadClicks <= 0) {
841 interactionChecks.push("thread clicks");
842 }
843 if (typedChars <= 0) {
844 interactionChecks.push("typed chars");
845 }
846 if (interactionChecks.length > 0) {
847 throw new Error(
848 `Desktop perf automation completed without required scripted interactions: ${interactionChecks.join(", ")}`,
849 );
850 }
851
852 const summary = summarizeTrace(tracePath);
853 const thresholdCheck = evaluateThresholds(summary, {
854 maxKeypressAvgMs,
855 maxKeypressMaxMs,
856 maxLongDispatchCount,
857 });
858 const markdown = createMarkdownSummary({
859 tracePath,
860 donePayload,
861 summary,
862 thresholds: {
863 maxKeypressAvgMs,
864 maxKeypressMaxMs,
865 maxLongDispatchCount,
866 },
867 thresholdCheck,
868 });
869 fs.writeFileSync(summaryPath, markdown);
870
871 console.log(`\nPerf summary written to ${summaryPath}\n`);
872 console.log(markdown);
873
874 if (args.postPr) {
875 postSummaryToPr(summaryPath);
876 }
877
878 if (!thresholdCheck.passed) {
879 throw new Error(`Performance thresholds failed:\n- ${thresholdCheck.failures.join("\n- ")}`);
880 }
881}
882
883main().catch((error) => {
884 const message = error instanceof Error ? error.message : String(error);
885 console.error("\nDesktop perf trace test failed:\n" + message);
886 process.exit(1);
887});