Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

desktopPerfAutomation.ts

1,251 lines41.7 KB

1// oxlint-disable no-await-in-loop
2import fs from "node:fs";
3import os from "node:os";
4import path from "node:path";
5​
6import { BrowserWindow, contentTracing, type WebContents } from "electron";
7import {
8 resolveBenchmarkFollowUpPassCount,
9 shouldRunBenchmarkThreadSweep,
10 shouldRunOptionalRendererPerfInteractions,
11 shouldRunTerminalPerfInteractions,
12} from "./perfConfig";
13​
14const PERF_AUTOMATION_ENABLED = process.env.T3CODE_DESKTOP_PERF_AUTOMATION === "1";
15const PERF_TRACE_OUT_PATH = process.env.T3CODE_DESKTOP_PERF_TRACE_OUT?.trim() ?? "";
16const PERF_DONE_OUT_PATH = process.env.T3CODE_DESKTOP_PERF_DONE_OUT?.trim() ?? "";
17const PERF_SEED_PATH = process.env.T3CODE_DESKTOP_PERF_SEED_PATH?.trim() ?? "";
18const RUN_TERMINAL_INTERACTIONS = shouldRunTerminalPerfInteractions({
19 T3CODE_DESKTOP_PERF_RUN_TERMINAL: process.env.T3CODE_DESKTOP_PERF_RUN_TERMINAL,
20 CI: process.env.CI,
21});
22const RUN_OPTIONAL_RENDERER_INTERACTIONS = shouldRunOptionalRendererPerfInteractions({
23 T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: process.env.T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER,
24 CI: process.env.CI,
25});
26const BENCHMARK_FOLLOW_UP_PASS_COUNT = resolveBenchmarkFollowUpPassCount({
27 T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES:
28 process.env.T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES,
29 CI: process.env.CI,
30});
31const RUN_BENCHMARK_THREAD_SWEEP = shouldRunBenchmarkThreadSweep({
32 T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: process.env.T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP,
33 CI: process.env.CI,
34});
35​
36function delay(ms: number): Promise<void> {
37 return new Promise((resolve) => setTimeout(resolve, ms));
39​
40function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
41 return new Promise((resolve, reject) => {
42 const timeout = setTimeout(() => {
43 reject(new Error(`Timed out waiting for ${label} (${timeoutMs}ms).`));
44 }, timeoutMs);
45 timeout.unref();
46​
47 promise.then(
48 (value) => {
49 clearTimeout(timeout);
50 resolve(value);
51 },
52 (error: unknown) => {
53 clearTimeout(timeout);
54 reject(error);
55 },
56 );
57 });
59​
60function waitForDidFinishLoad(
61 webContents: WebContents,
62 options?: { timeoutMs?: number; label?: string },
63): Promise<void> {
64 const timeoutMs = options?.timeoutMs ?? 20_000;
65 const label = options?.label ?? "renderer load";
66​
67 if (!webContents.isLoadingMainFrame()) {
68 const currentUrl = webContents.getURL();
69 if (currentUrl.length === 0 || currentUrl.startsWith("chrome-error://")) {
70 return Promise.reject(
71 new Error(`${label} is not loading and no valid page is currently loaded (${currentUrl}).`),
72 );
73 }
74 return Promise.resolve();
75 }
76​
77 return new Promise((resolve, reject) => {
78 let settled = false;
79 const cleanup = () => {
80 webContents.removeListener("did-finish-load", onLoad);
81 webContents.removeListener("did-fail-load", onFailLoad);
82 clearTimeout(timeout);
83 };
84 const finish = (callback: () => void) => {
85 if (settled) return;
86 settled = true;
87 cleanup();
88 callback();
89 };
90 const onLoad = () => {
91 finish(resolve);
92 };
93 const onFailLoad = (
94 _event: Electron.Event,
95 errorCode: number,
96 errorDescription: string,
97 validatedURL: string,
98 isMainFrame: boolean,
99 ) => {
100 if (!isMainFrame) return;
101 finish(() => {
102 reject(
103 new Error(
104 `${label} failed for ${validatedURL || "(unknown url)"} [${errorCode}] ${errorDescription}`,
105 ),
106 );
107 });
108 };
109 const timeout = setTimeout(() => {
110 finish(() => reject(new Error(`Timed out waiting for ${label} (${timeoutMs}ms).`)));
111 }, timeoutMs);
112 timeout.unref();
113​
114 webContents.on("did-fail-load", onFailLoad);
115 webContents.once("did-finish-load", onLoad);
116 });
118​
119interface PerfPersistedMessage {
120 id: string;
121 role: "user" | "assistant";
122 text: string;
123 createdAt: string;
124 streaming: false;
126​
127interface PerfPersistedThread {
128 id: string;
129 projectId: string;
130 title: string;
131 model: string;
132 terminalOpen: false;
133 messages: PerfPersistedMessage[];
134 createdAt: string;
135 lastVisitedAt: string;
137​
138interface PerfPersistedProject {
139 id: string;
140 name: string;
141 cwd: string;
142 model: string;
143 expanded: true;
145​
146interface PerfPersistedState {
147 version: 7;
148 runtimeMode: "approval-required";
149 projects: PerfPersistedProject[];
150 threads: PerfPersistedThread[];
151 activeThreadId: string | null;
153​
154const LARGE_THREAD_EXCHANGE_COUNT = 120;
155const BENCHMARK_THREAD_COUNT = 2;
156const BENCHMARK_TITLE_PREVIEW_LENGTH = 15;
157​
158interface PerfThreadStat {
159 id: string;
160 title: string;
161 messageCount: number;
163​
164interface ResolvedPerfSeed {
165 source: string;
166 resolvedPath: string | null;
167 state: unknown;
168 projectCount: number;
169 threadCount: number;
170 benchmarkThreads: PerfThreadStat[];
172​
173interface PerfLargeThreadRenderStat {
174 threadId: string;
175 messageCount: number;
176 firstRenderMs: number;
177 followUpRenderMs: number;
178 followUpMinMs: number;
179 followUpMaxMs: number;
180 followUpSampleCount: number;
181 deltaMs: number;
182 deltaPct: number;
184​
185interface RendererPerfInteractions {
186 threadClicks: number;
187 typedChars: number;
188 selectedModel: string | null;
189 largeThreadRenderStats: PerfLargeThreadRenderStat[];
190 benchmarkThreadIds: string[];
192​
193interface TerminalPerfInteractions {
194 openedByShortcut: boolean;
195 splitCount: number;
196 commandMarker: string;
197 commandEchoObserved: boolean;
198 commandFileTouched: boolean;
199 modifierUsed: "meta" | "control";
201​
202function isRecord(value: unknown): value is Record<string, unknown> {
203 return typeof value === "object" && value !== null;
205​
206function collectThreadStats(state: unknown): PerfThreadStat[] {
207 if (!isRecord(state)) return [];
208 const threads = state.threads;
209 if (!Array.isArray(threads)) return [];
210​
211 const stats: PerfThreadStat[] = [];
212 for (const thread of threads) {
213 if (!isRecord(thread)) continue;
214 const id = typeof thread.id === "string" ? thread.id : "";
215 if (id.length === 0) continue;
216 const title = typeof thread.title === "string" ? thread.title : "";
217 const messages = thread.messages;
218 const messageCount = Array.isArray(messages) ? messages.length : 0;
219 stats.push({ id, title, messageCount });
220 }
221​
222 return stats;
224​
225function pickBenchmarkThreads(stats: PerfThreadStat[], benchmarkAll: boolean): PerfThreadStat[] {
226 const sorted = stats.toSorted((a, b) => b.messageCount - a.messageCount);
227 return benchmarkAll ? sorted : sorted.slice(0, BENCHMARK_THREAD_COUNT);
229​
230function toTitlePreview(title: string): string {
231 return title.slice(0, BENCHMARK_TITLE_PREVIEW_LENGTH);
233​
234function resolvePerfSeed(): ResolvedPerfSeed {
235 if (PERF_SEED_PATH.length === 0) {
236 const generated = buildPerfSeedState();
237 const stats = collectThreadStats(generated);
238 return {
239 source: "generated",
240 resolvedPath: null,
241 state: generated,
242 projectCount: generated.projects.length,
243 threadCount: generated.threads.length,
244 benchmarkThreads: pickBenchmarkThreads(stats, false),
245 };
246 }
247​
248 const resolvedPath = path.isAbsolute(PERF_SEED_PATH)
249 ? PERF_SEED_PATH
250 : path.resolve(process.cwd(), PERF_SEED_PATH);
251​
252 if (!fs.existsSync(resolvedPath)) {
253 throw new Error(`Perf seed file not found: ${resolvedPath}`);
254 }
255​
256 let parsed: unknown;
257 try {
258 parsed = JSON.parse(fs.readFileSync(resolvedPath, "utf8"));
259 } catch (error) {
260 const message = error instanceof Error ? error.message : String(error);
261 throw new Error(`Failed to parse perf seed JSON at ${resolvedPath}: ${message}`, {
262 cause: error,
263 });
264 }
265​
266 if (!isRecord(parsed)) {
267 throw new Error(`Perf seed must be a JSON object: ${resolvedPath}`);
268 }
269 if (!Array.isArray(parsed.projects)) {
270 throw new Error(`Perf seed is missing "projects" array: ${resolvedPath}`);
271 }
272 if (!Array.isArray(parsed.threads)) {
273 throw new Error(`Perf seed is missing "threads" array: ${resolvedPath}`);
274 }
275​
276 const stats = collectThreadStats(parsed);
277 return {
278 source: "file",
279 resolvedPath,
280 state: parsed,
281 projectCount: parsed.projects.length,
282 threadCount: parsed.threads.length,
283 benchmarkThreads: pickBenchmarkThreads(stats, false),
284 };
286​
287function buildLargeThreadMessage(
288 projectName: string,
289 exchangeIndex: number,
290 role: "user" | "assistant",
291): string {
292 if (role === "user") {
293 return [
294 `Large-thread perf scenario ${exchangeIndex + 1} for ${projectName}.`,
295 "Please audit render cost while scrolling and switching among heavy histories.",
296 "Include hotspots in markdown rendering, timeline grouping, and message list virtualization candidates.",
297 "Track regressions across interaction loops and report any long-task spikes.",
298 ].join("\n");
299 }
300​
301 return [
302 `### Perf analysis batch ${exchangeIndex + 1}`,
303 "",
304 "- Checked keypress/input dispatch cost and scheduler churn.",
305 "- Compared component update cadence before/after thread switch.",
306 "- Captured timeline and branch/tool state snapshots.",
307 "",
308 "```txt",
309 `project=${projectName}`,
310 `batch=${exchangeIndex + 1}`,
311 "status=stable",
312 "focus=render-throughput",
313 "```",
314 "",
315 "Observed stable behavior under bursty UI events; continue profiling for long-thread rendering regressions.",
316 ].join("\n");
318​
319function buildLargePerfThread(project: PerfPersistedProject, now: number): PerfPersistedThread {
320 const threadId = `${project.id}-thread-large`;
321 const createdAt = new Date(now - 1_500_000).toISOString();
322 const messages: PerfPersistedMessage[] = [];
323 for (let exchangeIndex = 0; exchangeIndex < LARGE_THREAD_EXCHANGE_COUNT; exchangeIndex += 1) {
324 const offsetMs = (LARGE_THREAD_EXCHANGE_COUNT - exchangeIndex) * 11_000;
325 messages.push({
326 id: `${threadId}-user-${exchangeIndex + 1}`,
327 role: "user",
328 text: buildLargeThreadMessage(project.name, exchangeIndex, "user"),
329 createdAt: new Date(now - offsetMs - 2_000).toISOString(),
330 streaming: false,
331 });
332 messages.push({
333 id: `${threadId}-assistant-${exchangeIndex + 1}`,
334 role: "assistant",
335 text: buildLargeThreadMessage(project.name, exchangeIndex, "assistant"),
336 createdAt: new Date(now - offsetMs).toISOString(),
337 streaming: false,
338 });
339 }
340​
341 return {
342 id: threadId,
343 projectId: project.id,
344 title: `${project.name} perf large thread`,
345 model: "gpt-5-codex",
346 terminalOpen: false,
347 messages,
348 createdAt,
349 lastVisitedAt: new Date(now - 1_000_000).toISOString(),
350 };
352​
353function buildPerfSeedState(): PerfPersistedState {
354 const now = Date.now();
355 const projects: PerfPersistedProject[] = [
356 {
357 id: "perf-project-1",
358 name: "codething-mvp",
359 cwd: "/tmp/perf/codething-mvp",
360 model: "gpt-5-codex",
361 expanded: true,
362 },
363 {
364 id: "perf-project-2",
365 name: "contracts-bench",
366 cwd: "/tmp/perf/contracts-bench",
367 model: "gpt-5-codex",
368 expanded: true,
369 },
370 ];
371​
372 const threads: PerfPersistedThread[] = [];
373 let threadOrdinal = 0;
374​
375 for (const project of projects) {
376 for (let threadIndex = 0; threadIndex < 5; threadIndex += 1) {
377 const threadId = `${project.id}-thread-${threadIndex + 1}`;
378 const threadCreatedAt = new Date(now - (threadOrdinal + 1) * 45_000).toISOString();
379 const messages: PerfPersistedMessage[] = [];
380 const exchangeCount = 6;
381 for (let exchangeIndex = 0; exchangeIndex < exchangeCount; exchangeIndex += 1) {
382 const msgBaseOffsetMs =
383 (threadOrdinal * exchangeCount + exchangeIndex + 1) * 4_500 + threadIndex * 850;
384 const userCreatedAt = new Date(now - msgBaseOffsetMs - 1_500).toISOString();
385 const assistantCreatedAt = new Date(now - msgBaseOffsetMs).toISOString();
386 messages.push({
387 id: `${threadId}-user-${exchangeIndex + 1}`,
388 role: "user",
389 text: `Investigate renderer performance pattern ${exchangeIndex + 1} for ${project.name}.`,
390 createdAt: userCreatedAt,
391 streaming: false,
392 });
393 messages.push({
394 id: `${threadId}-assistant-${exchangeIndex + 1}`,
395 role: "assistant",
396 text: [
397 `Profiling note ${exchangeIndex + 1}:`,
398 "- Checked event dispatch and render cadence.",
399 "- Compared selector interactions and thread switches.",
400 "- Captured actionable optimization candidates.",
401 ].join("\n"),
402 createdAt: assistantCreatedAt,
403 streaming: false,
404 });
405 }
406​
407 threads.push({
408 id: threadId,
409 projectId: project.id,
410 title: `${project.name} perf thread ${threadIndex + 1}`,
411 model: "gpt-5-codex",
412 terminalOpen: false,
413 messages,
414 createdAt: threadCreatedAt,
415 lastVisitedAt: new Date(now - threadOrdinal * 2_000).toISOString(),
416 });
417 threadOrdinal += 1;
418 }
419 }
420​
421 for (const project of projects) {
422 threads.push(buildLargePerfThread(project, now));
423 }
424​
425 return {
426 version: 7,
427 runtimeMode: "approval-required",
428 projects,
429 threads,
430 activeThreadId: threads[0]?.id ?? null,
431 };
433​
434async function seedRendererState(
435 window: BrowserWindow,
436 state: unknown,
437): Promise<void> {
438 const script = `
439 (() => {
440 const key = "t3code:renderer-state:v7";
441 localStorage.setItem(key, JSON.stringify(${JSON.stringify(state)}));
442 window.location.reload();
443 })();
444 `;
445 await window.webContents.executeJavaScript(script, true);
447​
448async function readRendererPersistedThreadCount(window: BrowserWindow): Promise<number> {
449 const script = `
450 (() => {
451 const key = "t3code:renderer-state:v7";
452 const raw = localStorage.getItem(key);
453 let threads = 0;
454 if (raw) {
455 try {
456 const parsed = JSON.parse(raw);
457 threads = Array.isArray(parsed?.threads) ? parsed.threads.length : 0;
458 } catch {
459 threads = -1;
460 }
461 }
462 return threads;
463 })();
464 `;
465 return window.webContents.executeJavaScript(script, true);
467​
468async function runRendererPerfInteractions(
469 window: BrowserWindow,
470 benchmarkThreadIds: string[],
471): Promise<RendererPerfInteractions> {
472 const script = `
473 (async () => {
474 const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
475 const must = (condition, message) => {
476 if (!condition) throw new Error(message);
477 };
478 const nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => resolve()));
479 const waitFor = async (predicate, timeoutMs, message) => {
480 const deadline = performance.now() + timeoutMs;
481 while (performance.now() < deadline) {
482 if (predicate()) return;
483 await nextFrame();
484 }
485 throw new Error(message);
486 };
487​
488 const clickElement = (node) => {
489 if (!(node instanceof HTMLElement)) return false;
490 node.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true, cancelable: true }));
491 node.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));
492 node.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true }));
493 node.click();
494 return true;
495 };
496 const getThreadButtons = () =>
497 Array.from(document.querySelectorAll("[data-perf-thread-id]")).filter(
498 (node) => node instanceof HTMLElement,
499 );
500 const getPersistedStateStats = () => {
501 const key = "t3code:renderer-state:v7";
502 const raw = localStorage.getItem(key);
503 if (!raw) {
504 return { present: false, projects: 0, threads: 0 };
505 }
506 try {
507 const parsed = JSON.parse(raw);
508 const projects = Array.isArray(parsed?.projects) ? parsed.projects.length : 0;
509 const threads = Array.isArray(parsed?.threads) ? parsed.threads.length : 0;
510 return { present: true, projects, threads };
511 } catch {
512 return { present: true, projects: -1, threads: -1 };
513 }
514 };
515 const getThreadListDiagnostics = () => ({
516 url: window.location.href,
517 readyState: document.readyState,
518 threadButtonCount: getThreadButtons().length,
519 sidebarButtonCount: document.querySelectorAll("nav button").length,
520 noProjectsVisible:
521 document.body.textContent?.toLowerCase().includes("no projects yet") ?? false,
522 connectingVisible:
523 document.body.textContent?.toLowerCase().includes("connecting to t3 code server") ?? false,
524 persistedState: getPersistedStateStats(),
525 });
526 let threadButtons = [];
527 let renderedThreadIds = [];
528 try {
529 await waitFor(
530 () => getThreadButtons().length >= 1,
531 15_000,
532 "Expected seeded thread rows to be rendered.",
533 );
534 threadButtons = getThreadButtons();
535 renderedThreadIds = threadButtons
536 .map((node) => node.getAttribute("data-perf-thread-id"))
537 .filter((value) => typeof value === "string" && value.length > 0);
538 } catch (error) {
539 const message = error instanceof Error ? error.message : String(error);
540 console.warn("[desktop-perf] thread list unavailable; continuing", {
541 message,
542 diagnostics: getThreadListDiagnostics(),
543 });
544 }
545 const getActiveThreadId = () => {
546 const scroller = document.querySelector("[data-perf-messages-scroll]");
547 if (!(scroller instanceof HTMLElement)) return null;
548 const value = scroller.getAttribute("data-perf-active-thread-id");
549 return typeof value === "string" && value.length > 0 ? value : null;
550 };
551 const waitForActiveThread = async (threadId) => {
552 await waitFor(
553 () => getActiveThreadId() === threadId,
554 15_000,
555 "Timed out waiting for thread activation " + threadId,
556 );
557 };
558​
559 const measureThreadRender = async (threadId) => {
560 const selector = '[data-perf-thread-id="' + threadId + '"]';
561 const targetButton = document.querySelector(selector);
562 must(targetButton instanceof HTMLElement, "Thread button missing for " + threadId);
563 const start = performance.now();
564 clickElement(targetButton);
565 await waitForActiveThread(threadId);
566 await nextFrame();
567 await nextFrame();
568 const scroller = document.querySelector("[data-perf-messages-scroll]");
569 const messageCountRaw =
570 scroller instanceof HTMLElement ? scroller.getAttribute("data-perf-message-count") : null;
571 const messageCount =
572 messageCountRaw && /^\\d+$/.test(messageCountRaw) ? Number(messageCountRaw) : 0;
573 return {
574 threadId,
575 messageCount,
576 renderMs: Number((performance.now() - start).toFixed(2)),
577 };
578 };
579 const median = (values) => {
580 if (!Array.isArray(values) || values.length === 0) return 0;
581 const sorted = [...values].sort((a, b) => a - b);
582 const middle = Math.floor(sorted.length / 2);
583 if (sorted.length % 2 === 0) {
584 return Number((((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2).toFixed(2));
585 }
586 return Number((sorted[middle] ?? 0).toFixed(2));
587 };
588​
589 const runBenchmarkThreadSweep = ${RUN_BENCHMARK_THREAD_SWEEP};
590 const preferredThreadIds = ${JSON.stringify(benchmarkThreadIds)}.filter(
591 (value) => typeof value === "string" && value.length > 0,
592 );
593 const benchmarkThreadIds = runBenchmarkThreadSweep
594 ? preferredThreadIds.filter((threadId) => renderedThreadIds.includes(threadId))
595 : [];
596 if (runBenchmarkThreadSweep && benchmarkThreadIds.length === 0) {
597 benchmarkThreadIds.push(...renderedThreadIds.slice(0, ${BENCHMARK_THREAD_COUNT}));
598 }
599​
600 const ensureThreadSwitchTarget = async (threadId) => {
601 if (getActiveThreadId() !== threadId) {
602 return;
603 }
604 const fallbackThreadId = renderedThreadIds.find((id) => id !== threadId);
605 if (!fallbackThreadId) return;
606 const fallbackButton = document.querySelector('[data-perf-thread-id="' + fallbackThreadId + '"]');
607 if (!(fallbackButton instanceof HTMLElement)) return;
608 clickElement(fallbackButton);
609 await waitForActiveThread(fallbackThreadId);
610 await nextFrame();
611 };
612​
613 const firstPassByThreadId = new Map();
614 const followUpSamplesByThreadId = new Map();
615 if (runBenchmarkThreadSweep) {
616 for (const threadId of benchmarkThreadIds) {
617 await ensureThreadSwitchTarget(threadId);
618 firstPassByThreadId.set(threadId, await measureThreadRender(threadId));
619 }
620​
621 for (const threadId of benchmarkThreadIds) {
622 followUpSamplesByThreadId.set(threadId, []);
623 }
624 const followUpPassCount = ${BENCHMARK_FOLLOW_UP_PASS_COUNT};
625 for (let passIndex = 0; passIndex < followUpPassCount; passIndex += 1) {
626 for (const threadId of benchmarkThreadIds) {
627 await ensureThreadSwitchTarget(threadId);
628 const sample = await measureThreadRender(threadId);
629 const samples = followUpSamplesByThreadId.get(threadId);
630 if (Array.isArray(samples)) {
631 samples.push(sample.renderMs);
632 } else {
633 followUpSamplesByThreadId.set(threadId, [sample.renderMs]);
634 }
635 }
636 }
637 }
638​
639 const largeThreadRenderStats = benchmarkThreadIds.map((threadId) => {
640 const first = firstPassByThreadId.get(threadId);
641 const followUpSamples = followUpSamplesByThreadId.get(threadId);
642 const messageCount = first?.messageCount ?? 0;
643 const firstRenderMs = first?.renderMs ?? 0;
644 const followUpValues =
645 Array.isArray(followUpSamples) && followUpSamples.length > 0
646 ? followUpSamples
647 : [firstRenderMs];
648 const followUpMinMs = Number(Math.min(...followUpValues).toFixed(2));
649 const followUpMaxMs = Number(Math.max(...followUpValues).toFixed(2));
650 const followUpRenderMs = median(followUpValues);
651 const deltaMs = Number((followUpRenderMs - firstRenderMs).toFixed(2));
652 const deltaPct =
653 firstRenderMs > 0 ? Number((((followUpRenderMs - firstRenderMs) / firstRenderMs) * 100).toFixed(1)) : 0;
654 return {
655 threadId,
656 messageCount,
657 firstRenderMs,
658 followUpRenderMs,
659 followUpMinMs,
660 followUpMaxMs,
661 followUpSampleCount: Array.isArray(followUpSamples) ? followUpSamples.length : 0,
662 deltaMs,
663 deltaPct,
664 };
665 });
666​
667 const runOptionalRendererInteractions = ${RUN_OPTIONAL_RENDERER_INTERACTIONS};
668 const clickCount = Math.min(1, threadButtons.length);
669 for (let index = 0; index < clickCount; index += 1) {
670 clickElement(threadButtons[index]);
671 await sleep(80);
672 }
673​
674 const scroller = document.querySelector("[data-perf-messages-scroll]");
675 if (runOptionalRendererInteractions && scroller instanceof HTMLElement) {
676 scroller.scrollTo({ top: scroller.scrollHeight, behavior: "instant" });
677 await sleep(60);
678 scroller.scrollTo({ top: 0, behavior: "instant" });
679 await sleep(60);
680 }
681​
682 const getComposerTextarea = () => {
683 const direct = document.querySelector("[data-perf-composer-input]");
684 if (direct instanceof HTMLTextAreaElement) return direct;
685 const fallback = document.querySelector("form textarea");
686 if (fallback instanceof HTMLTextAreaElement) return fallback;
687 return null;
688 };
689 try {
690 await waitFor(
691 () => getComposerTextarea() instanceof HTMLTextAreaElement,
692 15_000,
693 "Composer textarea missing.",
694 );
695 } catch (error) {
696 const message = error instanceof Error ? error.message : String(error);
697 throw new Error(
698 "Composer textarea missing. diagnostics=" +
699 JSON.stringify({
700 ...getThreadListDiagnostics(),
701 hasMessagesScroll:
702 document.querySelector("[data-perf-messages-scroll]") instanceof HTMLElement,
703 activeThreadId: getActiveThreadId(),
704 }) +
705 "; cause=" +
706 message,
707 );
708 }
709 const textarea = getComposerTextarea();
710 must(textarea instanceof HTMLTextAreaElement, "Composer textarea missing.");
711 textarea.focus();
712​
713 const valueDescriptor = Object.getOwnPropertyDescriptor(
714 HTMLTextAreaElement.prototype,
715 "value",
716 );
717 const setValue = valueDescriptor?.set;
718 must(typeof setValue === "function", "Textarea value setter unavailable.");
719 const inputText = runOptionalRendererInteractions ? "Perf." : ".";
720​
721 for (const character of inputText) {
722 textarea.dispatchEvent(
723 new KeyboardEvent("keydown", { key: character, bubbles: true, cancelable: true }),
724 );
725 setValue.call(textarea, textarea.value + character);
726 textarea.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
727 textarea.dispatchEvent(
728 new KeyboardEvent("keyup", { key: character, bubbles: true, cancelable: true }),
729 );
730 await sleep(8);
731 }
732​
733 const selectOption = async (triggerSelector, optionSelector, label) => {
734 const trigger = document.querySelector(triggerSelector);
735 if (!(trigger instanceof HTMLElement)) {
736 console.warn("[desktop-perf] selector trigger not found", { label, triggerSelector });
737 return null;
738 }
739 clickElement(trigger);
740 await sleep(130);
741​
742 const options = Array.from(document.querySelectorAll(optionSelector)).filter(
743 (node) => node instanceof HTMLElement,
744 );
745 if (options.length === 0) {
746 console.warn("[desktop-perf] selector options not found", { label, optionSelector });
747 return null;
748 }
749 const preferred = options[1] ?? options[0];
750 clickElement(preferred);
751 await sleep(130);
752 return preferred.textContent?.trim() ?? null;
753 };
754​
755 let selectedModel = null;
756 if (runOptionalRendererInteractions) {
757 selectedModel = await selectOption(
758 "[data-perf-model-trigger]",
759 "[data-perf-model-option]",
760 "Model",
761 );
762 await selectOption(
763 "[data-perf-reasoning-trigger]",
764 "[data-perf-reasoning-option]",
765 "Reasoning",
766 );
767​
768 const diffToggle = document.querySelector("[data-perf-diff-toggle]");
769 if (diffToggle instanceof HTMLElement) {
770 clickElement(diffToggle);
771 await sleep(70);
772 clickElement(diffToggle);
773 await sleep(70);
774 }
775​
776 const runtimeToggle = document.querySelector("[data-perf-runtime-toggle]");
777 if (runtimeToggle instanceof HTMLElement) {
778 clickElement(runtimeToggle);
779 await sleep(100);
780 }
781 }
782​
783 return {
784 threadClicks: clickCount,
785 typedChars: inputText.length,
786 selectedModel,
787 largeThreadRenderStats,
788 benchmarkThreadIds,
789 };
790 })();
791 `;
792​
793 return window.webContents.executeJavaScript(script, true);
795​
796async function evaluateRenderer<T>(window: BrowserWindow, script: string): Promise<T> {
797 return window.webContents.executeJavaScript(script, true) as Promise<T>;
799​
800async function waitForRendererCondition(
801 window: BrowserWindow,
802 script: string,
803 message: string,
804 timeoutMs = 15_000,
805): Promise<void> {
806 const deadline = Date.now() + timeoutMs;
807 while (Date.now() < deadline) {
808 const matched = await evaluateRenderer<boolean>(window, script);
809 if (matched) return;
810 await delay(50);
811 }
812 throw new Error(message);
814​
815function sendShortcutKey(
816 webContents: WebContents,
817 keyCode: string,
818 modifier: TerminalPerfInteractions["modifierUsed"],
819): void {
820 webContents.sendInputEvent({
821 type: "keyDown",
822 keyCode,
823 modifiers: [modifier],
824 });
825 webContents.sendInputEvent({
826 type: "keyUp",
827 keyCode,
828 modifiers: [modifier],
829 });
831​
832async function sendTextInput(webContents: WebContents, text: string): Promise<void> {
833 for (const character of text) {
834 webContents.sendInputEvent({
835 type: "char",
836 keyCode: character,
837 });
838 await delay(4);
839 }
841​
842async function pressEnter(webContents: WebContents): Promise<void> {
843 webContents.sendInputEvent({
844 type: "keyDown",
845 keyCode: "Enter",
846 });
847 webContents.sendInputEvent({
848 type: "keyUp",
849 keyCode: "Enter",
850 });
851 await delay(20);
853​
854async function focusActiveTerminalInput(window: BrowserWindow): Promise<void> {
855 await waitForRendererCondition(
856 window,
857 `(() => {
858 const inputs = Array.from(
859 document.querySelectorAll(".thread-terminal-drawer .xterm-helper-textarea"),
860 );
861 const target = inputs[inputs.length - 1];
862 if (!(target instanceof HTMLTextAreaElement)) return false;
863 target.focus();
864 return document.activeElement === target;
865 })()`,
866 "Active terminal input is not focusable.",
867 15_000,
868 );
870​
871async function runTerminalPerfInteractions(
872 window: BrowserWindow,
873): Promise<TerminalPerfInteractions> {
874 window.focus();
875 window.webContents.focus();
876​
877 const modifier = await evaluateRenderer<TerminalPerfInteractions["modifierUsed"]>(
878 window,
879 `navigator.platform.toLowerCase().includes("mac") ? "meta" : "control"`,
880 );
881 const terminalDrawerSelector = ".thread-terminal-drawer";
882​
883 sendShortcutKey(window.webContents, "J", modifier);
884 try {
885 await waitForRendererCondition(
886 window,
887 `document.querySelector(${JSON.stringify(terminalDrawerSelector)}) instanceof HTMLElement`,
888 "Terminal drawer did not open after shortcut.",
889 15_000,
890 );
891 } catch (error) {
892 const diagnostics = await evaluateRenderer(window, `(() => ({
893 url: window.location.href,
894 readyState: document.readyState,
895 hasDrawer: document.querySelector(${JSON.stringify(terminalDrawerSelector)}) instanceof HTMLElement,
896 terminalButtonCount: document.querySelectorAll("[data-perf-terminal-toggle]").length,
897 activeElementTag: document.activeElement ? document.activeElement.tagName : null,
898 bodyHasConnectText:
899 document.body.textContent?.toLowerCase().includes("connecting to t3 code server") ?? false,
900 }))()`);
901 const message = error instanceof Error ? error.message : String(error);
902 throw new Error(
903 `Terminal drawer did not open after shortcut. diagnostics=${JSON.stringify(diagnostics)}; cause=${message}`,
904 {
905 cause: error,
906 },
907 );
908 }
909​
910 await focusActiveTerminalInput(window);
911​
912 let splitCount = 0;
913 for (let splitIndex = 0; splitIndex < 2; splitIndex += 1) {
914 await focusActiveTerminalInput(window);
915 sendShortcutKey(window.webContents, "D", modifier);
916 try {
917 await waitForRendererCondition(
918 window,
919 `document.querySelectorAll(".thread-terminal-drawer .xterm-helper-textarea").length >= ${
920 splitIndex + 2
921 }`,
922 "Terminal split did not appear.",
923 15_000,
924 );
925 splitCount += 1;
926 } catch (error) {
927 const message = error instanceof Error ? error.message : String(error);
928 console.warn(`[desktop-perf] terminal split attempt ${splitIndex + 1} failed: ${message}`);
929 break;
930 }
931 }
932​
933 const commandMarker = `perfterm${Date.now().toString(36)}`;
934 const markerFilePath = path.join(os.tmpdir(), `t3code-desktop-perf-${commandMarker}`);
935 try {
936 fs.rmSync(markerFilePath, { force: true });
937 } catch {
938 // best effort cleanup for stale marker file
939 }
940​
941 await focusActiveTerminalInput(window);
942 await sendTextInput(window.webContents, `echo ${commandMarker}`);
943 await pressEnter(window.webContents);
944 await delay(120);
945​
946 await focusActiveTerminalInput(window);
947 await sendTextInput(window.webContents, `touch ${markerFilePath}`);
948 await pressEnter(window.webContents);
949​
950 const fileWaitDeadline = Date.now() + 20_000;
951 let commandFileTouched = false;
952 while (Date.now() < fileWaitDeadline) {
953 if (fs.existsSync(markerFilePath)) {
954 commandFileTouched = true;
955 break;
956 }
957 await delay(100);
958 }
959 if (!commandFileTouched) {
960 throw new Error(`Terminal command side effect file not observed at ${markerFilePath}.`);
961 }
962​
963 let commandEchoObserved = false;
964 try {
965 await waitForRendererCondition(
966 window,
967 `(() => {
968 const marker = ${JSON.stringify(commandMarker)};
969 const drawer = document.querySelector(${JSON.stringify(terminalDrawerSelector)});
970 if (!(drawer instanceof HTMLElement)) return false;
971 const rawText = [
972 drawer.textContent ?? "",
973 ...Array.from(
974 drawer.querySelectorAll(
975 ".xterm-accessibility, .xterm-accessibility-tree, .xterm-helper-textarea",
976 ),
977 ).map((node) => node.textContent ?? ""),
978 ].join(" ");
979 return rawText.toLowerCase().includes(marker.toLowerCase());
980 })()`,
981 "Terminal command output marker was not found in terminal DOM.",
982 5_000,
983 );
984 commandEchoObserved = true;
985 } catch {
986 commandEchoObserved = false;
987 }
988​
989 try {
990 fs.rmSync(markerFilePath, { force: true });
991 } catch {
992 // best effort cleanup after verification
993 }
994​
995 return {
996 openedByShortcut: true,
997 splitCount,
998 commandMarker,
999 commandEchoObserved,
1000 commandFileTouched,
1001 modifierUsed: modifier,
1002 };
1004​
1005export async function runDesktopPerfAutomation(window: BrowserWindow): Promise<void> {
1006 if (!PERF_AUTOMATION_ENABLED) return;
1007 console.log("[desktop-perf] automation mode enabled");
1008 if (PERF_DONE_OUT_PATH.length > 0) {
1009 console.log(`[desktop-perf] done marker path: ${PERF_DONE_OUT_PATH}`);
1011 console.log(`[desktop-perf] trace path: ${PERF_TRACE_OUT_PATH}`);
1012 console.log(
1013 "[desktop-perf] interaction toggles:",
1014 JSON.stringify({
1015 terminal: RUN_TERMINAL_INTERACTIONS,
1016 optionalRenderer: RUN_OPTIONAL_RENDERER_INTERACTIONS,
1017 benchmarkSweep: RUN_BENCHMARK_THREAD_SWEEP,
1018 benchmarkFollowUpPasses: BENCHMARK_FOLLOW_UP_PASS_COUNT,
1019 }),
1020 );
1021​
1022 if (PERF_TRACE_OUT_PATH.length === 0) {
1023 const error = new Error("T3CODE_DESKTOP_PERF_TRACE_OUT is required for perf automation.");
1024 console.error("[desktop-perf] " + error.message);
1025 if (PERF_DONE_OUT_PATH.length > 0) {
1026 fs.mkdirSync(path.dirname(PERF_DONE_OUT_PATH), { recursive: true });
1027 fs.writeFileSync(
1028 PERF_DONE_OUT_PATH,
1029 JSON.stringify(
1031 status: "error",
1032 error: error.message,
1033 },
1034 null,
1035 2,
1036 ),
1037 );
1039 return;
1041​
1042 const traceConfig = {
1043 included_categories: [
1044 "devtools.timeline",
1045 "disabled-by-default-devtools.timeline",
1046 "disabled-by-default-devtools.timeline.frame",
1047 "blink.user_timing",
1048 "v8",
1049 "disabled-by-default-v8.cpu_profiler",
1050 "disabled-by-default-v8.gc",
1051 ],
1052 record_mode: "record-until-full",
1053 };
1054​
1055 let tracePath = PERF_TRACE_OUT_PATH;
1056 let isTraceRecording = false;
1057 const startedAt = Date.now();
1058 let seed: ResolvedPerfSeed | null = null;
1059 try {
1060 seed = resolvePerfSeed();
1061 const seedLabel =
1062 seed.source === "file" ? `file (${seed.resolvedPath ?? "unknown"})` : seed.source;
1063 const benchmarkThreadLabel =
1064 seed.benchmarkThreads.length > 0
1065 ? seed.benchmarkThreads
1066 .slice(0, 5)
1067 .map((thread) => `${thread.id} (${toTitlePreview(thread.title)})`)
1068 .join(", ")
1069 : "none";
1070 console.log(`[desktop-perf] seed source: ${seedLabel}`);
1071 console.log(`[desktop-perf] benchmark thread count: ${seed.benchmarkThreads.length}`);
1072 console.log(`[desktop-perf] benchmark thread preview: ${benchmarkThreadLabel}`);
1073​
1074 console.log("[desktop-perf] waiting for initial load");
1075 await waitForDidFinishLoad(window.webContents, {
1076 timeoutMs: 60_000,
1077 label: "initial load",
1078 });
1079 console.log("[desktop-perf] seeding renderer state");
1080 await seedRendererState(window, seed.state);
1081 console.log("[desktop-perf] waiting for reload");
1082 await waitForDidFinishLoad(window.webContents, {
1083 timeoutMs: 60_000,
1084 label: "post-seed reload",
1085 });
1086 let postSeedThreadCount = await readRendererPersistedThreadCount(window);
1087 if (postSeedThreadCount <= 0) {
1088 console.warn("[desktop-perf] post-seed state had no threads; retrying seed on current origin");
1089 await seedRendererState(window, seed.state);
1090 await waitForDidFinishLoad(window.webContents, {
1091 timeoutMs: 60_000,
1092 label: "post-seed retry reload",
1093 });
1094 postSeedThreadCount = await readRendererPersistedThreadCount(window);
1095 if (postSeedThreadCount <= 0) {
1096 console.warn("[desktop-perf] post-seed retry still has no threads");
1099 await delay(300);
1100​
1101 fs.mkdirSync(path.dirname(PERF_TRACE_OUT_PATH), { recursive: true });
1102 console.log("[desktop-perf] starting trace recording");
1103 await contentTracing.startRecording(traceConfig);
1104 isTraceRecording = true;
1105 console.log("[desktop-perf] running scripted interactions");
1106 let rendererInteractions: RendererPerfInteractions = {
1107 threadClicks: 0,
1108 typedChars: 0,
1109 selectedModel: null,
1110 largeThreadRenderStats: [],
1111 benchmarkThreadIds: [],
1112 };
1113 try {
1114 rendererInteractions = await runRendererPerfInteractions(
1115 window,
1116 seed.benchmarkThreads.map((thread) => thread.id),
1117 );
1118 } catch (rendererError) {
1119 const message = rendererError instanceof Error ? rendererError.message : String(rendererError);
1120 console.warn("[desktop-perf] renderer scripted interactions failed; continuing:", message);
1122 let terminalInteractions: TerminalPerfInteractions = {
1123 openedByShortcut: false,
1124 splitCount: 0,
1125 commandMarker: "",
1126 commandEchoObserved: false,
1127 commandFileTouched: false,
1128 modifierUsed: process.platform === "darwin" ? "meta" : "control",
1129 };
1130 if (RUN_TERMINAL_INTERACTIONS) {
1131 console.log("[desktop-perf] running terminal shortcut interactions");
1132 try {
1133 terminalInteractions = await runTerminalPerfInteractions(window);
1134 } catch (terminalError) {
1135 const message = terminalError instanceof Error ? terminalError.message : String(terminalError);
1136 console.warn("[desktop-perf] terminal scripted interactions failed; continuing:", message);
1138 } else {
1139 console.log("[desktop-perf] terminal shortcut interactions disabled for this run");
1141 const interactions = {
1142 ...rendererInteractions,
1143 terminal: terminalInteractions,
1144 };
1145 const titleByThreadId = new Map(
1146 seed.benchmarkThreads.map((thread) => [thread.id, toTitlePreview(thread.title)]),
1147 );
1148 const interactionsWithTitles = {
1149 ...interactions,
1150 // oxlint-disable-next-line oxc/no-map-spread
1151 largeThreadRenderStats: interactions.largeThreadRenderStats.map((stat) => ({
1152 ...stat,
1153 threadTitleShort:
1154 titleByThreadId.get(stat.threadId) ??
1155 stat.threadId.slice(0, BENCHMARK_TITLE_PREVIEW_LENGTH),
1156 })),
1157 };
1158 await delay(300);
1159 console.log("[desktop-perf] stopping trace recording");
1160 tracePath = await withTimeout(
1161 contentTracing.stopRecording(PERF_TRACE_OUT_PATH),
1162 15_000,
1163 "trace recording to stop",
1164 );
1165 isTraceRecording = false;
1166 const completedAt = Date.now();
1167​
1168 console.log(`[desktop-perf] trace recorded at ${tracePath}`);
1169 if (PERF_DONE_OUT_PATH.length > 0) {
1170 fs.mkdirSync(path.dirname(PERF_DONE_OUT_PATH), { recursive: true });
1171 fs.writeFileSync(
1172 PERF_DONE_OUT_PATH,
1173 JSON.stringify(
1175 status: "ok",
1176 tracePath,
1177 interactions: interactionsWithTitles,
1178 seed: {
1179 source: seed.source,
1180 path: seed.resolvedPath,
1181 projectCount: seed.projectCount,
1182 threadCount: seed.threadCount,
1183 benchmarkThreadCount: seed.benchmarkThreads.length,
1184 },
1185 config: {
1186 runTerminalInteractions: RUN_TERMINAL_INTERACTIONS,
1187 runOptionalRendererInteractions: RUN_OPTIONAL_RENDERER_INTERACTIONS,
1188 runBenchmarkThreadSweep: RUN_BENCHMARK_THREAD_SWEEP,
1189 benchmarkFollowUpPassCount: BENCHMARK_FOLLOW_UP_PASS_COUNT,
1190 },
1191 startedAt: new Date(startedAt).toISOString(),
1192 completedAt: new Date(completedAt).toISOString(),
1193 durationMs: completedAt - startedAt,
1194 },
1195 null,
1196 2,
1197 ),
1198 );
1200 } catch (error) {
1201 if (isTraceRecording) {
1202 try {
1203 tracePath = await withTimeout(
1204 contentTracing.stopRecording(PERF_TRACE_OUT_PATH),
1205 15_000,
1206 "trace recording to stop after failure",
1207 );
1208 } catch (stopError) {
1209 const stopMessage = stopError instanceof Error ? stopError.message : String(stopError);
1210 console.error("[desktop-perf] failed to stop trace recording:", stopMessage);
1211 } finally {
1212 isTraceRecording = false;
1215 const message = error instanceof Error ? error.message : String(error);
1216 console.error("[desktop-perf] automation failed:", message);
1217 if (PERF_DONE_OUT_PATH.length > 0) {
1218 fs.mkdirSync(path.dirname(PERF_DONE_OUT_PATH), { recursive: true });
1219 fs.writeFileSync(
1220 PERF_DONE_OUT_PATH,
1221 JSON.stringify(
1223 status: "error",
1224 error: message,
1225 tracePath,
1226 seed:
1227 seed === null
1228 ? undefined
1229 : {
1230 source: seed.source,
1231 path: seed.resolvedPath,
1232 projectCount: seed.projectCount,
1233 threadCount: seed.threadCount,
1234 benchmarkThreadCount: seed.benchmarkThreads.length,
1235 },
1236 config: {
1237 runTerminalInteractions: RUN_TERMINAL_INTERACTIONS,
1238 runOptionalRendererInteractions: RUN_OPTIONAL_RENDERER_INTERACTIONS,
1239 runBenchmarkThreadSweep: RUN_BENCHMARK_THREAD_SWEEP,
1240 benchmarkFollowUpPassCount: BENCHMARK_FOLLOW_UP_PASS_COUNT,
1241 },
1242 startedAt: new Date(startedAt).toISOString(),
1243 completedAt: new Date().toISOString(),
1244 },
1245 null,
1246 2,
1247 ),
1248 );