// oxlint-disable no-await-in-loopimport fs from "node:fs";import os from "node:os";import path from "node:path"; import { BrowserWindow, contentTracing, type WebContents } from "electron";import { resolveBenchmarkFollowUpPassCount, shouldRunBenchmarkThreadSweep, shouldRunOptionalRendererPerfInteractions, shouldRunTerminalPerfInteractions,} from "./perfConfig"; 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() ?? "";const PERF_SEED_PATH = process.env.T3CODE_DESKTOP_PERF_SEED_PATH?.trim() ?? "";const RUN_TERMINAL_INTERACTIONS = shouldRunTerminalPerfInteractions({ T3CODE_DESKTOP_PERF_RUN_TERMINAL: process.env.T3CODE_DESKTOP_PERF_RUN_TERMINAL, CI: process.env.CI,});const RUN_OPTIONAL_RENDERER_INTERACTIONS = shouldRunOptionalRendererPerfInteractions({ T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: process.env.T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER, CI: process.env.CI,});const BENCHMARK_FOLLOW_UP_PASS_COUNT = resolveBenchmarkFollowUpPassCount({ T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: process.env.T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES, CI: process.env.CI,});const RUN_BENCHMARK_THREAD_SWEEP = shouldRunBenchmarkThreadSweep({ T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: process.env.T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP, CI: process.env.CI,}); function delay(ms: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, ms));} function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error(`Timed out waiting for ${label} (${timeoutMs}ms).`)); }, timeoutMs); timeout.unref(); promise.then( (value) => { clearTimeout(timeout); resolve(value); }, (error: unknown) => { clearTimeout(timeout); reject(error); }, ); });} function waitForDidFinishLoad( webContents: WebContents, options?: { timeoutMs?: number; label?: string },): Promise<void> { const timeoutMs = options?.timeoutMs ?? 20_000; const label = options?.label ?? "renderer load"; if (!webContents.isLoadingMainFrame()) { const currentUrl = webContents.getURL(); if (currentUrl.length === 0 || currentUrl.startsWith("chrome-error://")) { return Promise.reject( new Error(`${label} is not loading and no valid page is currently loaded (${currentUrl}).`), ); } return Promise.resolve(); } return new Promise((resolve, reject) => { let settled = false; const cleanup = () => { webContents.removeListener("did-finish-load", onLoad); webContents.removeListener("did-fail-load", onFailLoad); clearTimeout(timeout); }; const finish = (callback: () => void) => { if (settled) return; settled = true; cleanup(); callback(); }; const onLoad = () => { finish(resolve); }; const onFailLoad = ( _event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean, ) => { if (!isMainFrame) return; finish(() => { reject( new Error( `${label} failed for ${validatedURL || "(unknown url)"} [${errorCode}] ${errorDescription}`, ), ); }); }; const timeout = setTimeout(() => { finish(() => reject(new Error(`Timed out waiting for ${label} (${timeoutMs}ms).`))); }, timeoutMs); timeout.unref(); webContents.on("did-fail-load", onFailLoad); 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;} const LARGE_THREAD_EXCHANGE_COUNT = 120;const BENCHMARK_THREAD_COUNT = 2;const BENCHMARK_TITLE_PREVIEW_LENGTH = 15; interface PerfThreadStat { id: string; title: string; messageCount: number;} interface ResolvedPerfSeed { source: string; resolvedPath: string | null; state: unknown; projectCount: number; threadCount: number; benchmarkThreads: PerfThreadStat[];} interface PerfLargeThreadRenderStat { threadId: string; messageCount: number; firstRenderMs: number; followUpRenderMs: number; followUpMinMs: number; followUpMaxMs: number; followUpSampleCount: number; deltaMs: number; deltaPct: number;} interface RendererPerfInteractions { threadClicks: number; typedChars: number; selectedModel: string | null; largeThreadRenderStats: PerfLargeThreadRenderStat[]; benchmarkThreadIds: string[];} interface TerminalPerfInteractions { openedByShortcut: boolean; splitCount: number; commandMarker: string; commandEchoObserved: boolean; commandFileTouched: boolean; modifierUsed: "meta" | "control";} function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === "object" && value !== null;} function collectThreadStats(state: unknown): PerfThreadStat[] { if (!isRecord(state)) return []; const threads = state.threads; if (!Array.isArray(threads)) return []; const stats: PerfThreadStat[] = []; for (const thread of threads) { if (!isRecord(thread)) continue; const id = typeof thread.id === "string" ? thread.id : ""; if (id.length === 0) continue; const title = typeof thread.title === "string" ? thread.title : ""; const messages = thread.messages; const messageCount = Array.isArray(messages) ? messages.length : 0; stats.push({ id, title, messageCount }); } return stats;} function pickBenchmarkThreads(stats: PerfThreadStat[], benchmarkAll: boolean): PerfThreadStat[] { const sorted = stats.toSorted((a, b) => b.messageCount - a.messageCount); return benchmarkAll ? sorted : sorted.slice(0, BENCHMARK_THREAD_COUNT);} function toTitlePreview(title: string): string { return title.slice(0, BENCHMARK_TITLE_PREVIEW_LENGTH);} function resolvePerfSeed(): ResolvedPerfSeed { if (PERF_SEED_PATH.length === 0) { const generated = buildPerfSeedState(); const stats = collectThreadStats(generated); return { source: "generated", resolvedPath: null, state: generated, projectCount: generated.projects.length, threadCount: generated.threads.length, benchmarkThreads: pickBenchmarkThreads(stats, false), }; } const resolvedPath = path.isAbsolute(PERF_SEED_PATH) ? PERF_SEED_PATH : path.resolve(process.cwd(), PERF_SEED_PATH); if (!fs.existsSync(resolvedPath)) { throw new Error(`Perf seed file not found: ${resolvedPath}`); } let parsed: unknown; try { parsed = JSON.parse(fs.readFileSync(resolvedPath, "utf8")); } catch (error) { const message = error instanceof Error ? error.message : String(error); throw new Error(`Failed to parse perf seed JSON at ${resolvedPath}: ${message}`, { cause: error, }); } if (!isRecord(parsed)) { throw new Error(`Perf seed must be a JSON object: ${resolvedPath}`); } if (!Array.isArray(parsed.projects)) { throw new Error(`Perf seed is missing "projects" array: ${resolvedPath}`); } if (!Array.isArray(parsed.threads)) { throw new Error(`Perf seed is missing "threads" array: ${resolvedPath}`); } const stats = collectThreadStats(parsed); return { source: "file", resolvedPath, state: parsed, projectCount: parsed.projects.length, threadCount: parsed.threads.length, benchmarkThreads: pickBenchmarkThreads(stats, false), };} function buildLargeThreadMessage( projectName: string, exchangeIndex: number, role: "user" | "assistant",): string { if (role === "user") { return [ `Large-thread perf scenario ${exchangeIndex + 1} for ${projectName}.`, "Please audit render cost while scrolling and switching among heavy histories.", "Include hotspots in markdown rendering, timeline grouping, and message list virtualization candidates.", "Track regressions across interaction loops and report any long-task spikes.", ].join("\n"); } return [ `### Perf analysis batch ${exchangeIndex + 1}`, "", "- Checked keypress/input dispatch cost and scheduler churn.", "- Compared component update cadence before/after thread switch.", "- Captured timeline and branch/tool state snapshots.", "", "```txt", `project=${projectName}`, `batch=${exchangeIndex + 1}`, "status=stable", "focus=render-throughput", "```", "", "Observed stable behavior under bursty UI events; continue profiling for long-thread rendering regressions.", ].join("\n");} function buildLargePerfThread(project: PerfPersistedProject, now: number): PerfPersistedThread { const threadId = `${project.id}-thread-large`; const createdAt = new Date(now - 1_500_000).toISOString(); const messages: PerfPersistedMessage[] = []; for (let exchangeIndex = 0; exchangeIndex < LARGE_THREAD_EXCHANGE_COUNT; exchangeIndex += 1) { const offsetMs = (LARGE_THREAD_EXCHANGE_COUNT - exchangeIndex) * 11_000; messages.push({ id: `${threadId}-user-${exchangeIndex + 1}`, role: "user", text: buildLargeThreadMessage(project.name, exchangeIndex, "user"), createdAt: new Date(now - offsetMs - 2_000).toISOString(), streaming: false, }); messages.push({ id: `${threadId}-assistant-${exchangeIndex + 1}`, role: "assistant", text: buildLargeThreadMessage(project.name, exchangeIndex, "assistant"), createdAt: new Date(now - offsetMs).toISOString(), streaming: false, }); } return { id: threadId, projectId: project.id, title: `${project.name} perf large thread`, model: "gpt-5-codex", terminalOpen: false, messages, createdAt, lastVisitedAt: new Date(now - 1_000_000).toISOString(), };} 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; } } for (const project of projects) { threads.push(buildLargePerfThread(project, now)); } return { version: 7, runtimeMode: "approval-required", projects, threads, activeThreadId: threads[0]?.id ?? null, };} async function seedRendererState( window: BrowserWindow, state: unknown,): Promise<void> { const script = ` (() => { const key = "t3code:renderer-state:v7"; localStorage.setItem(key, JSON.stringify(${JSON.stringify(state)})); window.location.reload(); })(); `; await window.webContents.executeJavaScript(script, true);} async function readRendererPersistedThreadCount(window: BrowserWindow): Promise<number> { const script = ` (() => { const key = "t3code:renderer-state:v7"; const raw = localStorage.getItem(key); let threads = 0; if (raw) { try { const parsed = JSON.parse(raw); threads = Array.isArray(parsed?.threads) ? parsed.threads.length : 0; } catch { threads = -1; } } return threads; })(); `; return window.webContents.executeJavaScript(script, true);} async function runRendererPerfInteractions( window: BrowserWindow, benchmarkThreadIds: string[],): Promise<RendererPerfInteractions> { const script = ` (async () => { const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const must = (condition, message) => { if (!condition) throw new Error(message); }; const nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => resolve())); const waitFor = async (predicate, timeoutMs, message) => { const deadline = performance.now() + timeoutMs; while (performance.now() < deadline) { if (predicate()) return; await nextFrame(); } 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 getThreadButtons = () => Array.from(document.querySelectorAll("[data-perf-thread-id]")).filter( (node) => node instanceof HTMLElement, ); const getPersistedStateStats = () => {Lines 1–500 of 1251. Load more
// oxlint-disable no-await-in-loop import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { BrowserWindow, contentTracing, type WebContents } from "electron"; import { resolveBenchmarkFollowUpPassCount, shouldRunBenchmarkThreadSweep, shouldRunOptionalRendererPerfInteractions, shouldRunTerminalPerfInteractions, } from "./perfConfig"; 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() ?? ""; const PERF_SEED_PATH = process.env.T3CODE_DESKTOP_PERF_SEED_PATH?.trim() ?? ""; const RUN_TERMINAL_INTERACTIONS = shouldRunTerminalPerfInteractions({ T3CODE_DESKTOP_PERF_RUN_TERMINAL: process.env.T3CODE_DESKTOP_PERF_RUN_TERMINAL, CI: process.env.CI, }); const RUN_OPTIONAL_RENDERER_INTERACTIONS = shouldRunOptionalRendererPerfInteractions({ T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER: process.env.T3CODE_DESKTOP_PERF_RUN_OPTIONAL_RENDERER, CI: process.env.CI, }); const BENCHMARK_FOLLOW_UP_PASS_COUNT = resolveBenchmarkFollowUpPassCount({ T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES: process.env.T3CODE_DESKTOP_PERF_BENCHMARK_FOLLOW_UP_PASSES, CI: process.env.CI, }); const RUN_BENCHMARK_THREAD_SWEEP = shouldRunBenchmarkThreadSweep({ T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP: process.env.T3CODE_DESKTOP_PERF_RUN_BENCHMARK_SWEEP, CI: process.env.CI, }); function delay(ms: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, ms)); } function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error(`Timed out waiting for ${label} (${timeoutMs}ms).`)); }, timeoutMs); timeout.unref(); promise.then( (value) => { clearTimeout(timeout); resolve(value); }, (error: unknown) => { clearTimeout(timeout); reject(error); }, ); }); } function waitForDidFinishLoad( webContents: WebContents, options?: { timeoutMs?: number; label?: string }, ): Promise<void> { const timeoutMs = options?.timeoutMs ?? 20_000; const label = options?.label ?? "renderer load"; if (!webContents.isLoadingMainFrame()) { const currentUrl = webContents.getURL(); if (currentUrl.length === 0 || currentUrl.startsWith("chrome-error://")) { return Promise.reject( new Error(`${label} is not loading and no valid page is currently loaded (${currentUrl}).`), ); } return Promise.resolve(); } return new Promise((resolve, reject) => { let settled = false; const cleanup = () => { webContents.removeListener("did-finish-load", onLoad); webContents.removeListener("did-fail-load", onFailLoad); clearTimeout(timeout); }; const finish = (callback: () => void) => { if (settled) return; settled = true; cleanup(); callback(); }; const onLoad = () => { finish(resolve); }; const onFailLoad = ( _event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean, ) => { if (!isMainFrame) return; finish(() => { reject( new Error( `${label} failed for ${validatedURL || "(unknown url)"} [${errorCode}] ${errorDescription}`, ), ); }); }; const timeout = setTimeout(() => { finish(() => reject(new Error(`Timed out waiting for ${label} (${timeoutMs}ms).`))); }, timeoutMs); timeout.unref(); webContents.on("did-fail-load", onFailLoad); 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; } const LARGE_THREAD_EXCHANGE_COUNT = 120; const BENCHMARK_THREAD_COUNT = 2; const BENCHMARK_TITLE_PREVIEW_LENGTH = 15; interface PerfThreadStat { id: string; title: string; messageCount: number; } interface ResolvedPerfSeed { source: string; resolvedPath: string | null; state: unknown; projectCount: number; threadCount: number; benchmarkThreads: PerfThreadStat[]; } interface PerfLargeThreadRenderStat { threadId: string; messageCount: number; firstRenderMs: number; followUpRenderMs: number; followUpMinMs: number; followUpMaxMs: number; followUpSampleCount: number; deltaMs: number; deltaPct: number; } interface RendererPerfInteractions { threadClicks: number; typedChars: number; selectedModel: string | null; largeThreadRenderStats: PerfLargeThreadRenderStat[]; benchmarkThreadIds: string[]; } interface TerminalPerfInteractions { openedByShortcut: boolean; splitCount: number; commandMarker: string; commandEchoObserved: boolean; commandFileTouched: boolean; modifierUsed: "meta" | "control"; } function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === "object" && value !== null; } function collectThreadStats(state: unknown): PerfThreadStat[] { if (!isRecord(state)) return []; const threads = state.threads; if (!Array.isArray(threads)) return []; const stats: PerfThreadStat[] = []; for (const thread of threads) { if (!isRecord(thread)) continue; const id = typeof thread.id === "string" ? thread.id : ""; if (id.length === 0) continue; const title = typeof thread.title === "string" ? thread.title : ""; const messages = thread.messages; const messageCount = Array.isArray(messages) ? messages.length : 0; stats.push({ id, title, messageCount }); } return stats; } function pickBenchmarkThreads(stats: PerfThreadStat[], benchmarkAll: boolean): PerfThreadStat[] { const sorted = stats.toSorted((a, b) => b.messageCount - a.messageCount); return benchmarkAll ? sorted : sorted.slice(0, BENCHMARK_THREAD_COUNT); } function toTitlePreview(title: string): string { return title.slice(0, BENCHMARK_TITLE_PREVIEW_LENGTH); } function resolvePerfSeed(): ResolvedPerfSeed { if (PERF_SEED_PATH.length === 0) { const generated = buildPerfSeedState(); const stats = collectThreadStats(generated); return { source: "generated", resolvedPath: null, state: generated, projectCount: generated.projects.length, threadCount: generated.threads.length, benchmarkThreads: pickBenchmarkThreads(stats, false), }; } const resolvedPath = path.isAbsolute(PERF_SEED_PATH) ? PERF_SEED_PATH : path.resolve(process.cwd(), PERF_SEED_PATH); if (!fs.existsSync(resolvedPath)) { throw new Error(`Perf seed file not found: ${resolvedPath}`); } let parsed: unknown; try { parsed = JSON.parse(fs.readFileSync(resolvedPath, "utf8")); } catch (error) { const message = error instanceof Error ? error.message : String(error); throw new Error(`Failed to parse perf seed JSON at ${resolvedPath}: ${message}`, { cause: error, }); } if (!isRecord(parsed)) { throw new Error(`Perf seed must be a JSON object: ${resolvedPath}`); } if (!Array.isArray(parsed.projects)) { throw new Error(`Perf seed is missing "projects" array: ${resolvedPath}`); } if (!Array.isArray(parsed.threads)) { throw new Error(`Perf seed is missing "threads" array: ${resolvedPath}`); } const stats = collectThreadStats(parsed); return { source: "file", resolvedPath, state: parsed, projectCount: parsed.projects.length, threadCount: parsed.threads.length, benchmarkThreads: pickBenchmarkThreads(stats, false), }; } function buildLargeThreadMessage( projectName: string, exchangeIndex: number, role: "user" | "assistant", ): string { if (role === "user") { return [ `Large-thread perf scenario ${exchangeIndex + 1} for ${projectName}.`, "Please audit render cost while scrolling and switching among heavy histories.", "Include hotspots in markdown rendering, timeline grouping, and message list virtualization candidates.", "Track regressions across interaction loops and report any long-task spikes.", ].join("\n"); } return [ `### Perf analysis batch ${exchangeIndex + 1}`, "", "- Checked keypress/input dispatch cost and scheduler churn.", "- Compared component update cadence before/after thread switch.", "- Captured timeline and branch/tool state snapshots.", "", "```txt", `project=${projectName}`, `batch=${exchangeIndex + 1}`, "status=stable", "focus=render-throughput", "```", "", "Observed stable behavior under bursty UI events; continue profiling for long-thread rendering regressions.", ].join("\n"); } function buildLargePerfThread(project: PerfPersistedProject, now: number): PerfPersistedThread { const threadId = `${project.id}-thread-large`; const createdAt = new Date(now - 1_500_000).toISOString(); const messages: PerfPersistedMessage[] = []; for (let exchangeIndex = 0; exchangeIndex < LARGE_THREAD_EXCHANGE_COUNT; exchangeIndex += 1) { const offsetMs = (LARGE_THREAD_EXCHANGE_COUNT - exchangeIndex) * 11_000; messages.push({ id: `${threadId}-user-${exchangeIndex + 1}`, role: "user", text: buildLargeThreadMessage(project.name, exchangeIndex, "user"), createdAt: new Date(now - offsetMs - 2_000).toISOString(), streaming: false, }); messages.push({ id: `${threadId}-assistant-${exchangeIndex + 1}`, role: "assistant", text: buildLargeThreadMessage(project.name, exchangeIndex, "assistant"), createdAt: new Date(now - offsetMs).toISOString(), streaming: false, }); } return { id: threadId, projectId: project.id, title: `${project.name} perf large thread`, model: "gpt-5-codex", terminalOpen: false, messages, createdAt, lastVisitedAt: new Date(now - 1_000_000).toISOString(), }; } 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; } } for (const project of projects) { threads.push(buildLargePerfThread(project, now)); } return { version: 7, runtimeMode: "approval-required", projects, threads, activeThreadId: threads[0]?.id ?? null, }; } async function seedRendererState( window: BrowserWindow, state: unknown, ): Promise<void> { const script = ` (() => { const key = "t3code:renderer-state:v7"; localStorage.setItem(key, JSON.stringify(${JSON.stringify(state)})); window.location.reload(); })(); `; await window.webContents.executeJavaScript(script, true); } async function readRendererPersistedThreadCount(window: BrowserWindow): Promise<number> { const script = ` (() => { const key = "t3code:renderer-state:v7"; const raw = localStorage.getItem(key); let threads = 0; if (raw) { try { const parsed = JSON.parse(raw); threads = Array.isArray(parsed?.threads) ? parsed.threads.length : 0; } catch { threads = -1; } } return threads; })(); `; return window.webContents.executeJavaScript(script, true); } async function runRendererPerfInteractions( window: BrowserWindow, benchmarkThreadIds: string[], ): Promise<RendererPerfInteractions> { const script = ` (async () => { const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const must = (condition, message) => { if (!condition) throw new Error(message); }; const nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => resolve())); const waitFor = async (predicate, timeoutMs, message) => { const deadline = performance.now() + timeoutMs; while (performance.now() < deadline) { if (predicate()) return; await nextFrame(); } 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 getThreadButtons = () => Array.from(document.querySelectorAll("[data-perf-thread-id]")).filter( (node) => node instanceof HTMLElement, ); const getPersistedStateStats = () => {